SDL_immdevice.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #if defined(SDL_PLATFORM_WINDOWS) && defined(HAVE_MMDEVICEAPI_H)
  20. #include "SDL_windows.h"
  21. #include "SDL_immdevice.h"
  22. #include "../../audio/SDL_sysaudio.h"
  23. #include <objbase.h> // For CLSIDFromString
  24. typedef struct SDL_IMMDevice_HandleData
  25. {
  26. LPWSTR immdevice_id;
  27. GUID directsound_guid;
  28. } SDL_IMMDevice_HandleData;
  29. static const ERole SDL_IMMDevice_role = eConsole; // !!! FIXME: should this be eMultimedia? Should be a hint?
  30. // This is global to the WASAPI target, to handle hotplug and default device lookup.
  31. static IMMDeviceEnumerator *enumerator = NULL;
  32. static SDL_IMMDevice_callbacks immcallbacks;
  33. // PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency.
  34. #ifdef PropVariantInit
  35. #undef PropVariantInit
  36. #endif
  37. #define PropVariantInit(p) SDL_zerop(p)
  38. // Some GUIDs we need to know without linking to libraries that aren't available before Vista.
  39. /* *INDENT-OFF* */ // clang-format off
  40. static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
  41. static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
  42. static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
  43. static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,{ 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } };
  44. static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd,{ 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 };
  45. static const PROPERTYKEY SDL_PKEY_AudioEngine_DeviceFormat = { { 0xf19f064d, 0x82c, 0x4e27,{ 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, } }, 0 };
  46. static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 4 };
  47. /* *INDENT-ON* */ // clang-format on
  48. static bool FindByDevIDCallback(SDL_AudioDevice *device, void *userdata)
  49. {
  50. LPCWSTR devid = (LPCWSTR)userdata;
  51. if (devid && device && device->handle) {
  52. const SDL_IMMDevice_HandleData *handle = (const SDL_IMMDevice_HandleData *)device->handle;
  53. if (handle->immdevice_id && SDL_wcscmp(handle->immdevice_id, devid) == 0) {
  54. return true;
  55. }
  56. }
  57. return false;
  58. }
  59. static SDL_AudioDevice *SDL_IMMDevice_FindByDevID(LPCWSTR devid)
  60. {
  61. return SDL_FindPhysicalAudioDeviceByCallback(FindByDevIDCallback, (void *) devid);
  62. }
  63. LPGUID SDL_IMMDevice_GetDirectSoundGUID(SDL_AudioDevice *device)
  64. {
  65. return (device && device->handle) ? &(((SDL_IMMDevice_HandleData *) device->handle)->directsound_guid) : NULL;
  66. }
  67. LPCWSTR SDL_IMMDevice_GetDevID(SDL_AudioDevice *device)
  68. {
  69. return (device && device->handle) ? ((const SDL_IMMDevice_HandleData *) device->handle)->immdevice_id : NULL;
  70. }
  71. static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid)
  72. {
  73. /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
  74. "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
  75. its own UIs, like Volume Control, etc. */
  76. IPropertyStore *props = NULL;
  77. *utf8dev = NULL;
  78. SDL_zerop(fmt);
  79. if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) {
  80. PROPVARIANT var;
  81. PropVariantInit(&var);
  82. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) {
  83. *utf8dev = WIN_StringToUTF8W(var.pwszVal);
  84. }
  85. PropVariantClear(&var);
  86. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEngine_DeviceFormat, &var))) {
  87. SDL_memcpy(fmt, var.blob.pBlobData, SDL_min(var.blob.cbSize, sizeof(WAVEFORMATEXTENSIBLE)));
  88. }
  89. PropVariantClear(&var);
  90. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEndpoint_GUID, &var))) {
  91. (void)CLSIDFromString(var.pwszVal, guid);
  92. }
  93. PropVariantClear(&var);
  94. IPropertyStore_Release(props);
  95. }
  96. }
  97. void SDL_IMMDevice_FreeDeviceHandle(SDL_AudioDevice *device)
  98. {
  99. if (device && device->handle) {
  100. SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *) device->handle;
  101. SDL_free(handle->immdevice_id);
  102. SDL_free(handle);
  103. device->handle = NULL;
  104. }
  105. }
  106. static SDL_AudioDevice *SDL_IMMDevice_Add(const bool recording, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid)
  107. {
  108. /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
  109. In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
  110. phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
  111. available and switch automatically. (!!! FIXME...?) */
  112. if (!devname) {
  113. return NULL;
  114. }
  115. // see if we already have this one first.
  116. SDL_AudioDevice *device = SDL_IMMDevice_FindByDevID(devid);
  117. if (device) {
  118. if (SDL_GetAtomicInt(&device->zombie)) {
  119. // whoa, it came back! This can happen if you unplug and replug USB headphones while we're still keeping the SDL object alive.
  120. // Kill this device's IMMDevice id; the device will go away when the app closes it, or maybe a new default device is chosen
  121. // (possibly this reconnected device), so we just want to make sure IMMDevice doesn't try to find the old device by the existing ID string.
  122. SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *) device->handle;
  123. SDL_free(handle->immdevice_id);
  124. handle->immdevice_id = NULL;
  125. device = NULL; // add a new device, below.
  126. }
  127. }
  128. if (!device) {
  129. // handle is freed by SDL_IMMDevice_FreeDeviceHandle!
  130. SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *)SDL_malloc(sizeof(SDL_IMMDevice_HandleData));
  131. if (!handle) {
  132. return NULL;
  133. }
  134. handle->immdevice_id = SDL_wcsdup(devid);
  135. if (!handle->immdevice_id) {
  136. SDL_free(handle);
  137. return NULL;
  138. }
  139. SDL_memcpy(&handle->directsound_guid, dsoundguid, sizeof(GUID));
  140. SDL_AudioSpec spec;
  141. SDL_zero(spec);
  142. spec.channels = (Uint8)fmt->Format.nChannels;
  143. spec.freq = fmt->Format.nSamplesPerSec;
  144. spec.format = SDL_WaveFormatExToSDLFormat((WAVEFORMATEX *)fmt);
  145. device = SDL_AddAudioDevice(recording, devname, &spec, handle);
  146. if (!device) {
  147. SDL_free(handle->immdevice_id);
  148. SDL_free(handle);
  149. }
  150. }
  151. return device;
  152. }
  153. /* We need a COM subclass of IMMNotificationClient for hotplug support, which is
  154. easy in C++, but we have to tapdance more to make work in C.
  155. Thanks to this page for coaching on how to make this work:
  156. https://www.codeproject.com/Articles/13601/COM-in-plain-C */
  157. typedef struct SDLMMNotificationClient
  158. {
  159. const IMMNotificationClientVtbl *lpVtbl;
  160. SDL_AtomicInt refcount;
  161. } SDLMMNotificationClient;
  162. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_QueryInterface(IMMNotificationClient *client, REFIID iid, void **ppv)
  163. {
  164. if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient))) {
  165. *ppv = client;
  166. client->lpVtbl->AddRef(client);
  167. return S_OK;
  168. }
  169. *ppv = NULL;
  170. return E_NOINTERFACE;
  171. }
  172. static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_AddRef(IMMNotificationClient *iclient)
  173. {
  174. SDLMMNotificationClient *client = (SDLMMNotificationClient *)iclient;
  175. return (ULONG)(SDL_AtomicIncRef(&client->refcount) + 1);
  176. }
  177. static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_Release(IMMNotificationClient *iclient)
  178. {
  179. // client is a static object; we don't ever free it.
  180. SDLMMNotificationClient *client = (SDLMMNotificationClient *)iclient;
  181. const ULONG rc = SDL_AtomicDecRef(&client->refcount);
  182. if (rc == 0) {
  183. SDL_SetAtomicInt(&client->refcount, 0); // uhh...
  184. return 0;
  185. }
  186. return rc - 1;
  187. }
  188. // These are the entry points called when WASAPI device endpoints change.
  189. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *iclient, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
  190. {
  191. if (role == SDL_IMMDevice_role) {
  192. immcallbacks.default_audio_device_changed(SDL_IMMDevice_FindByDevID(pwstrDeviceId));
  193. }
  194. return S_OK;
  195. }
  196. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId)
  197. {
  198. /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in
  199. OnDeviceStateChange, making that a better place to deal with device adds. More
  200. importantly: the first time you plug in a USB audio device, this callback will
  201. fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT).
  202. Plugging it back in won't fire this callback again. */
  203. return S_OK;
  204. }
  205. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId)
  206. {
  207. return S_OK; // See notes in OnDeviceAdded handler about why we ignore this.
  208. }
  209. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId, DWORD dwNewState)
  210. {
  211. IMMDevice *device = NULL;
  212. if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) {
  213. IMMEndpoint *endpoint = NULL;
  214. if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **)&endpoint))) {
  215. EDataFlow flow;
  216. if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
  217. const bool recording = (flow == eCapture);
  218. if (dwNewState == DEVICE_STATE_ACTIVE) {
  219. char *utf8dev;
  220. WAVEFORMATEXTENSIBLE fmt;
  221. GUID dsoundguid;
  222. GetMMDeviceInfo(device, &utf8dev, &fmt, &dsoundguid);
  223. if (utf8dev) {
  224. SDL_IMMDevice_Add(recording, utf8dev, &fmt, pwstrDeviceId, &dsoundguid);
  225. SDL_free(utf8dev);
  226. }
  227. } else {
  228. immcallbacks.audio_device_disconnected(SDL_IMMDevice_FindByDevID(pwstrDeviceId));
  229. }
  230. }
  231. IMMEndpoint_Release(endpoint);
  232. }
  233. IMMDevice_Release(device);
  234. }
  235. return S_OK;
  236. }
  237. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *client, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
  238. {
  239. return S_OK; // we don't care about these.
  240. }
  241. static const IMMNotificationClientVtbl notification_client_vtbl = {
  242. SDLMMNotificationClient_QueryInterface,
  243. SDLMMNotificationClient_AddRef,
  244. SDLMMNotificationClient_Release,
  245. SDLMMNotificationClient_OnDeviceStateChanged,
  246. SDLMMNotificationClient_OnDeviceAdded,
  247. SDLMMNotificationClient_OnDeviceRemoved,
  248. SDLMMNotificationClient_OnDefaultDeviceChanged,
  249. SDLMMNotificationClient_OnPropertyValueChanged
  250. };
  251. static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } };
  252. bool SDL_IMMDevice_Init(const SDL_IMMDevice_callbacks *callbacks)
  253. {
  254. HRESULT ret;
  255. // just skip the discussion with COM here.
  256. if (!WIN_IsWindowsVistaOrGreater()) {
  257. return SDL_SetError("IMMDevice support requires Windows Vista or later");
  258. }
  259. if (FAILED(WIN_CoInitialize())) {
  260. return SDL_SetError("IMMDevice: CoInitialize() failed");
  261. }
  262. ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID *)&enumerator);
  263. if (FAILED(ret)) {
  264. WIN_CoUninitialize();
  265. return WIN_SetErrorFromHRESULT("IMMDevice CoCreateInstance(MMDeviceEnumerator)", ret);
  266. }
  267. if (callbacks) {
  268. SDL_copyp(&immcallbacks, callbacks);
  269. } else {
  270. SDL_zero(immcallbacks);
  271. }
  272. if (!immcallbacks.audio_device_disconnected) {
  273. immcallbacks.audio_device_disconnected = SDL_AudioDeviceDisconnected;
  274. }
  275. if (!immcallbacks.default_audio_device_changed) {
  276. immcallbacks.default_audio_device_changed = SDL_DefaultAudioDeviceChanged;
  277. }
  278. return true;
  279. }
  280. void SDL_IMMDevice_Quit(void)
  281. {
  282. if (enumerator) {
  283. IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)&notification_client);
  284. IMMDeviceEnumerator_Release(enumerator);
  285. enumerator = NULL;
  286. }
  287. SDL_zero(immcallbacks);
  288. WIN_CoUninitialize();
  289. }
  290. bool SDL_IMMDevice_Get(SDL_AudioDevice *device, IMMDevice **immdevice, bool recording)
  291. {
  292. const Uint64 timeout = SDL_GetTicks() + 8000; // intel's audio drivers can fail for up to EIGHT SECONDS after a device is connected or we wake from sleep.
  293. SDL_assert(device != NULL);
  294. SDL_assert(immdevice != NULL);
  295. LPCWSTR devid = SDL_IMMDevice_GetDevID(device);
  296. SDL_assert(devid != NULL);
  297. HRESULT ret;
  298. while ((ret = IMMDeviceEnumerator_GetDevice(enumerator, devid, immdevice)) == E_NOTFOUND) {
  299. const Uint64 now = SDL_GetTicks();
  300. if (timeout > now) {
  301. const Uint64 ticksleft = timeout - now;
  302. SDL_Delay((Uint32)SDL_min(ticksleft, 300)); // wait awhile and try again.
  303. continue;
  304. }
  305. break;
  306. }
  307. if (!SUCCEEDED(ret)) {
  308. return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret);
  309. }
  310. return true;
  311. }
  312. static void EnumerateEndpointsForFlow(const bool recording, SDL_AudioDevice **default_device)
  313. {
  314. /* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
  315. ...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */
  316. IMMDeviceCollection *collection = NULL;
  317. if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, recording ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) {
  318. return;
  319. }
  320. UINT total = 0;
  321. if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) {
  322. IMMDeviceCollection_Release(collection);
  323. return;
  324. }
  325. LPWSTR default_devid = NULL;
  326. if (default_device) {
  327. IMMDevice *default_immdevice = NULL;
  328. const EDataFlow dataflow = recording ? eCapture : eRender;
  329. if (SUCCEEDED(IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_IMMDevice_role, &default_immdevice))) {
  330. LPWSTR devid = NULL;
  331. if (SUCCEEDED(IMMDevice_GetId(default_immdevice, &devid))) {
  332. default_devid = SDL_wcsdup(devid); // if this fails, oh well.
  333. CoTaskMemFree(devid);
  334. }
  335. IMMDevice_Release(default_immdevice);
  336. }
  337. }
  338. for (UINT i = 0; i < total; i++) {
  339. IMMDevice *immdevice = NULL;
  340. if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &immdevice))) {
  341. LPWSTR devid = NULL;
  342. if (SUCCEEDED(IMMDevice_GetId(immdevice, &devid))) {
  343. char *devname = NULL;
  344. WAVEFORMATEXTENSIBLE fmt;
  345. GUID dsoundguid;
  346. SDL_zero(fmt);
  347. SDL_zero(dsoundguid);
  348. GetMMDeviceInfo(immdevice, &devname, &fmt, &dsoundguid);
  349. if (devname) {
  350. SDL_AudioDevice *sdldevice = SDL_IMMDevice_Add(recording, devname, &fmt, devid, &dsoundguid);
  351. if (default_device && default_devid && SDL_wcscmp(default_devid, devid) == 0) {
  352. *default_device = sdldevice;
  353. }
  354. SDL_free(devname);
  355. }
  356. CoTaskMemFree(devid);
  357. }
  358. IMMDevice_Release(immdevice);
  359. }
  360. }
  361. SDL_free(default_devid);
  362. IMMDeviceCollection_Release(collection);
  363. }
  364. void SDL_IMMDevice_EnumerateEndpoints(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording)
  365. {
  366. EnumerateEndpointsForFlow(false, default_playback);
  367. EnumerateEndpointsForFlow(true, default_recording);
  368. // if this fails, we just won't get hotplug events. Carry on anyhow.
  369. IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)&notification_client);
  370. }
  371. #endif // defined(SDL_PLATFORM_WINDOWS) && defined(HAVE_MMDEVICEAPI_H)