SDL_immdevice.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  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(__WIN32__) || defined(__GDK__)) && 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. /* PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. */
  33. #ifdef PropVariantInit
  34. #undef PropVariantInit
  35. #endif
  36. #define PropVariantInit(p) SDL_zerop(p)
  37. /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
  38. /* *INDENT-OFF* */ /* clang-format off */
  39. static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
  40. static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
  41. static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
  42. static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,{ 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } };
  43. static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd,{ 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 };
  44. static const PROPERTYKEY SDL_PKEY_AudioEngine_DeviceFormat = { { 0xf19f064d, 0x82c, 0x4e27,{ 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, } }, 0 };
  45. static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 4 };
  46. /* *INDENT-ON* */ /* clang-format on */
  47. static SDL_bool FindByDevIDCallback(SDL_AudioDevice *device, void *userdata)
  48. {
  49. LPCWSTR devid = (LPCWSTR)userdata;
  50. if (devid && device && device->handle) {
  51. const SDL_IMMDevice_HandleData *handle = (const SDL_IMMDevice_HandleData *)device->handle;
  52. if (handle->immdevice_id && SDL_wcscmp(handle->immdevice_id, devid) == 0) {
  53. return SDL_TRUE;
  54. }
  55. }
  56. return SDL_FALSE;
  57. }
  58. static SDL_AudioDevice *SDL_IMMDevice_FindByDevID(LPCWSTR devid)
  59. {
  60. return SDL_FindPhysicalAudioDeviceByCallback(FindByDevIDCallback, (void *) devid);
  61. }
  62. LPGUID SDL_IMMDevice_GetDirectSoundGUID(SDL_AudioDevice *device)
  63. {
  64. return (device && device->handle) ? &(((SDL_IMMDevice_HandleData *) device->handle)->directsound_guid) : NULL;
  65. }
  66. LPCWSTR SDL_IMMDevice_GetDevID(SDL_AudioDevice *device)
  67. {
  68. return (device && device->handle) ? ((const SDL_IMMDevice_HandleData *) device->handle)->immdevice_id : NULL;
  69. }
  70. static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid)
  71. {
  72. /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
  73. "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
  74. its own UIs, like Volume Control, etc. */
  75. IPropertyStore *props = NULL;
  76. *utf8dev = NULL;
  77. SDL_zerop(fmt);
  78. if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) {
  79. PROPVARIANT var;
  80. PropVariantInit(&var);
  81. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) {
  82. *utf8dev = WIN_StringToUTF8W(var.pwszVal);
  83. }
  84. PropVariantClear(&var);
  85. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEngine_DeviceFormat, &var))) {
  86. SDL_memcpy(fmt, var.blob.pBlobData, SDL_min(var.blob.cbSize, sizeof(WAVEFORMATEXTENSIBLE)));
  87. }
  88. PropVariantClear(&var);
  89. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEndpoint_GUID, &var))) {
  90. CLSIDFromString(var.pwszVal, guid);
  91. }
  92. PropVariantClear(&var);
  93. IPropertyStore_Release(props);
  94. }
  95. }
  96. void SDL_IMMDevice_FreeDeviceHandle(SDL_AudioDevice *device)
  97. {
  98. if (device && device->handle) {
  99. SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *) device->handle;
  100. SDL_free(handle->immdevice_id);
  101. SDL_free(handle);
  102. device->handle = NULL;
  103. }
  104. }
  105. static SDL_AudioDevice *SDL_IMMDevice_Add(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid)
  106. {
  107. /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
  108. In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
  109. phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
  110. available and switch automatically. (!!! FIXME...?) */
  111. if (!devname) {
  112. return NULL;
  113. }
  114. // see if we already have this one first.
  115. SDL_AudioDevice *device = SDL_IMMDevice_FindByDevID(devid);
  116. if (!device) {
  117. // handle is freed by SDL_IMMDevice_FreeDeviceHandle!
  118. SDL_IMMDevice_HandleData *handle = SDL_malloc(sizeof(SDL_IMMDevice_HandleData));
  119. if (!handle) {
  120. SDL_OutOfMemory();
  121. return NULL;
  122. }
  123. handle->immdevice_id = SDL_wcsdup(devid);
  124. if (!handle->immdevice_id) {
  125. SDL_OutOfMemory();
  126. SDL_free(handle);
  127. return NULL;
  128. }
  129. SDL_memcpy(&handle->directsound_guid, dsoundguid, sizeof(GUID));
  130. SDL_AudioSpec spec;
  131. SDL_zero(spec);
  132. spec.channels = (Uint8)fmt->Format.nChannels;
  133. spec.freq = fmt->Format.nSamplesPerSec;
  134. spec.format = SDL_WaveFormatExToSDLFormat((WAVEFORMATEX *)fmt);
  135. device = SDL_AddAudioDevice(iscapture, devname, &spec, handle);
  136. }
  137. return device;
  138. }
  139. /* We need a COM subclass of IMMNotificationClient for hotplug support, which is
  140. easy in C++, but we have to tapdance more to make work in C.
  141. Thanks to this page for coaching on how to make this work:
  142. https://www.codeproject.com/Articles/13601/COM-in-plain-C */
  143. typedef struct SDLMMNotificationClient
  144. {
  145. const IMMNotificationClientVtbl *lpVtbl;
  146. SDL_AtomicInt refcount;
  147. } SDLMMNotificationClient;
  148. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_QueryInterface(IMMNotificationClient *client, REFIID iid, void **ppv)
  149. {
  150. if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient))) {
  151. *ppv = client;
  152. client->lpVtbl->AddRef(client);
  153. return S_OK;
  154. }
  155. *ppv = NULL;
  156. return E_NOINTERFACE;
  157. }
  158. static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_AddRef(IMMNotificationClient *iclient)
  159. {
  160. SDLMMNotificationClient *client = (SDLMMNotificationClient *)iclient;
  161. return (ULONG)(SDL_AtomicIncRef(&client->refcount) + 1);
  162. }
  163. static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_Release(IMMNotificationClient *iclient)
  164. {
  165. /* client is a static object; we don't ever free it. */
  166. SDLMMNotificationClient *client = (SDLMMNotificationClient *)iclient;
  167. const ULONG retval = SDL_AtomicDecRef(&client->refcount);
  168. if (retval == 0) {
  169. SDL_AtomicSet(&client->refcount, 0); /* uhh... */
  170. return 0;
  171. }
  172. return retval - 1;
  173. }
  174. // These are the entry points called when WASAPI device endpoints change.
  175. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *iclient, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
  176. {
  177. if (role == SDL_IMMDevice_role) {
  178. SDL_DefaultAudioDeviceChanged(SDL_IMMDevice_FindByDevID(pwstrDeviceId));
  179. }
  180. return S_OK;
  181. }
  182. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId)
  183. {
  184. /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in
  185. OnDeviceStateChange, making that a better place to deal with device adds. More
  186. importantly: the first time you plug in a USB audio device, this callback will
  187. fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT).
  188. Plugging it back in won't fire this callback again. */
  189. return S_OK;
  190. }
  191. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId)
  192. {
  193. return S_OK; // See notes in OnDeviceAdded handler about why we ignore this.
  194. }
  195. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *iclient, LPCWSTR pwstrDeviceId, DWORD dwNewState)
  196. {
  197. IMMDevice *device = NULL;
  198. if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) {
  199. IMMEndpoint *endpoint = NULL;
  200. if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **)&endpoint))) {
  201. EDataFlow flow;
  202. if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
  203. const SDL_bool iscapture = (flow == eCapture);
  204. if (dwNewState == DEVICE_STATE_ACTIVE) {
  205. char *utf8dev;
  206. WAVEFORMATEXTENSIBLE fmt;
  207. GUID dsoundguid;
  208. GetMMDeviceInfo(device, &utf8dev, &fmt, &dsoundguid);
  209. if (utf8dev) {
  210. SDL_IMMDevice_Add(iscapture, utf8dev, &fmt, pwstrDeviceId, &dsoundguid);
  211. SDL_free(utf8dev);
  212. }
  213. } else {
  214. SDL_AudioDeviceDisconnected(SDL_IMMDevice_FindByDevID(pwstrDeviceId));
  215. }
  216. }
  217. IMMEndpoint_Release(endpoint);
  218. }
  219. IMMDevice_Release(device);
  220. }
  221. return S_OK;
  222. }
  223. static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *client, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
  224. {
  225. return S_OK; // we don't care about these.
  226. }
  227. static const IMMNotificationClientVtbl notification_client_vtbl = {
  228. SDLMMNotificationClient_QueryInterface,
  229. SDLMMNotificationClient_AddRef,
  230. SDLMMNotificationClient_Release,
  231. SDLMMNotificationClient_OnDeviceStateChanged,
  232. SDLMMNotificationClient_OnDeviceAdded,
  233. SDLMMNotificationClient_OnDeviceRemoved,
  234. SDLMMNotificationClient_OnDefaultDeviceChanged,
  235. SDLMMNotificationClient_OnPropertyValueChanged
  236. };
  237. static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } };
  238. int SDL_IMMDevice_Init(void)
  239. {
  240. HRESULT ret;
  241. /* just skip the discussion with COM here. */
  242. if (!WIN_IsWindowsVistaOrGreater()) {
  243. return SDL_SetError("IMMDevice support requires Windows Vista or later");
  244. }
  245. if (FAILED(WIN_CoInitialize())) {
  246. return SDL_SetError("IMMDevice: CoInitialize() failed");
  247. }
  248. ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID *)&enumerator);
  249. if (FAILED(ret)) {
  250. WIN_CoUninitialize();
  251. return WIN_SetErrorFromHRESULT("IMMDevice CoCreateInstance(MMDeviceEnumerator)", ret);
  252. }
  253. return 0;
  254. }
  255. void SDL_IMMDevice_Quit(void)
  256. {
  257. if (enumerator) {
  258. IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)&notification_client);
  259. IMMDeviceEnumerator_Release(enumerator);
  260. enumerator = NULL;
  261. }
  262. WIN_CoUninitialize();
  263. }
  264. int SDL_IMMDevice_Get(SDL_AudioDevice *device, IMMDevice **immdevice, SDL_bool iscapture)
  265. {
  266. 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. */
  267. SDL_assert(device != NULL);
  268. SDL_assert(immdevice != NULL);
  269. LPCWSTR devid = SDL_IMMDevice_GetDevID(device);
  270. SDL_assert(devid != NULL);
  271. HRESULT ret;
  272. while ((ret = IMMDeviceEnumerator_GetDevice(enumerator, devid, immdevice)) == E_NOTFOUND) {
  273. const Uint64 now = SDL_GetTicks();
  274. if (timeout > now) {
  275. const Uint64 ticksleft = timeout - now;
  276. SDL_Delay((Uint32)SDL_min(ticksleft, 300)); /* wait awhile and try again. */
  277. continue;
  278. }
  279. break;
  280. }
  281. return SUCCEEDED(ret) ? 0 : WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret);
  282. }
  283. static void EnumerateEndpointsForFlow(const SDL_bool iscapture, SDL_AudioDevice **default_device)
  284. {
  285. /* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
  286. ...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */
  287. IMMDeviceCollection *collection = NULL;
  288. if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, iscapture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) {
  289. return;
  290. }
  291. UINT total = 0;
  292. if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) {
  293. IMMDeviceCollection_Release(collection);
  294. return;
  295. }
  296. LPWSTR default_devid = NULL;
  297. if (default_device) {
  298. IMMDevice *default_immdevice = NULL;
  299. const EDataFlow dataflow = iscapture ? eCapture : eRender;
  300. if (SUCCEEDED(IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_IMMDevice_role, &default_immdevice))) {
  301. LPWSTR devid = NULL;
  302. if (SUCCEEDED(IMMDevice_GetId(default_immdevice, &devid))) {
  303. default_devid = SDL_wcsdup(devid); // if this fails, oh well.
  304. CoTaskMemFree(devid);
  305. }
  306. IMMDevice_Release(default_immdevice);
  307. }
  308. }
  309. for (UINT i = 0; i < total; i++) {
  310. IMMDevice *immdevice = NULL;
  311. if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &immdevice))) {
  312. LPWSTR devid = NULL;
  313. if (SUCCEEDED(IMMDevice_GetId(immdevice, &devid))) {
  314. char *devname = NULL;
  315. WAVEFORMATEXTENSIBLE fmt;
  316. GUID dsoundguid;
  317. SDL_zero(fmt);
  318. SDL_zero(dsoundguid);
  319. GetMMDeviceInfo(immdevice, &devname, &fmt, &dsoundguid);
  320. if (devname) {
  321. SDL_AudioDevice *sdldevice = SDL_IMMDevice_Add(iscapture, devname, &fmt, devid, &dsoundguid);
  322. if (default_device && default_devid && SDL_wcscmp(default_devid, devid) == 0) {
  323. *default_device = sdldevice;
  324. }
  325. SDL_free(devname);
  326. }
  327. CoTaskMemFree(devid);
  328. }
  329. IMMDevice_Release(immdevice);
  330. }
  331. }
  332. SDL_free(default_devid);
  333. IMMDeviceCollection_Release(collection);
  334. }
  335. void SDL_IMMDevice_EnumerateEndpoints(SDL_AudioDevice **default_output, SDL_AudioDevice **default_capture)
  336. {
  337. EnumerateEndpointsForFlow(SDL_FALSE, default_output); /* playback */
  338. EnumerateEndpointsForFlow(SDL_TRUE, default_capture); /* capture */
  339. /* if this fails, we just won't get hotplug events. Carry on anyhow. */
  340. IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)&notification_client);
  341. }
  342. #endif /* (defined(__WIN32__) || defined(__GDK__)) && defined(HAVE_MMDEVICEAPI_H) */