SDL_wasapi.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2017 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 SDL_AUDIO_DRIVER_WASAPI
  20. #include "../../core/windows/SDL_windows.h"
  21. #include "SDL_audio.h"
  22. #include "SDL_timer.h"
  23. #include "../SDL_audio_c.h"
  24. #include "../SDL_sysaudio.h"
  25. #include "SDL_assert.h"
  26. #include "SDL_log.h"
  27. #define COBJMACROS
  28. #include <mmdeviceapi.h>
  29. #include <audioclient.h>
  30. #include "SDL_wasapi.h"
  31. static const ERole SDL_WASAPI_role = eConsole; /* !!! FIXME: should this be eMultimedia? Should be a hint? */
  32. /* This is global to the WASAPI target, to handle hotplug and default device lookup. */
  33. static IMMDeviceEnumerator *enumerator = NULL;
  34. /* these increment as default devices change. Opened default devices pick up changes in their threads. */
  35. static SDL_atomic_t default_playback_generation;
  36. static SDL_atomic_t default_capture_generation;
  37. /* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */
  38. typedef struct DevIdList
  39. {
  40. WCHAR *str;
  41. struct DevIdList *next;
  42. } DevIdList;
  43. static DevIdList *deviceid_list = NULL;
  44. /* handle to Avrt.dll--Vista and later!--for flagging the callback thread as "Pro Audio" (low latency). */
  45. #ifndef __WINRT__
  46. static HMODULE libavrt = NULL;
  47. #endif
  48. typedef HANDLE (WINAPI *pfnAvSetMmThreadCharacteristicsW)(LPWSTR,LPDWORD);
  49. typedef BOOL (WINAPI *pfnAvRevertMmThreadCharacteristics)(HANDLE);
  50. static pfnAvSetMmThreadCharacteristicsW pAvSetMmThreadCharacteristicsW = NULL;
  51. static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
  52. /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
  53. static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, { 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
  54. static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, { 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
  55. static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85, { 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
  56. static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089, { 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } };
  57. static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, { 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
  58. static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, { 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
  59. static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0, { 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
  60. static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  61. static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  62. static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 };
  63. /* PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. */
  64. #ifdef PropVariantInit
  65. #undef PropVariantInit
  66. #endif
  67. #define PropVariantInit(p) SDL_zerop(p)
  68. static void AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid);
  69. static void RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid);
  70. /* We need a COM subclass of IMMNotificationClient for hotplug support, which is
  71. easy in C++, but we have to tapdance more to make work in C.
  72. Thanks to this page for coaching on how to make this work:
  73. https://www.codeproject.com/Articles/13601/COM-in-plain-C */
  74. typedef struct SDLMMNotificationClient
  75. {
  76. const IMMNotificationClientVtbl *lpVtbl;
  77. SDL_atomic_t refcount;
  78. } SDLMMNotificationClient;
  79. static HRESULT STDMETHODCALLTYPE
  80. SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv)
  81. {
  82. if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient)))
  83. {
  84. *ppv = this;
  85. this->lpVtbl->AddRef(this);
  86. return S_OK;
  87. }
  88. *ppv = NULL;
  89. return E_NOINTERFACE;
  90. }
  91. static ULONG STDMETHODCALLTYPE
  92. SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis)
  93. {
  94. SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
  95. return (ULONG) (SDL_AtomicIncRef(&this->refcount) + 1);
  96. }
  97. static ULONG STDMETHODCALLTYPE
  98. SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
  99. {
  100. /* this is a static object; we don't ever free it. */
  101. SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
  102. const ULONG retval = SDL_AtomicDecRef(&this->refcount);
  103. if (retval == 0) {
  104. SDL_AtomicSet(&this->refcount, 0); /* uhh... */
  105. return 0;
  106. }
  107. return retval - 1;
  108. }
  109. /* These are the entry points called when WASAPI device endpoints change. */
  110. static HRESULT STDMETHODCALLTYPE
  111. SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
  112. {
  113. if (role != SDL_WASAPI_role) {
  114. return S_OK; /* ignore it. */
  115. }
  116. /* Increment the "generation," so opened devices will pick this up in their threads. */
  117. switch (flow) {
  118. case eRender:
  119. SDL_AtomicAdd(&default_playback_generation, 1);
  120. break;
  121. case eCapture:
  122. SDL_AtomicAdd(&default_capture_generation, 1);
  123. break;
  124. case eAll:
  125. SDL_AtomicAdd(&default_playback_generation, 1);
  126. SDL_AtomicAdd(&default_capture_generation, 1);
  127. break;
  128. default:
  129. SDL_assert(!"uhoh, unexpected OnDefaultDeviceChange flow!");
  130. break;
  131. }
  132. return S_OK;
  133. }
  134. static HRESULT STDMETHODCALLTYPE
  135. SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
  136. {
  137. /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in
  138. OnDeviceStateChange, making that a better place to deal with device adds. More
  139. importantly: the first time you plug in a USB audio device, this callback will
  140. fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT).
  141. Plugging it back in won't fire this callback again. */
  142. return S_OK;
  143. }
  144. static HRESULT STDMETHODCALLTYPE
  145. SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
  146. {
  147. /* See notes in OnDeviceAdded handler about why we ignore this. */
  148. return S_OK;
  149. }
  150. static HRESULT STDMETHODCALLTYPE
  151. SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState)
  152. {
  153. IMMDevice *device = NULL;
  154. if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) {
  155. IMMEndpoint *endpoint = NULL;
  156. if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **) &endpoint))) {
  157. EDataFlow flow;
  158. if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
  159. const SDL_bool iscapture = (flow == eCapture);
  160. if (dwNewState == DEVICE_STATE_ACTIVE) {
  161. AddWASAPIDevice(iscapture, device, pwstrDeviceId);
  162. } else {
  163. RemoveWASAPIDevice(iscapture, pwstrDeviceId);
  164. }
  165. }
  166. IMMEndpoint_Release(endpoint);
  167. }
  168. IMMDevice_Release(device);
  169. }
  170. return S_OK;
  171. }
  172. static HRESULT STDMETHODCALLTYPE
  173. SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
  174. {
  175. return S_OK; /* we don't care about these. */
  176. }
  177. static const IMMNotificationClientVtbl notification_client_vtbl = {
  178. SDLMMNotificationClient_QueryInterface,
  179. SDLMMNotificationClient_AddRef,
  180. SDLMMNotificationClient_Release,
  181. SDLMMNotificationClient_OnDeviceStateChanged,
  182. SDLMMNotificationClient_OnDeviceAdded,
  183. SDLMMNotificationClient_OnDeviceRemoved,
  184. SDLMMNotificationClient_OnDefaultDeviceChanged,
  185. SDLMMNotificationClient_OnPropertyValueChanged
  186. };
  187. static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } };
  188. static SDL_bool
  189. WStrEqual(const WCHAR *a, const WCHAR *b)
  190. {
  191. while (*a) {
  192. if (*a != *b) {
  193. return SDL_FALSE;
  194. }
  195. a++;
  196. b++;
  197. }
  198. return *b == 0;
  199. }
  200. static WCHAR *
  201. WStrDupe(const WCHAR *wstr)
  202. {
  203. const int len = (lstrlenW(wstr) + 1) * sizeof (WCHAR);
  204. WCHAR *retval = (WCHAR *) SDL_malloc(len);
  205. if (retval) {
  206. SDL_memcpy(retval, wstr, len);
  207. }
  208. return retval;
  209. }
  210. static void
  211. RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid)
  212. {
  213. DevIdList *i;
  214. DevIdList *next;
  215. DevIdList *prev = NULL;
  216. for (i = deviceid_list; i; i = next) {
  217. next = i->next;
  218. if (WStrEqual(i->str, devid)) {
  219. if (prev) {
  220. prev->next = next;
  221. } else {
  222. deviceid_list = next;
  223. }
  224. SDL_RemoveAudioDevice(iscapture, i->str);
  225. SDL_free(i->str);
  226. SDL_free(i);
  227. }
  228. prev = i;
  229. }
  230. }
  231. static void
  232. AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid)
  233. {
  234. IPropertyStore *props = NULL;
  235. char *utf8dev = NULL;
  236. DevIdList *devidlist;
  237. PROPVARIANT var;
  238. /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
  239. In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
  240. phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
  241. available and switch automatically. (!!! FIXME...?) */
  242. /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
  243. "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
  244. its own UIs, like Volume Control, etc. */
  245. /* see if we already have this one. */
  246. for (devidlist = deviceid_list; devidlist; devidlist = devidlist->next) {
  247. if (WStrEqual(devidlist->str, devid)) {
  248. return; /* we already have this. */
  249. }
  250. }
  251. devidlist = (DevIdList *) SDL_malloc(sizeof (*devidlist));
  252. if (!devidlist) {
  253. return; /* oh well. */
  254. }
  255. devid = WStrDupe(devid);
  256. if (!devid) {
  257. SDL_free(devidlist);
  258. return; /* oh well. */
  259. }
  260. devidlist->str = (WCHAR *) devid;
  261. devidlist->next = deviceid_list;
  262. deviceid_list = devidlist;
  263. if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) {
  264. PropVariantInit(&var);
  265. if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) {
  266. utf8dev = WIN_StringToUTF8(var.pwszVal);
  267. if (utf8dev) {
  268. SDL_AddAudioDevice(iscapture, utf8dev, (void *) devid);
  269. SDL_free(utf8dev);
  270. }
  271. }
  272. PropVariantClear(&var);
  273. IPropertyStore_Release(props);
  274. }
  275. }
  276. static void
  277. EnumerateEndpoints(const SDL_bool iscapture)
  278. {
  279. IMMDeviceCollection *collection = NULL;
  280. UINT i, total;
  281. /* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
  282. ...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */
  283. if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, iscapture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) {
  284. return;
  285. }
  286. if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) {
  287. IMMDeviceCollection_Release(collection);
  288. return;
  289. }
  290. for (i = 0; i < total; i++) {
  291. IMMDevice *device = NULL;
  292. if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &device))) {
  293. LPWSTR devid = NULL;
  294. if (SUCCEEDED(IMMDevice_GetId(device, &devid))) {
  295. AddWASAPIDevice(iscapture, device, devid);
  296. CoTaskMemFree(devid);
  297. }
  298. IMMDevice_Release(device);
  299. }
  300. }
  301. IMMDeviceCollection_Release(collection);
  302. }
  303. static void
  304. WASAPI_DetectDevices(void)
  305. {
  306. EnumerateEndpoints(SDL_FALSE); /* playback */
  307. EnumerateEndpoints(SDL_TRUE); /* capture */
  308. /* if this fails, we just won't get hotplug events. Carry on anyhow. */
  309. IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
  310. }
  311. static int
  312. WASAPI_GetPendingBytes(_THIS)
  313. {
  314. UINT32 frames = 0;
  315. /* it's okay to fail here; we'll deal with failures in the audio thread. */
  316. /* FIXME: need a lock around checking this->hidden->client */
  317. if (!this->hidden->client || FAILED(IAudioClient_GetCurrentPadding(this->hidden->client, &frames))) {
  318. return 0; /* oh well. */
  319. }
  320. return ((int) frames) * this->hidden->framesize;
  321. }
  322. static SDL_INLINE SDL_bool
  323. WasapiFailed(_THIS, const HRESULT err)
  324. {
  325. if (err == S_OK) {
  326. return SDL_FALSE;
  327. }
  328. if (err == AUDCLNT_E_DEVICE_INVALIDATED) {
  329. this->hidden->device_lost = SDL_TRUE;
  330. } else if (SDL_AtomicGet(&this->enabled)) {
  331. IAudioClient_Stop(this->hidden->client);
  332. SDL_OpenedAudioDeviceDisconnected(this);
  333. SDL_assert(!SDL_AtomicGet(&this->enabled));
  334. }
  335. return SDL_TRUE;
  336. }
  337. static int PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device);
  338. static void ReleaseWasapiDevice(_THIS);
  339. static SDL_bool
  340. RecoverWasapiDevice(_THIS)
  341. {
  342. const SDL_AudioSpec oldspec = this->spec;
  343. IMMDevice *device = NULL;
  344. HRESULT ret = S_OK;
  345. if (this->hidden->default_device_generation) {
  346. const EDataFlow dataflow = this->iscapture ? eCapture : eRender;
  347. ReleaseWasapiDevice(this); /* dump the lost device's handles. */
  348. this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ? &default_capture_generation : &default_playback_generation);
  349. ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
  350. if (FAILED(ret)) {
  351. return SDL_FALSE; /* can't find a new default device! */
  352. }
  353. } else {
  354. device = this->hidden->device;
  355. this->hidden->device = NULL; /* don't release this in ReleaseWasapiDevice(). */
  356. ReleaseWasapiDevice(this); /* dump the lost device's handles. */
  357. }
  358. SDL_assert(device != NULL);
  359. /* this can fail for lots of reasons, but the most likely is we had a
  360. non-default device that was disconnected, so we can't recover. Default
  361. devices try to reinitialize whatever the new default is, so it's more
  362. likely to carry on here, but this handles a non-default device that
  363. simply had its format changed in the Windows Control Panel. */
  364. if (PrepWasapiDevice(this, this->iscapture, device) == -1) {
  365. return SDL_FALSE;
  366. }
  367. /* Since WASAPI requires us to handle all audio conversion, and our
  368. device format might have changed, we might have to add/remove/change
  369. the audio stream that the higher level uses to convert data, so
  370. SDL keeps firing the callback as if nothing happened here. */
  371. if ( (this->callbackspec.channels == this->spec.channels) &&
  372. (this->callbackspec.format == this->spec.format) &&
  373. (this->callbackspec.freq == this->spec.freq) &&
  374. (this->callbackspec.samples == this->spec.samples) ) {
  375. /* no need to buffer/convert in an AudioStream! */
  376. SDL_FreeAudioStream(this->stream);
  377. this->stream = NULL;
  378. } else if ( (oldspec.channels == this->spec.channels) &&
  379. (oldspec.format == this->spec.format) &&
  380. (oldspec.freq == this->spec.freq) ) {
  381. /* The existing audio stream is okay to keep using. */
  382. } else {
  383. /* replace the audiostream for new format */
  384. SDL_FreeAudioStream(this->stream);
  385. if (this->iscapture) {
  386. this->stream = SDL_NewAudioStream(this->spec.format,
  387. this->spec.channels, this->spec.freq,
  388. this->callbackspec.format,
  389. this->callbackspec.channels,
  390. this->callbackspec.freq);
  391. } else {
  392. this->stream = SDL_NewAudioStream(this->callbackspec.format,
  393. this->callbackspec.channels,
  394. this->callbackspec.freq, this->spec.format,
  395. this->spec.channels, this->spec.freq);
  396. }
  397. if (!this->stream) {
  398. return SDL_FALSE;
  399. }
  400. }
  401. /* make sure our scratch buffer can cover the new device spec. */
  402. if (this->spec.size > this->work_buffer_len) {
  403. Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size);
  404. if (ptr == NULL) {
  405. SDL_OutOfMemory();
  406. return SDL_FALSE;
  407. }
  408. this->work_buffer = ptr;
  409. this->work_buffer_len = this->spec.size;
  410. }
  411. this->hidden->device_lost = SDL_FALSE;
  412. return SDL_TRUE; /* okay, carry on with new device details! */
  413. }
  414. static SDL_bool
  415. RecoverWasapiIfLost(_THIS)
  416. {
  417. const int generation = this->hidden->default_device_generation;
  418. SDL_bool lost = this->hidden->device_lost;
  419. if (!SDL_AtomicGet(&this->enabled)) {
  420. return SDL_FALSE; /* already failed. */
  421. }
  422. if (!lost && (generation > 0)) { /* is a default device? */
  423. const int newgen = SDL_AtomicGet(this->iscapture ? &default_capture_generation : &default_playback_generation);
  424. if (generation != newgen) { /* the desired default device was changed, jump over to it. */
  425. lost = SDL_TRUE;
  426. }
  427. }
  428. return lost ? RecoverWasapiDevice(this) : SDL_TRUE;
  429. }
  430. static Uint8 *
  431. WASAPI_GetDeviceBuf(_THIS)
  432. {
  433. /* get an endpoint buffer from WASAPI. */
  434. BYTE *buffer = NULL;
  435. while (RecoverWasapiIfLost(this)) {
  436. if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) {
  437. return (Uint8 *) buffer;
  438. }
  439. SDL_assert(buffer == NULL);
  440. }
  441. return (Uint8 *) buffer;
  442. }
  443. static void
  444. WASAPI_PlayDevice(_THIS)
  445. {
  446. /* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
  447. WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0));
  448. }
  449. static void
  450. WASAPI_WaitDevice(_THIS)
  451. {
  452. const UINT32 maxpadding = this->spec.samples;
  453. while (RecoverWasapiIfLost(this)) {
  454. UINT32 padding = 0;
  455. if (!WasapiFailed(this, IAudioClient_GetCurrentPadding(this->hidden->client, &padding))) {
  456. if (padding <= maxpadding) {
  457. break;
  458. }
  459. /* Sleep long enough for half the buffer to be free. */
  460. SDL_Delay(((padding - maxpadding) * 1000) / this->spec.freq);
  461. }
  462. }
  463. }
  464. static int
  465. WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
  466. {
  467. SDL_AudioStream *stream = this->hidden->capturestream;
  468. const int avail = SDL_AudioStreamAvailable(stream);
  469. if (avail > 0) {
  470. const int cpy = SDL_min(buflen, avail);
  471. SDL_AudioStreamGet(stream, buffer, cpy);
  472. return cpy;
  473. }
  474. while (RecoverWasapiIfLost(this)) {
  475. HRESULT ret;
  476. BYTE *ptr = NULL;
  477. UINT32 frames = 0;
  478. DWORD flags = 0;
  479. ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  480. if (ret != AUDCLNT_S_BUFFER_EMPTY) {
  481. WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
  482. }
  483. if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) {
  484. WASAPI_WaitDevice(this);
  485. } else if (ret == S_OK) {
  486. const int total = ((int) frames) * this->hidden->framesize;
  487. const int cpy = SDL_min(buflen, total);
  488. const int leftover = total - cpy;
  489. const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
  490. if (silent) {
  491. SDL_memset(buffer, this->spec.silence, cpy);
  492. } else {
  493. SDL_memcpy(buffer, ptr, cpy);
  494. }
  495. if (leftover > 0) {
  496. ptr += cpy;
  497. if (silent) {
  498. SDL_memset(ptr, this->spec.silence, leftover); /* I guess this is safe? */
  499. }
  500. if (SDL_AudioStreamPut(stream, ptr, leftover) == -1) {
  501. return -1; /* uhoh, out of memory, etc. Kill device. :( */
  502. }
  503. }
  504. ret = IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames);
  505. WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
  506. return cpy;
  507. }
  508. }
  509. return -1; /* unrecoverable error. */
  510. }
  511. static void
  512. WASAPI_FlushCapture(_THIS)
  513. {
  514. BYTE *ptr = NULL;
  515. UINT32 frames = 0;
  516. DWORD flags = 0;
  517. /* just read until we stop getting packets, throwing them away. */
  518. while (SDL_TRUE) {
  519. const HRESULT ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  520. if (ret == AUDCLNT_S_BUFFER_EMPTY) {
  521. break; /* no more buffered data; we're done. */
  522. } else if (WasapiFailed(this, ret)) {
  523. break; /* failed for some other reason, abort. */
  524. } else if (WasapiFailed(this, IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames))) {
  525. break; /* something broke. */
  526. }
  527. }
  528. SDL_AudioStreamClear(this->hidden->capturestream);
  529. }
  530. static void
  531. ReleaseWasapiDevice(_THIS)
  532. {
  533. if (this->hidden->client) {
  534. IAudioClient_Stop(this->hidden->client);
  535. this->hidden->client = NULL;
  536. }
  537. if (this->hidden->render) {
  538. IAudioRenderClient_Release(this->hidden->render);
  539. this->hidden->render = NULL;
  540. }
  541. if (this->hidden->capture) {
  542. IAudioCaptureClient_Release(this->hidden->capture);
  543. this->hidden->capture = NULL;
  544. }
  545. if (this->hidden->waveformat) {
  546. CoTaskMemFree(this->hidden->waveformat);
  547. this->hidden->waveformat = NULL;
  548. }
  549. if (this->hidden->device) {
  550. IMMDevice_Release(this->hidden->device);
  551. this->hidden->device = NULL;
  552. }
  553. if (this->hidden->capturestream) {
  554. SDL_FreeAudioStream(this->hidden->capturestream);
  555. this->hidden->capturestream = NULL;
  556. }
  557. }
  558. static void
  559. WASAPI_CloseDevice(_THIS)
  560. {
  561. /* don't touch this->hidden->task in here; it has to be reverted from
  562. our callback thread. We do that in WASAPI_ThreadDeinit().
  563. (likewise for this->hidden->coinitialized). */
  564. ReleaseWasapiDevice(this);
  565. SDL_free(this->hidden);
  566. }
  567. static int
  568. PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
  569. {
  570. /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
  571. !!! it will write into the kernel's audio buffer directly instead of
  572. !!! shared memory that a user-mode mixer then writes to the kernel with
  573. !!! everything else. Doing this means any other sound using this device will
  574. !!! stop playing, including the user's MP3 player and system notification
  575. !!! sounds. You'd probably need to release the device when the app isn't in
  576. !!! the foreground, to be a good citizen of the system. It's doable, but it's
  577. !!! more work and causes some annoyances, and I don't know what the latency
  578. !!! wins actually look like. Maybe add a hint to force exclusive mode at
  579. !!! some point. To be sure, defaulting to shared mode is the right thing to
  580. !!! do in any case. */
  581. const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
  582. UINT32 bufsize = 0; /* this is in sample frames, not samples, not bytes. */
  583. REFERENCE_TIME duration = 0;
  584. IAudioClient *client = NULL;
  585. IAudioRenderClient *render = NULL;
  586. IAudioCaptureClient *capture = NULL;
  587. WAVEFORMATEX *waveformat = NULL;
  588. SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
  589. SDL_AudioFormat wasapi_format = 0;
  590. SDL_bool valid_format = SDL_FALSE;
  591. HRESULT ret = S_OK;
  592. this->hidden->device = device;
  593. ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **) &client);
  594. if (FAILED(ret)) {
  595. return WIN_SetErrorFromHRESULT("WASAPI can't activate audio endpoint", ret);
  596. }
  597. SDL_assert(client != NULL);
  598. this->hidden->client = client;
  599. ret = IAudioClient_GetMixFormat(client, &waveformat);
  600. if (FAILED(ret)) {
  601. return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret);
  602. }
  603. SDL_assert(waveformat != NULL);
  604. this->hidden->waveformat = waveformat;
  605. /* WASAPI will not do any conversion on our behalf. Force channels and sample rate. */
  606. this->spec.channels = (Uint8) waveformat->nChannels;
  607. this->spec.freq = waveformat->nSamplesPerSec;
  608. /* Make sure we have a valid format that we can convert to whatever WASAPI wants. */
  609. if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
  610. wasapi_format = AUDIO_F32SYS;
  611. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
  612. wasapi_format = AUDIO_S16SYS;
  613. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
  614. wasapi_format = AUDIO_S32SYS;
  615. } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  616. const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *) waveformat;
  617. if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  618. wasapi_format = AUDIO_F32SYS;
  619. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
  620. wasapi_format = AUDIO_S16SYS;
  621. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  622. wasapi_format = AUDIO_S32SYS;
  623. }
  624. }
  625. while ((!valid_format) && (test_format)) {
  626. if (test_format == wasapi_format) {
  627. this->spec.format = test_format;
  628. valid_format = SDL_TRUE;
  629. break;
  630. }
  631. test_format = SDL_NextAudioFormat();
  632. }
  633. if (!valid_format) {
  634. return SDL_SetError("WASAPI: Unsupported audio format");
  635. }
  636. ret = IAudioClient_GetDevicePeriod(client, NULL, &duration);
  637. if (FAILED(ret)) {
  638. return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret);
  639. }
  640. ret = IAudioClient_Initialize(client, sharemode, 0, duration, sharemode == AUDCLNT_SHAREMODE_SHARED ? 0 : duration, waveformat, NULL);
  641. if (FAILED(ret)) {
  642. return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret);
  643. }
  644. ret = IAudioClient_GetBufferSize(client, &bufsize);
  645. if (FAILED(ret)) {
  646. return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret);
  647. }
  648. this->spec.samples = (Uint16) bufsize;
  649. if (!iscapture) {
  650. this->spec.samples /= 2; /* fill half of the DMA buffer on each run. */
  651. }
  652. /* Update the fragment size as size in bytes */
  653. SDL_CalculateAudioSpec(&this->spec);
  654. this->hidden->framesize = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
  655. if (iscapture) {
  656. this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
  657. if (!this->hidden->capturestream) {
  658. return -1; /* already set SDL_Error */
  659. }
  660. ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void**) &capture);
  661. if (FAILED(ret)) {
  662. return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
  663. }
  664. SDL_assert(capture != NULL);
  665. this->hidden->capture = capture;
  666. ret = IAudioClient_Start(client);
  667. if (FAILED(ret)) {
  668. return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret);
  669. }
  670. WASAPI_FlushCapture(this); /* MSDN says you should flush capture endpoint right after startup. */
  671. } else {
  672. ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void**) &render);
  673. if (FAILED(ret)) {
  674. return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
  675. }
  676. SDL_assert(render != NULL);
  677. this->hidden->render = render;
  678. ret = IAudioClient_Start(client);
  679. if (FAILED(ret)) {
  680. return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret);
  681. }
  682. }
  683. return 0; /* good to go. */
  684. }
  685. static int
  686. WASAPI_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
  687. {
  688. const SDL_bool is_default_device = (handle == NULL);
  689. IMMDevice *device = NULL;
  690. HRESULT ret = S_OK;
  691. /* Initialize all variables that we clean on shutdown */
  692. this->hidden = (struct SDL_PrivateAudioData *)
  693. SDL_malloc((sizeof *this->hidden));
  694. if (this->hidden == NULL) {
  695. return SDL_OutOfMemory();
  696. }
  697. SDL_zerop(this->hidden);
  698. if (is_default_device) {
  699. const EDataFlow dataflow = iscapture ? eCapture : eRender;
  700. this->hidden->default_device_generation = SDL_AtomicGet(iscapture ? &default_capture_generation : &default_playback_generation);
  701. ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
  702. } else {
  703. ret = IMMDeviceEnumerator_GetDevice(enumerator, (LPCWSTR) handle, &device);
  704. }
  705. if (FAILED(ret)) {
  706. return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret);
  707. }
  708. SDL_assert(device != NULL);
  709. return PrepWasapiDevice(this, iscapture, device);
  710. }
  711. static void
  712. WASAPI_ThreadInit(_THIS)
  713. {
  714. /* this thread uses COM. */
  715. if (SUCCEEDED(WIN_CoInitialize())) { /* can't report errors, hope it worked! */
  716. this->hidden->coinitialized = SDL_TRUE;
  717. }
  718. /* Set this thread to very high "Pro Audio" priority. */
  719. if (pAvSetMmThreadCharacteristicsW) {
  720. DWORD idx = 0;
  721. this->hidden->task = pAvSetMmThreadCharacteristicsW(TEXT("Pro Audio"), &idx);
  722. }
  723. }
  724. static void
  725. WASAPI_ThreadDeinit(_THIS)
  726. {
  727. /* Set this thread to very high "Pro Audio" priority. */
  728. if (this->hidden->task && pAvRevertMmThreadCharacteristics) {
  729. pAvRevertMmThreadCharacteristics(this->hidden->task);
  730. this->hidden->task = NULL;
  731. }
  732. if (this->hidden->coinitialized) {
  733. WIN_CoUninitialize();
  734. }
  735. }
  736. static void
  737. WASAPI_Deinitialize(void)
  738. {
  739. DevIdList *devidlist;
  740. DevIdList *next;
  741. if (enumerator) {
  742. IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
  743. IMMDeviceEnumerator_Release(enumerator);
  744. enumerator = NULL;
  745. }
  746. #ifndef __WINRT__
  747. if (libavrt) {
  748. FreeLibrary(libavrt);
  749. libavrt = NULL;
  750. }
  751. #endif
  752. pAvSetMmThreadCharacteristicsW = NULL;
  753. pAvRevertMmThreadCharacteristics = NULL;
  754. for (devidlist = deviceid_list; devidlist; devidlist = next) {
  755. next = devidlist->next;
  756. SDL_free(devidlist->str);
  757. SDL_free(devidlist);
  758. }
  759. deviceid_list = NULL;
  760. WIN_CoUninitialize();
  761. }
  762. static int
  763. WASAPI_Init(SDL_AudioDriverImpl * impl)
  764. {
  765. HRESULT ret;
  766. /* just skip the discussion with COM here. */
  767. if (!WIN_IsWindowsVistaOrGreater()) {
  768. SDL_SetError("WASAPI support requires Windows Vista or later");
  769. return 0;
  770. }
  771. SDL_AtomicSet(&default_playback_generation, 1);
  772. SDL_AtomicSet(&default_capture_generation, 1);
  773. if (FAILED(WIN_CoInitialize())) {
  774. SDL_SetError("WASAPI: CoInitialize() failed");
  775. return 0;
  776. }
  777. ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID) &enumerator);
  778. if (FAILED(ret)) {
  779. WIN_CoUninitialize();
  780. WIN_SetErrorFromHRESULT("WASAPI CoCreateInstance(MMDeviceEnumerator)", ret);
  781. return 0; /* oh well. */
  782. }
  783. #ifdef __WINRT__
  784. pAvSetMmThreadCharacteristicsW = AvSetMmThreadCharacteristicsW;
  785. pAvRevertMmThreadCharacteristics = AvRevertMmThreadCharacteristics;
  786. #else
  787. libavrt = LoadLibraryW(L"avrt.dll"); /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */
  788. if (libavrt) {
  789. pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW) GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW");
  790. pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics) GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics");
  791. }
  792. #endif
  793. /* Set the function pointers */
  794. impl->DetectDevices = WASAPI_DetectDevices;
  795. impl->ThreadInit = WASAPI_ThreadInit;
  796. impl->ThreadDeinit = WASAPI_ThreadDeinit;
  797. impl->OpenDevice = WASAPI_OpenDevice;
  798. impl->PlayDevice = WASAPI_PlayDevice;
  799. impl->WaitDevice = WASAPI_WaitDevice;
  800. impl->GetPendingBytes = WASAPI_GetPendingBytes;
  801. impl->GetDeviceBuf = WASAPI_GetDeviceBuf;
  802. impl->CaptureFromDevice = WASAPI_CaptureFromDevice;
  803. impl->FlushCapture = WASAPI_FlushCapture;
  804. impl->CloseDevice = WASAPI_CloseDevice;
  805. impl->Deinitialize = WASAPI_Deinitialize;
  806. impl->HasCaptureSupport = 1;
  807. return 1; /* this audio target is available. */
  808. }
  809. AudioBootStrap WASAPI_bootstrap = {
  810. "wasapi", "WASAPI", WASAPI_Init, 0
  811. };
  812. #endif /* SDL_AUDIO_DRIVER_WASAPI */
  813. /* vi: set ts=4 sw=4 expandtab: */