SDL_wasapi.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 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_sysaudio.h"
  24. #define COBJMACROS
  25. #include <audioclient.h>
  26. #include "SDL_wasapi.h"
  27. // These constants aren't available in older SDKs
  28. #ifndef AUDCLNT_STREAMFLAGS_RATEADJUST
  29. #define AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
  30. #endif
  31. #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
  32. #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  33. #endif
  34. #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
  35. #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  36. #endif
  37. // Some GUIDs we need to know without linking to libraries that aren't available before Vista.
  38. static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, { 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
  39. static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0, { 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
  40. static const IID SDL_IID_IAudioClient3 = { 0x7ed4ee07, 0x8e67, 0x4cd4, { 0x8c, 0x1a, 0x2b, 0x7a, 0x59, 0x87, 0xad, 0x42 } };
  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 = (ManagementThreadPendingTask *)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) && (SDL_GetCurrentThreadID() == 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 = (ManagementThreadPendingTask *)SDL_calloc(1, sizeof(ManagementThreadPendingTask));
  90. if (!pending) {
  91. return -1;
  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 = (ManagementThreadPendingTask *)SDL_AtomicGetPtr((void **)&ManagementThreadPendingTasks); i; i = i->next) {
  107. prev = i;
  108. }
  109. if (prev) {
  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;
  224. data.default_output = default_output;
  225. data.default_capture = default_capture;
  226. WASAPI_ProxyToManagementThread(mgmtthrtask_DetectDevices, &data, &rc);
  227. }
  228. static int mgmtthrtask_DisconnectDevice(void *userdata)
  229. {
  230. SDL_AudioDeviceDisconnected((SDL_AudioDevice *)userdata);
  231. return 0;
  232. }
  233. void WASAPI_DisconnectDevice(SDL_AudioDevice *device)
  234. {
  235. int rc; // block on this; don't disconnect while holding the device lock!
  236. WASAPI_ProxyToManagementThread(mgmtthrtask_DisconnectDevice, device, &rc);
  237. }
  238. static SDL_bool WasapiFailed(SDL_AudioDevice *device, const HRESULT err)
  239. {
  240. if (err == S_OK) {
  241. return SDL_FALSE;
  242. } else if (err == AUDCLNT_E_DEVICE_INVALIDATED) {
  243. device->hidden->device_lost = SDL_TRUE;
  244. } else {
  245. device->hidden->device_dead = SDL_TRUE;
  246. }
  247. return SDL_TRUE;
  248. }
  249. static int mgmtthrtask_StopAndReleaseClient(void *userdata)
  250. {
  251. IAudioClient *client = (IAudioClient *) userdata;
  252. IAudioClient_Stop(client);
  253. IAudioClient_Release(client);
  254. return 0;
  255. }
  256. static int mgmtthrtask_ReleaseCaptureClient(void *userdata)
  257. {
  258. IAudioCaptureClient_Release((IAudioCaptureClient *)userdata);
  259. return 0;
  260. }
  261. static int mgmtthrtask_ReleaseRenderClient(void *userdata)
  262. {
  263. IAudioRenderClient_Release((IAudioRenderClient *)userdata);
  264. return 0;
  265. }
  266. static int mgmtthrtask_CoTaskMemFree(void *userdata)
  267. {
  268. CoTaskMemFree(userdata);
  269. return 0;
  270. }
  271. static int mgmtthrtask_PlatformDeleteActivationHandler(void *userdata)
  272. {
  273. WASAPI_PlatformDeleteActivationHandler(userdata);
  274. return 0;
  275. }
  276. static int mgmtthrtask_CloseHandle(void *userdata)
  277. {
  278. CloseHandle((HANDLE) userdata);
  279. return 0;
  280. }
  281. static void ResetWasapiDevice(SDL_AudioDevice *device)
  282. {
  283. if (!device || !device->hidden) {
  284. return;
  285. }
  286. // just queue up all the tasks in the management thread and don't block.
  287. // We don't care when any of these actually get free'd.
  288. if (device->hidden->client) {
  289. IAudioClient *client = device->hidden->client;
  290. device->hidden->client = NULL;
  291. WASAPI_ProxyToManagementThread(mgmtthrtask_StopAndReleaseClient, client, NULL);
  292. }
  293. if (device->hidden->render) {
  294. IAudioRenderClient *render = device->hidden->render;
  295. device->hidden->render = NULL;
  296. WASAPI_ProxyToManagementThread(mgmtthrtask_ReleaseRenderClient, render, NULL);
  297. }
  298. if (device->hidden->capture) {
  299. IAudioCaptureClient *capture = device->hidden->capture;
  300. device->hidden->capture = NULL;
  301. WASAPI_ProxyToManagementThread(mgmtthrtask_ReleaseCaptureClient, capture, NULL);
  302. }
  303. if (device->hidden->waveformat) {
  304. void *ptr = device->hidden->waveformat;
  305. device->hidden->waveformat = NULL;
  306. WASAPI_ProxyToManagementThread(mgmtthrtask_CoTaskMemFree, ptr, NULL);
  307. }
  308. if (device->hidden->activation_handler) {
  309. void *activation_handler = device->hidden->activation_handler;
  310. device->hidden->activation_handler = NULL;
  311. WASAPI_ProxyToManagementThread(mgmtthrtask_PlatformDeleteActivationHandler, activation_handler, NULL);
  312. }
  313. if (device->hidden->event) {
  314. HANDLE event = device->hidden->event;
  315. device->hidden->event = NULL;
  316. WASAPI_ProxyToManagementThread(mgmtthrtask_CloseHandle, (void *) event, NULL);
  317. }
  318. }
  319. static int mgmtthrtask_ActivateDevice(void *userdata)
  320. {
  321. return WASAPI_ActivateDevice((SDL_AudioDevice *)userdata);
  322. }
  323. static int ActivateWasapiDevice(SDL_AudioDevice *device)
  324. {
  325. // this blocks because we're either being notified from a background thread or we're running during device open,
  326. // both of which won't deadlock vs the device thread.
  327. int rc = -1;
  328. return ((WASAPI_ProxyToManagementThread(mgmtthrtask_ActivateDevice, device, &rc) < 0) || (rc < 0)) ? -1 : 0;
  329. }
  330. // do not call when holding the device lock!
  331. static SDL_bool RecoverWasapiDevice(SDL_AudioDevice *device)
  332. {
  333. ResetWasapiDevice(device); // dump the lost device's handles.
  334. // This handles a non-default device that simply had its format changed in the Windows Control Panel.
  335. if (ActivateWasapiDevice(device) == -1) {
  336. WASAPI_DisconnectDevice(device);
  337. return SDL_FALSE;
  338. }
  339. device->hidden->device_lost = SDL_FALSE;
  340. return SDL_TRUE; // okay, carry on with new device details!
  341. }
  342. // do not call when holding the device lock!
  343. static SDL_bool RecoverWasapiIfLost(SDL_AudioDevice *device)
  344. {
  345. if (SDL_AtomicGet(&device->shutdown)) {
  346. return SDL_FALSE; // already failed.
  347. } else if (device->hidden->device_dead) { // had a fatal error elsewhere, clean up and quit
  348. IAudioClient_Stop(device->hidden->client);
  349. WASAPI_DisconnectDevice(device);
  350. SDL_assert(SDL_AtomicGet(&device->shutdown)); // so we don't come back through here.
  351. return SDL_FALSE; // already failed.
  352. } else if (SDL_AtomicGet(&device->zombie)) {
  353. return SDL_FALSE; // we're already dead, so just leave and let the Zombie implementations take over.
  354. } else if (!device->hidden->client) {
  355. return SDL_TRUE; // still waiting for activation.
  356. }
  357. return device->hidden->device_lost ? RecoverWasapiDevice(device) : SDL_TRUE;
  358. }
  359. static Uint8 *WASAPI_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
  360. {
  361. // get an endpoint buffer from WASAPI.
  362. BYTE *buffer = NULL;
  363. if (device->hidden->render) {
  364. const HRESULT ret = IAudioRenderClient_GetBuffer(device->hidden->render, device->sample_frames, &buffer);
  365. if (ret == AUDCLNT_E_BUFFER_TOO_LARGE) {
  366. SDL_assert(buffer == NULL);
  367. *buffer_size = 0; // just go back to WaitDevice and try again after the hardware has consumed some more data.
  368. } else if (WasapiFailed(device, ret)) {
  369. SDL_assert(buffer == NULL);
  370. if (device->hidden->device_lost) { // just use an available buffer, we won't be playing it anyhow.
  371. *buffer_size = 0; // we'll recover during WaitDevice and try again.
  372. }
  373. }
  374. }
  375. return (Uint8 *)buffer;
  376. }
  377. static int WASAPI_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
  378. {
  379. if (device->hidden->render) { // definitely activated?
  380. // WasapiFailed() will mark the device for reacquisition or removal elsewhere.
  381. WasapiFailed(device, IAudioRenderClient_ReleaseBuffer(device->hidden->render, device->sample_frames, 0));
  382. }
  383. return 0;
  384. }
  385. static int WASAPI_WaitDevice(SDL_AudioDevice *device)
  386. {
  387. // WaitDevice does not hold the device lock, so check for recovery/disconnect details here.
  388. while (RecoverWasapiIfLost(device) && device->hidden->client && device->hidden->event) {
  389. UINT32 padding = 0;
  390. if (!WasapiFailed(device, IAudioClient_GetCurrentPadding(device->hidden->client, &padding))) {
  391. const UINT32 maxpadding = device->sample_frames;
  392. //SDL_Log("WASAPI %s EVENT! padding=%u maxpadding=%u", device->iscapture ? "CAPTURE" : "PLAYBACK", (unsigned int)padding, (unsigned int)maxpadding);
  393. if (device->iscapture ? (padding > 0) : (padding < maxpadding)) {
  394. break;
  395. }
  396. }
  397. switch (WaitForSingleObjectEx(device->hidden->event, 200, FALSE)) {
  398. case WAIT_OBJECT_0:
  399. case WAIT_TIMEOUT:
  400. break;
  401. default:
  402. //SDL_Log("WASAPI FAILED EVENT!");
  403. IAudioClient_Stop(device->hidden->client);
  404. return -1;
  405. }
  406. }
  407. return 0;
  408. }
  409. static int WASAPI_CaptureFromDevice(SDL_AudioDevice *device, void *buffer, int buflen)
  410. {
  411. BYTE *ptr = NULL;
  412. UINT32 frames = 0;
  413. DWORD flags = 0;
  414. while (device->hidden->capture) {
  415. const HRESULT ret = IAudioCaptureClient_GetBuffer(device->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  416. if (ret == AUDCLNT_S_BUFFER_EMPTY) {
  417. 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.
  418. }
  419. WasapiFailed(device, ret); // mark device lost/failed if necessary.
  420. if (ret == S_OK) {
  421. const int total = ((int)frames) * device->hidden->framesize;
  422. const int cpy = SDL_min(buflen, total);
  423. const int leftover = total - cpy;
  424. const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
  425. SDL_assert(leftover == 0); // according to MSDN, this isn't everything available, just one "packet" of data per-GetBuffer call.
  426. if (silent) {
  427. SDL_memset(buffer, device->silence_value, cpy);
  428. } else {
  429. SDL_memcpy(buffer, ptr, cpy);
  430. }
  431. WasapiFailed(device, IAudioCaptureClient_ReleaseBuffer(device->hidden->capture, frames));
  432. return cpy;
  433. }
  434. }
  435. return -1; // unrecoverable error.
  436. }
  437. static void WASAPI_FlushCapture(SDL_AudioDevice *device)
  438. {
  439. BYTE *ptr = NULL;
  440. UINT32 frames = 0;
  441. DWORD flags = 0;
  442. // just read until we stop getting packets, throwing them away.
  443. while (!SDL_AtomicGet(&device->shutdown) && device->hidden->capture) {
  444. const HRESULT ret = IAudioCaptureClient_GetBuffer(device->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  445. if (ret == AUDCLNT_S_BUFFER_EMPTY) {
  446. break; // no more buffered data; we're done.
  447. } else if (WasapiFailed(device, ret)) {
  448. break; // failed for some other reason, abort.
  449. } else if (WasapiFailed(device, IAudioCaptureClient_ReleaseBuffer(device->hidden->capture, frames))) {
  450. break; // something broke.
  451. }
  452. }
  453. }
  454. static void WASAPI_CloseDevice(SDL_AudioDevice *device)
  455. {
  456. if (device->hidden) {
  457. ResetWasapiDevice(device);
  458. SDL_free(device->hidden->devid);
  459. SDL_free(device->hidden);
  460. device->hidden = NULL;
  461. }
  462. }
  463. static int mgmtthrtask_PrepDevice(void *userdata)
  464. {
  465. SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
  466. /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
  467. !!! it will write into the kernel's audio buffer directly instead of
  468. !!! shared memory that a user-mode mixer then writes to the kernel with
  469. !!! everything else. Doing this means any other sound using this device will
  470. !!! stop playing, including the user's MP3 player and system notification
  471. !!! sounds. You'd probably need to release the device when the app isn't in
  472. !!! the foreground, to be a good citizen of the system. It's doable, but it's
  473. !!! more work and causes some annoyances, and I don't know what the latency
  474. !!! wins actually look like. Maybe add a hint to force exclusive mode at
  475. !!! some point. To be sure, defaulting to shared mode is the right thing to
  476. !!! do in any case. */
  477. const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
  478. IAudioClient *client = device->hidden->client;
  479. SDL_assert(client != NULL);
  480. #if defined(SDL_PLATFORM_WINRT) || defined(SDL_PLATFORM_GDK) // CreateEventEx() arrived in Vista, so we need an #ifdef for XP.
  481. device->hidden->event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
  482. #else
  483. device->hidden->event = CreateEventW(NULL, 0, 0, NULL);
  484. #endif
  485. if (!device->hidden->event) {
  486. return WIN_SetError("WASAPI can't create an event handle");
  487. }
  488. HRESULT ret;
  489. WAVEFORMATEX *waveformat = NULL;
  490. ret = IAudioClient_GetMixFormat(client, &waveformat);
  491. if (FAILED(ret)) {
  492. return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret);
  493. }
  494. SDL_assert(waveformat != NULL);
  495. device->hidden->waveformat = waveformat;
  496. SDL_AudioSpec newspec;
  497. newspec.channels = (Uint8)waveformat->nChannels;
  498. // Make sure we have a valid format that we can convert to whatever WASAPI wants.
  499. const SDL_AudioFormat wasapi_format = SDL_WaveFormatExToSDLFormat(waveformat);
  500. SDL_AudioFormat test_format;
  501. const SDL_AudioFormat *closefmts = SDL_ClosestAudioFormats(device->spec.format);
  502. while ((test_format = *(closefmts++)) != 0) {
  503. if (test_format == wasapi_format) {
  504. newspec.format = test_format;
  505. break;
  506. }
  507. }
  508. if (!test_format) {
  509. return SDL_SetError("%s: Unsupported audio format", "wasapi");
  510. }
  511. REFERENCE_TIME default_period = 0;
  512. ret = IAudioClient_GetDevicePeriod(client, &default_period, NULL);
  513. if (FAILED(ret)) {
  514. return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret);
  515. }
  516. DWORD streamflags = 0;
  517. /* we've gotten reports that WASAPI's resampler introduces distortions, but in the short term
  518. it fixes some other WASAPI-specific quirks we haven't quite tracked down.
  519. Refer to bug #6326 for the immediate concern. */
  520. #if 1
  521. // favor WASAPI's resampler over our own
  522. if ((DWORD)device->spec.freq != waveformat->nSamplesPerSec) {
  523. streamflags |= (AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY);
  524. waveformat->nSamplesPerSec = device->spec.freq;
  525. waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nChannels * (waveformat->wBitsPerSample / 8);
  526. }
  527. #endif
  528. newspec.freq = waveformat->nSamplesPerSec;
  529. streamflags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  530. int new_sample_frames = 0;
  531. SDL_bool iaudioclient3_initialized = SDL_FALSE;
  532. #ifdef __IAudioClient3_INTERFACE_DEFINED__
  533. // Try querying IAudioClient3 if sharemode is AUDCLNT_SHAREMODE_SHARED
  534. if (sharemode == AUDCLNT_SHAREMODE_SHARED) {
  535. IAudioClient3 *client3 = NULL;
  536. ret = IAudioClient_QueryInterface(client, &SDL_IID_IAudioClient3, (void**)&client3);
  537. if (SUCCEEDED(ret)) {
  538. UINT32 default_period_in_frames = 0;
  539. UINT32 fundamental_period_in_frames = 0;
  540. UINT32 min_period_in_frames = 0;
  541. UINT32 max_period_in_frames = 0;
  542. ret = IAudioClient3_GetSharedModeEnginePeriod(client3, waveformat,
  543. &default_period_in_frames, &fundamental_period_in_frames, &min_period_in_frames, &max_period_in_frames);
  544. if (SUCCEEDED(ret)) {
  545. // IAudioClient3_InitializeSharedAudioStream only accepts the integral multiple of fundamental_period_in_frames
  546. UINT32 period_in_frames = fundamental_period_in_frames * (UINT32)SDL_round((double)device->sample_frames / fundamental_period_in_frames);
  547. period_in_frames = SDL_clamp(period_in_frames, min_period_in_frames, max_period_in_frames);
  548. ret = IAudioClient3_InitializeSharedAudioStream(client3, streamflags, period_in_frames, waveformat, NULL);
  549. if (SUCCEEDED(ret)) {
  550. new_sample_frames = (int)period_in_frames;
  551. iaudioclient3_initialized = SDL_TRUE;
  552. }
  553. }
  554. IAudioClient3_Release(client3);
  555. }
  556. }
  557. #endif
  558. if (!iaudioclient3_initialized)
  559. ret = IAudioClient_Initialize(client, sharemode, streamflags, 0, 0, waveformat, NULL);
  560. if (FAILED(ret)) {
  561. return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret);
  562. }
  563. ret = IAudioClient_SetEventHandle(client, device->hidden->event);
  564. if (FAILED(ret)) {
  565. return WIN_SetErrorFromHRESULT("WASAPI can't set event handle", ret);
  566. }
  567. UINT32 bufsize = 0; // this is in sample frames, not samples, not bytes.
  568. ret = IAudioClient_GetBufferSize(client, &bufsize);
  569. if (FAILED(ret)) {
  570. return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret);
  571. }
  572. // Match the callback size to the period size to cut down on the number of
  573. // interrupts waited for in each call to WaitDevice
  574. if (new_sample_frames <= 0) {
  575. const float period_millis = default_period / 10000.0f;
  576. const float period_frames = period_millis * newspec.freq / 1000.0f;
  577. new_sample_frames = (int) SDL_ceilf(period_frames);
  578. }
  579. // regardless of what we calculated for the period size, clamp it to the expected hardware buffer size.
  580. if (new_sample_frames > (int) bufsize) {
  581. new_sample_frames = (int) bufsize;
  582. }
  583. // Update the fragment size as size in bytes
  584. if (SDL_AudioDeviceFormatChangedAlreadyLocked(device, &newspec, new_sample_frames) < 0) {
  585. return -1;
  586. }
  587. device->hidden->framesize = SDL_AUDIO_FRAMESIZE(device->spec);
  588. if (device->iscapture) {
  589. IAudioCaptureClient *capture = NULL;
  590. ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void **)&capture);
  591. if (FAILED(ret)) {
  592. return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
  593. }
  594. SDL_assert(capture != NULL);
  595. device->hidden->capture = capture;
  596. ret = IAudioClient_Start(client);
  597. if (FAILED(ret)) {
  598. return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret);
  599. }
  600. WASAPI_FlushCapture(device); // MSDN says you should flush capture endpoint right after startup.
  601. } else {
  602. IAudioRenderClient *render = NULL;
  603. ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void **)&render);
  604. if (FAILED(ret)) {
  605. return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
  606. }
  607. SDL_assert(render != NULL);
  608. device->hidden->render = render;
  609. ret = IAudioClient_Start(client);
  610. if (FAILED(ret)) {
  611. return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret);
  612. }
  613. }
  614. return 0; // good to go.
  615. }
  616. // This is called once a device is activated, possibly asynchronously.
  617. int WASAPI_PrepDevice(SDL_AudioDevice *device)
  618. {
  619. int rc = 0;
  620. return (WASAPI_ProxyToManagementThread(mgmtthrtask_PrepDevice, device, &rc) < 0) ? -1 : rc;
  621. }
  622. static int WASAPI_OpenDevice(SDL_AudioDevice *device)
  623. {
  624. // Initialize all variables that we clean on shutdown
  625. device->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, sizeof(*device->hidden));
  626. if (!device->hidden) {
  627. return -1;
  628. } else if (ActivateWasapiDevice(device) < 0) {
  629. return -1; // already set error.
  630. }
  631. /* Ready, but possibly waiting for async device activation.
  632. Until activation is successful, we will report silence from capture
  633. devices and ignore data on playback devices. Upon activation, we'll make
  634. sure any bound audio streams are adjusted for the final device format. */
  635. return 0;
  636. }
  637. static void WASAPI_ThreadInit(SDL_AudioDevice *device)
  638. {
  639. WASAPI_PlatformThreadInit(device);
  640. }
  641. static void WASAPI_ThreadDeinit(SDL_AudioDevice *device)
  642. {
  643. WASAPI_PlatformThreadDeinit(device);
  644. }
  645. static int mgmtthrtask_FreeDeviceHandle(void *userdata)
  646. {
  647. WASAPI_PlatformFreeDeviceHandle((SDL_AudioDevice *)userdata);
  648. return 0;
  649. }
  650. static void WASAPI_FreeDeviceHandle(SDL_AudioDevice *device)
  651. {
  652. int rc;
  653. WASAPI_ProxyToManagementThread(mgmtthrtask_FreeDeviceHandle, device, &rc);
  654. }
  655. static int mgmtthrtask_DeinitializeStart(void *userdata)
  656. {
  657. WASAPI_PlatformDeinitializeStart();
  658. return 0;
  659. }
  660. static void WASAPI_DeinitializeStart(void)
  661. {
  662. int rc;
  663. WASAPI_ProxyToManagementThread(mgmtthrtask_DeinitializeStart, NULL, &rc);
  664. }
  665. static void WASAPI_Deinitialize(void)
  666. {
  667. DeinitManagementThread();
  668. }
  669. static SDL_bool WASAPI_Init(SDL_AudioDriverImpl *impl)
  670. {
  671. if (InitManagementThread() < 0) {
  672. return SDL_FALSE;
  673. }
  674. impl->DetectDevices = WASAPI_DetectDevices;
  675. impl->ThreadInit = WASAPI_ThreadInit;
  676. impl->ThreadDeinit = WASAPI_ThreadDeinit;
  677. impl->OpenDevice = WASAPI_OpenDevice;
  678. impl->PlayDevice = WASAPI_PlayDevice;
  679. impl->WaitDevice = WASAPI_WaitDevice;
  680. impl->GetDeviceBuf = WASAPI_GetDeviceBuf;
  681. impl->WaitCaptureDevice = WASAPI_WaitDevice;
  682. impl->CaptureFromDevice = WASAPI_CaptureFromDevice;
  683. impl->FlushCapture = WASAPI_FlushCapture;
  684. impl->CloseDevice = WASAPI_CloseDevice;
  685. impl->DeinitializeStart = WASAPI_DeinitializeStart;
  686. impl->Deinitialize = WASAPI_Deinitialize;
  687. impl->FreeDeviceHandle = WASAPI_FreeDeviceHandle;
  688. impl->HasCaptureSupport = SDL_TRUE;
  689. return SDL_TRUE;
  690. }
  691. AudioBootStrap WASAPI_bootstrap = {
  692. "wasapi", "WASAPI", WASAPI_Init, SDL_FALSE
  693. };
  694. #endif // SDL_AUDIO_DRIVER_WASAPI