SDL_wasapi.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 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. #ifdef SDL_AUDIO_DRIVER_WASAPI
  20. #include "../../core/windows/SDL_windows.h"
  21. #include "../../core/windows/SDL_immdevice.h"
  22. #include "../../thread/SDL_systhread.h"
  23. #include "../SDL_audio_c.h"
  24. #include "../SDL_sysaudio.h"
  25. #define COBJMACROS
  26. #include <audioclient.h>
  27. #include "SDL_wasapi.h"
  28. // These constants aren't available in older SDKs
  29. #ifndef AUDCLNT_STREAMFLAGS_RATEADJUST
  30. #define AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
  31. #endif
  32. #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
  33. #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  34. #endif
  35. #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
  36. #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  37. #endif
  38. // Some GUIDs we need to know without linking to libraries that aren't available before Vista.
  39. static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, { 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
  40. static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0, { 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
  41. // WASAPI is _really_ particular about various things happening on the same thread, for COM and such,
  42. // so we proxy various stuff to a single background thread to manage.
  43. typedef struct ManagementThreadPendingTask
  44. {
  45. ManagementThreadTask fn;
  46. void *userdata;
  47. int result;
  48. SDL_Semaphore *task_complete_sem;
  49. char *errorstr;
  50. struct ManagementThreadPendingTask *next;
  51. } ManagementThreadPendingTask;
  52. static SDL_Thread *ManagementThread = NULL;
  53. static ManagementThreadPendingTask *ManagementThreadPendingTasks = NULL;
  54. static SDL_Mutex *ManagementThreadLock = NULL;
  55. static SDL_Condition *ManagementThreadCondition = NULL;
  56. static SDL_AtomicInt ManagementThreadShutdown;
  57. static void ManagementThreadMainloop(void)
  58. {
  59. SDL_LockMutex(ManagementThreadLock);
  60. ManagementThreadPendingTask *task;
  61. while (((task = SDL_AtomicGetPtr((void **) &ManagementThreadPendingTasks)) != NULL) || !SDL_AtomicGet(&ManagementThreadShutdown)) {
  62. if (!task) {
  63. SDL_WaitCondition(ManagementThreadCondition, ManagementThreadLock); // block until there's something to do.
  64. } else {
  65. SDL_AtomicSetPtr((void **) &ManagementThreadPendingTasks, task->next); // take task off the pending list.
  66. SDL_UnlockMutex(ManagementThreadLock); // let other things add to the list while we chew on this task.
  67. task->result = task->fn(task->userdata); // run this task.
  68. if (task->task_complete_sem) { // something waiting on result?
  69. task->errorstr = SDL_strdup(SDL_GetError());
  70. SDL_PostSemaphore(task->task_complete_sem);
  71. } else { // nothing waiting, we're done, free it.
  72. SDL_free(task);
  73. }
  74. SDL_LockMutex(ManagementThreadLock); // regrab the lock so we can get the next task; if nothing to do, we'll release the lock in SDL_WaitCondition.
  75. }
  76. }
  77. SDL_UnlockMutex(ManagementThreadLock); // told to shut down and out of tasks, let go of the lock and return.
  78. }
  79. int WASAPI_ProxyToManagementThread(ManagementThreadTask task, void *userdata, int *wait_on_result)
  80. {
  81. // We want to block for a result, but we are already running from the management thread! Just run the task now so we don't deadlock.
  82. if ((wait_on_result != NULL) && (SDL_ThreadID() == SDL_GetThreadID(ManagementThread))) {
  83. *wait_on_result = task(userdata);
  84. return 0; // completed!
  85. }
  86. if (SDL_AtomicGet(&ManagementThreadShutdown)) {
  87. return SDL_SetError("Can't add task, we're shutting down");
  88. }
  89. ManagementThreadPendingTask *pending = SDL_calloc(1, sizeof(ManagementThreadPendingTask));
  90. if (!pending) {
  91. return SDL_OutOfMemory();
  92. }
  93. pending->fn = task;
  94. pending->userdata = userdata;
  95. if (wait_on_result) {
  96. pending->task_complete_sem = SDL_CreateSemaphore(0);
  97. if (!pending->task_complete_sem) {
  98. SDL_free(pending);
  99. return -1;
  100. }
  101. }
  102. pending->next = NULL;
  103. SDL_LockMutex(ManagementThreadLock);
  104. // add to end of task list.
  105. ManagementThreadPendingTask *prev = NULL;
  106. for (ManagementThreadPendingTask *i = SDL_AtomicGetPtr((void **) &ManagementThreadPendingTasks); i != NULL; i = i->next) {
  107. prev = i;
  108. }
  109. if (prev != NULL) {
  110. prev->next = pending;
  111. } else {
  112. SDL_AtomicSetPtr((void **) &ManagementThreadPendingTasks, pending);
  113. }
  114. // task is added to the end of the pending list, let management thread rip!
  115. SDL_SignalCondition(ManagementThreadCondition);
  116. SDL_UnlockMutex(ManagementThreadLock);
  117. if (wait_on_result) {
  118. SDL_WaitSemaphore(pending->task_complete_sem);
  119. SDL_DestroySemaphore(pending->task_complete_sem);
  120. *wait_on_result = pending->result;
  121. if (pending->errorstr) {
  122. SDL_SetError("%s", pending->errorstr);
  123. SDL_free(pending->errorstr);
  124. }
  125. SDL_free(pending);
  126. }
  127. return 0; // successfully added (and possibly executed)!
  128. }
  129. static int ManagementThreadPrepare(void)
  130. {
  131. if (WASAPI_PlatformInit() == -1) {
  132. return -1;
  133. }
  134. ManagementThreadLock = SDL_CreateMutex();
  135. if (!ManagementThreadLock) {
  136. WASAPI_PlatformDeinit();
  137. return -1;
  138. }
  139. ManagementThreadCondition = SDL_CreateCondition();
  140. if (!ManagementThreadCondition) {
  141. SDL_DestroyMutex(ManagementThreadLock);
  142. ManagementThreadLock = NULL;
  143. WASAPI_PlatformDeinit();
  144. return -1;
  145. }
  146. return 0;
  147. }
  148. typedef struct
  149. {
  150. char *errorstr;
  151. SDL_Semaphore *ready_sem;
  152. } ManagementThreadEntryData;
  153. static int ManagementThreadEntry(void *userdata)
  154. {
  155. ManagementThreadEntryData *data = (ManagementThreadEntryData *)userdata;
  156. if (ManagementThreadPrepare() < 0) {
  157. data->errorstr = SDL_strdup(SDL_GetError());
  158. SDL_PostSemaphore(data->ready_sem); // unblock calling thread.
  159. return 0;
  160. }
  161. SDL_PostSemaphore(data->ready_sem); // unblock calling thread.
  162. ManagementThreadMainloop();
  163. WASAPI_PlatformDeinit();
  164. return 0;
  165. }
  166. static int InitManagementThread(void)
  167. {
  168. ManagementThreadEntryData mgmtdata;
  169. SDL_zero(mgmtdata);
  170. mgmtdata.ready_sem = SDL_CreateSemaphore(0);
  171. if (!mgmtdata.ready_sem) {
  172. return -1;
  173. }
  174. SDL_AtomicSetPtr((void **) &ManagementThreadPendingTasks, NULL);
  175. SDL_AtomicSet(&ManagementThreadShutdown, 0);
  176. ManagementThread = SDL_CreateThreadInternal(ManagementThreadEntry, "SDLWASAPIMgmt", 256 * 1024, &mgmtdata); // !!! FIXME: maybe even smaller stack size?
  177. if (!ManagementThread) {
  178. return -1;
  179. }
  180. SDL_WaitSemaphore(mgmtdata.ready_sem);
  181. SDL_DestroySemaphore(mgmtdata.ready_sem);
  182. if (mgmtdata.errorstr) {
  183. SDL_WaitThread(ManagementThread, NULL);
  184. ManagementThread = NULL;
  185. SDL_SetError("%s", mgmtdata.errorstr);
  186. SDL_free(mgmtdata.errorstr);
  187. return -1;
  188. }
  189. return 0;
  190. }
  191. static void DeinitManagementThread(void)
  192. {
  193. if (ManagementThread) {
  194. SDL_AtomicSet(&ManagementThreadShutdown, 1);
  195. SDL_LockMutex(ManagementThreadLock);
  196. SDL_SignalCondition(ManagementThreadCondition);
  197. SDL_UnlockMutex(ManagementThreadLock);
  198. SDL_WaitThread(ManagementThread, NULL);
  199. ManagementThread = NULL;
  200. }
  201. SDL_assert(SDL_AtomicGetPtr((void **) &ManagementThreadPendingTasks) == NULL);
  202. SDL_DestroyCondition(ManagementThreadCondition);
  203. SDL_DestroyMutex(ManagementThreadLock);
  204. ManagementThreadCondition = NULL;
  205. ManagementThreadLock = NULL;
  206. SDL_AtomicSet(&ManagementThreadShutdown, 0);
  207. }
  208. typedef struct
  209. {
  210. SDL_AudioDevice **default_output;
  211. SDL_AudioDevice **default_capture;
  212. } mgmtthrtask_DetectDevicesData;
  213. static int mgmtthrtask_DetectDevices(void *userdata)
  214. {
  215. mgmtthrtask_DetectDevicesData *data = (mgmtthrtask_DetectDevicesData *)userdata;
  216. WASAPI_EnumerateEndpoints(data->default_output, data->default_capture);
  217. return 0;
  218. }
  219. static void WASAPI_DetectDevices(SDL_AudioDevice **default_output, SDL_AudioDevice **default_capture)
  220. {
  221. int rc;
  222. // this blocks because it needs to finish before the audio subsystem inits
  223. mgmtthrtask_DetectDevicesData data = { default_output, default_capture };
  224. WASAPI_ProxyToManagementThread(mgmtthrtask_DetectDevices, &data, &rc);
  225. }
  226. static int mgmtthrtask_DisconnectDevice(void *userdata)
  227. {
  228. SDL_AudioDeviceDisconnected((SDL_AudioDevice *)userdata);
  229. return 0;
  230. }
  231. void WASAPI_DisconnectDevice(SDL_AudioDevice *device)
  232. {
  233. int rc; // block on this; don't disconnect while holding the device lock!
  234. WASAPI_ProxyToManagementThread(mgmtthrtask_DisconnectDevice, device, &rc);
  235. }
  236. static SDL_bool WasapiFailed(SDL_AudioDevice *device, const HRESULT err)
  237. {
  238. if (err == S_OK) {
  239. return SDL_FALSE;
  240. } else if (err == AUDCLNT_E_DEVICE_INVALIDATED) {
  241. device->hidden->device_lost = SDL_TRUE;
  242. } else {
  243. device->hidden->device_dead = SDL_TRUE;
  244. }
  245. return SDL_TRUE;
  246. }
  247. static int mgmtthrtask_ReleaseCaptureClient(void *userdata)
  248. {
  249. IAudioCaptureClient_Release((IAudioCaptureClient *)userdata);
  250. return 0;
  251. }
  252. static int mgmtthrtask_ReleaseRenderClient(void *userdata)
  253. {
  254. IAudioRenderClient_Release((IAudioRenderClient *)userdata);
  255. return 0;
  256. }
  257. static int mgmtthrtask_ResetWasapiDevice(void *userdata)
  258. {
  259. SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
  260. if (!device || !device->hidden) {
  261. return 0;
  262. }
  263. if (device->hidden->client) {
  264. IAudioClient_Stop(device->hidden->client);
  265. IAudioClient_Release(device->hidden->client);
  266. device->hidden->client = NULL;
  267. }
  268. if (device->hidden->render) {
  269. // this is silly, but this will block indefinitely if you call it from SDLMMNotificationClient_OnDefaultDeviceChanged, so
  270. // proxy this to the management thread to be released later.
  271. WASAPI_ProxyToManagementThread(mgmtthrtask_ReleaseRenderClient, device->hidden->render, NULL);
  272. device->hidden->render = NULL;
  273. }
  274. if (device->hidden->capture) {
  275. // this is silly, but this will block indefinitely if you call it from SDLMMNotificationClient_OnDefaultDeviceChanged, so
  276. // proxy this to the management thread to be released later.
  277. WASAPI_ProxyToManagementThread(mgmtthrtask_ReleaseCaptureClient, device->hidden->capture, NULL);
  278. device->hidden->capture = NULL;
  279. }
  280. if (device->hidden->waveformat) {
  281. CoTaskMemFree(device->hidden->waveformat);
  282. device->hidden->waveformat = NULL;
  283. }
  284. if (device->hidden->activation_handler) {
  285. WASAPI_PlatformDeleteActivationHandler(device->hidden->activation_handler);
  286. device->hidden->activation_handler = NULL;
  287. }
  288. if (device->hidden->event) {
  289. CloseHandle(device->hidden->event);
  290. device->hidden->event = NULL;
  291. }
  292. return 0;
  293. }
  294. static void ResetWasapiDevice(SDL_AudioDevice *device)
  295. {
  296. int rc;
  297. WASAPI_ProxyToManagementThread(mgmtthrtask_ResetWasapiDevice, device, &rc);
  298. }
  299. static int mgmtthrtask_ActivateDevice(void *userdata)
  300. {
  301. return WASAPI_ActivateDevice((SDL_AudioDevice *)userdata);
  302. }
  303. static int ActivateWasapiDevice(SDL_AudioDevice *device)
  304. {
  305. // this blocks because we're either being notified from a background thread or we're running during device open,
  306. // both of which won't deadlock vs the device thread.
  307. int rc;
  308. return ((WASAPI_ProxyToManagementThread(mgmtthrtask_ActivateDevice, device, &rc) < 0) || (rc < 0)) ? -1 : 0;
  309. }
  310. // do not call when holding the device lock!
  311. static SDL_bool RecoverWasapiDevice(SDL_AudioDevice *device)
  312. {
  313. ResetWasapiDevice(device); // dump the lost device's handles.
  314. // This handles a non-default device that simply had its format changed in the Windows Control Panel.
  315. if (ActivateWasapiDevice(device) == -1) {
  316. WASAPI_DisconnectDevice(device);
  317. return SDL_FALSE;
  318. }
  319. device->hidden->device_lost = SDL_FALSE;
  320. return SDL_TRUE; // okay, carry on with new device details!
  321. }
  322. // do not call when holding the device lock!
  323. static SDL_bool RecoverWasapiIfLost(SDL_AudioDevice *device)
  324. {
  325. if (SDL_AtomicGet(&device->shutdown)) {
  326. return SDL_FALSE; // already failed.
  327. } else if (device->hidden->device_dead) { // had a fatal error elsewhere, clean up and quit
  328. IAudioClient_Stop(device->hidden->client);
  329. WASAPI_DisconnectDevice(device);
  330. SDL_assert(SDL_AtomicGet(&device->shutdown)); // so we don't come back through here.
  331. return SDL_FALSE; // already failed.
  332. } else if (!device->hidden->client) {
  333. return SDL_TRUE; // still waiting for activation.
  334. }
  335. return device->hidden->device_lost ? RecoverWasapiDevice(device) : SDL_TRUE;
  336. }
  337. static Uint8 *WASAPI_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
  338. {
  339. // get an endpoint buffer from WASAPI.
  340. BYTE *buffer = NULL;
  341. if (device->hidden->render) {
  342. if (WasapiFailed(device, IAudioRenderClient_GetBuffer(device->hidden->render, device->sample_frames, &buffer))) {
  343. SDL_assert(buffer == NULL);
  344. if (device->hidden->device_lost) { // just use an available buffer, we won't be playing it anyhow.
  345. *buffer_size = 0; // we'll recover during WaitDevice and try again.
  346. }
  347. }
  348. }
  349. return (Uint8 *)buffer;
  350. }
  351. static int WASAPI_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
  352. {
  353. if (device->hidden->render != NULL) { // definitely activated?
  354. // WasapiFailed() will mark the device for reacquisition or removal elsewhere.
  355. WasapiFailed(device, IAudioRenderClient_ReleaseBuffer(device->hidden->render, device->sample_frames, 0));
  356. }
  357. return 0;
  358. }
  359. static void WASAPI_WaitDevice(SDL_AudioDevice *device)
  360. {
  361. // WaitDevice does not hold the device lock, so check for recovery/disconnect details here.
  362. while (RecoverWasapiIfLost(device) && device->hidden->client && device->hidden->event) {
  363. DWORD waitResult = WaitForSingleObjectEx(device->hidden->event, 200, FALSE);
  364. if (waitResult == WAIT_OBJECT_0) {
  365. const UINT32 maxpadding = device->sample_frames;
  366. UINT32 padding = 0;
  367. if (!WasapiFailed(device, IAudioClient_GetCurrentPadding(device->hidden->client, &padding))) {
  368. //SDL_Log("WASAPI EVENT! padding=%u maxpadding=%u", (unsigned int)padding, (unsigned int)maxpadding);*/
  369. if (device->iscapture && (padding > 0)) {
  370. break;
  371. } else if (!device->iscapture && (padding <= maxpadding)) {
  372. break;
  373. }
  374. }
  375. } else if (waitResult != WAIT_TIMEOUT) {
  376. //SDL_Log("WASAPI FAILED EVENT!");*/
  377. IAudioClient_Stop(device->hidden->client);
  378. WASAPI_DisconnectDevice(device);
  379. }
  380. }
  381. }
  382. static int WASAPI_CaptureFromDevice(SDL_AudioDevice *device, void *buffer, int buflen)
  383. {
  384. BYTE *ptr = NULL;
  385. UINT32 frames = 0;
  386. DWORD flags = 0;
  387. while (device->hidden->capture) {
  388. const HRESULT ret = IAudioCaptureClient_GetBuffer(device->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  389. if (ret == AUDCLNT_S_BUFFER_EMPTY) {
  390. return 0; // in theory we should have waited until there was data, but oh well, we'll go back to waiting. Returning 0 is safe in SDL3.
  391. }
  392. WasapiFailed(device, ret); // mark device lost/failed if necessary.
  393. if (ret == S_OK) {
  394. const int total = ((int)frames) * device->hidden->framesize;
  395. const int cpy = SDL_min(buflen, total);
  396. const int leftover = total - cpy;
  397. const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
  398. SDL_assert(leftover == 0); // according to MSDN, this isn't everything available, just one "packet" of data per-GetBuffer call.
  399. if (silent) {
  400. SDL_memset(buffer, device->silence_value, cpy);
  401. } else {
  402. SDL_memcpy(buffer, ptr, cpy);
  403. }
  404. WasapiFailed(device, IAudioCaptureClient_ReleaseBuffer(device->hidden->capture, frames));
  405. return cpy;
  406. }
  407. }
  408. return -1; // unrecoverable error.
  409. }
  410. static void WASAPI_FlushCapture(SDL_AudioDevice *device)
  411. {
  412. BYTE *ptr = NULL;
  413. UINT32 frames = 0;
  414. DWORD flags = 0;
  415. // just read until we stop getting packets, throwing them away.
  416. while (!SDL_AtomicGet(&device->shutdown) && device->hidden->capture) {
  417. const HRESULT ret = IAudioCaptureClient_GetBuffer(device->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  418. if (ret == AUDCLNT_S_BUFFER_EMPTY) {
  419. break; // no more buffered data; we're done.
  420. } else if (WasapiFailed(device, ret)) {
  421. break; // failed for some other reason, abort.
  422. } else if (WasapiFailed(device, IAudioCaptureClient_ReleaseBuffer(device->hidden->capture, frames))) {
  423. break; // something broke.
  424. }
  425. }
  426. }
  427. static void WASAPI_CloseDevice(SDL_AudioDevice *device)
  428. {
  429. if (device->hidden) {
  430. ResetWasapiDevice(device);
  431. SDL_free(device->hidden->devid);
  432. SDL_free(device->hidden);
  433. device->hidden = NULL;
  434. }
  435. }
  436. static int mgmtthrtask_PrepDevice(void *userdata)
  437. {
  438. SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
  439. /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
  440. !!! it will write into the kernel's audio buffer directly instead of
  441. !!! shared memory that a user-mode mixer then writes to the kernel with
  442. !!! everything else. Doing this means any other sound using this device will
  443. !!! stop playing, including the user's MP3 player and system notification
  444. !!! sounds. You'd probably need to release the device when the app isn't in
  445. !!! the foreground, to be a good citizen of the system. It's doable, but it's
  446. !!! more work and causes some annoyances, and I don't know what the latency
  447. !!! wins actually look like. Maybe add a hint to force exclusive mode at
  448. !!! some point. To be sure, defaulting to shared mode is the right thing to
  449. !!! do in any case. */
  450. const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
  451. IAudioClient *client = device->hidden->client;
  452. SDL_assert(client != NULL);
  453. #if defined(__WINRT__) || defined(__GDK__) // CreateEventEx() arrived in Vista, so we need an #ifdef for XP.
  454. device->hidden->event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
  455. #else
  456. device->hidden->event = CreateEventW(NULL, 0, 0, NULL);
  457. #endif
  458. if (device->hidden->event == NULL) {
  459. return WIN_SetError("WASAPI can't create an event handle");
  460. }
  461. HRESULT ret;
  462. WAVEFORMATEX *waveformat = NULL;
  463. ret = IAudioClient_GetMixFormat(client, &waveformat);
  464. if (FAILED(ret)) {
  465. return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret);
  466. }
  467. SDL_assert(waveformat != NULL);
  468. device->hidden->waveformat = waveformat;
  469. SDL_AudioSpec newspec;
  470. newspec.channels = (Uint8)waveformat->nChannels;
  471. // Make sure we have a valid format that we can convert to whatever WASAPI wants.
  472. const SDL_AudioFormat wasapi_format = SDL_WaveFormatExToSDLFormat(waveformat);
  473. SDL_AudioFormat test_format;
  474. const SDL_AudioFormat *closefmts = SDL_ClosestAudioFormats(device->spec.format);
  475. while ((test_format = *(closefmts++)) != 0) {
  476. if (test_format == wasapi_format) {
  477. newspec.format = test_format;
  478. break;
  479. }
  480. }
  481. if (!test_format) {
  482. return SDL_SetError("%s: Unsupported audio format", "wasapi");
  483. }
  484. REFERENCE_TIME default_period = 0;
  485. ret = IAudioClient_GetDevicePeriod(client, &default_period, NULL);
  486. if (FAILED(ret)) {
  487. return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret);
  488. }
  489. DWORD streamflags = 0;
  490. /* we've gotten reports that WASAPI's resampler introduces distortions, but in the short term
  491. it fixes some other WASAPI-specific quirks we haven't quite tracked down.
  492. Refer to bug #6326 for the immediate concern. */
  493. #if 1
  494. // favor WASAPI's resampler over our own
  495. if ((DWORD)device->spec.freq != waveformat->nSamplesPerSec) {
  496. streamflags |= (AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY);
  497. waveformat->nSamplesPerSec = device->spec.freq;
  498. waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nChannels * (waveformat->wBitsPerSample / 8);
  499. }
  500. #endif
  501. newspec.freq = waveformat->nSamplesPerSec;
  502. streamflags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  503. ret = IAudioClient_Initialize(client, sharemode, streamflags, 0, 0, waveformat, NULL);
  504. if (FAILED(ret)) {
  505. return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret);
  506. }
  507. ret = IAudioClient_SetEventHandle(client, device->hidden->event);
  508. if (FAILED(ret)) {
  509. return WIN_SetErrorFromHRESULT("WASAPI can't set event handle", ret);
  510. }
  511. UINT32 bufsize = 0; // this is in sample frames, not samples, not bytes.
  512. ret = IAudioClient_GetBufferSize(client, &bufsize);
  513. if (FAILED(ret)) {
  514. return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret);
  515. }
  516. /* Match the callback size to the period size to cut down on the number of
  517. interrupts waited for in each call to WaitDevice */
  518. const float period_millis = default_period / 10000.0f;
  519. const float period_frames = period_millis * newspec.freq / 1000.0f;
  520. const int new_sample_frames = (int) SDL_ceilf(period_frames);
  521. // Update the fragment size as size in bytes
  522. if (SDL_AudioDeviceFormatChangedAlreadyLocked(device, &newspec, new_sample_frames) < 0) {
  523. return -1;
  524. }
  525. device->hidden->framesize = SDL_AUDIO_FRAMESIZE(device->spec);
  526. if (device->iscapture) {
  527. IAudioCaptureClient *capture = NULL;
  528. ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void **)&capture);
  529. if (FAILED(ret)) {
  530. return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
  531. }
  532. SDL_assert(capture != NULL);
  533. device->hidden->capture = capture;
  534. ret = IAudioClient_Start(client);
  535. if (FAILED(ret)) {
  536. return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret);
  537. }
  538. WASAPI_FlushCapture(device); // MSDN says you should flush capture endpoint right after startup.
  539. } else {
  540. IAudioRenderClient *render = NULL;
  541. ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void **)&render);
  542. if (FAILED(ret)) {
  543. return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
  544. }
  545. SDL_assert(render != NULL);
  546. device->hidden->render = render;
  547. ret = IAudioClient_Start(client);
  548. if (FAILED(ret)) {
  549. return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret);
  550. }
  551. }
  552. return 0; // good to go.
  553. }
  554. // This is called once a device is activated, possibly asynchronously.
  555. int WASAPI_PrepDevice(SDL_AudioDevice *device)
  556. {
  557. int rc = 0;
  558. return (WASAPI_ProxyToManagementThread(mgmtthrtask_PrepDevice, device, &rc) < 0) ? -1 : rc;
  559. }
  560. static int WASAPI_OpenDevice(SDL_AudioDevice *device)
  561. {
  562. // Initialize all variables that we clean on shutdown
  563. device->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, sizeof(*device->hidden));
  564. if (device->hidden == NULL) {
  565. return SDL_OutOfMemory();
  566. } else if (ActivateWasapiDevice(device) < 0) {
  567. return -1; // already set error.
  568. }
  569. /* Ready, but possibly waiting for async device activation.
  570. Until activation is successful, we will report silence from capture
  571. devices and ignore data on playback devices. Upon activation, we'll make
  572. sure any bound audio streams are adjusted for the final device format. */
  573. return 0;
  574. }
  575. static void WASAPI_ThreadInit(SDL_AudioDevice *device)
  576. {
  577. WASAPI_PlatformThreadInit(device);
  578. }
  579. static void WASAPI_ThreadDeinit(SDL_AudioDevice *device)
  580. {
  581. WASAPI_PlatformThreadDeinit(device);
  582. }
  583. static int mgmtthrtask_FreeDeviceHandle(void *userdata)
  584. {
  585. WASAPI_PlatformFreeDeviceHandle((SDL_AudioDevice *)userdata);
  586. return 0;
  587. }
  588. static void WASAPI_FreeDeviceHandle(SDL_AudioDevice *device)
  589. {
  590. int rc;
  591. WASAPI_ProxyToManagementThread(mgmtthrtask_FreeDeviceHandle, device, &rc);
  592. }
  593. static void WASAPI_Deinitialize(void)
  594. {
  595. DeinitManagementThread();
  596. }
  597. static SDL_bool WASAPI_Init(SDL_AudioDriverImpl *impl)
  598. {
  599. if (InitManagementThread() < 0) {
  600. return SDL_FALSE;
  601. }
  602. impl->DetectDevices = WASAPI_DetectDevices;
  603. impl->ThreadInit = WASAPI_ThreadInit;
  604. impl->ThreadDeinit = WASAPI_ThreadDeinit;
  605. impl->OpenDevice = WASAPI_OpenDevice;
  606. impl->PlayDevice = WASAPI_PlayDevice;
  607. impl->WaitDevice = WASAPI_WaitDevice;
  608. impl->GetDeviceBuf = WASAPI_GetDeviceBuf;
  609. impl->WaitCaptureDevice = WASAPI_WaitDevice;
  610. impl->CaptureFromDevice = WASAPI_CaptureFromDevice;
  611. impl->FlushCapture = WASAPI_FlushCapture;
  612. impl->CloseDevice = WASAPI_CloseDevice;
  613. impl->Deinitialize = WASAPI_Deinitialize;
  614. impl->FreeDeviceHandle = WASAPI_FreeDeviceHandle;
  615. impl->HasCaptureSupport = SDL_TRUE;
  616. return SDL_TRUE;
  617. }
  618. AudioBootStrap WASAPI_bootstrap = {
  619. "wasapi", "WASAPI", WASAPI_Init, SDL_FALSE
  620. };
  621. #endif // SDL_AUDIO_DRIVER_WASAPI