SDL_wasapi.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2022 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. #define COBJMACROS
  26. #include <mmdeviceapi.h>
  27. #include <audioclient.h>
  28. #include "SDL_wasapi.h"
  29. /* These constants aren't available in older SDKs */
  30. #ifndef AUDCLNT_STREAMFLAGS_RATEADJUST
  31. #define AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
  32. #endif
  33. #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
  34. #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  35. #endif
  36. #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
  37. #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  38. #endif
  39. /* these increment as default devices change. Opened default devices pick up changes in their threads. */
  40. SDL_atomic_t WASAPI_DefaultPlaybackGeneration;
  41. SDL_atomic_t WASAPI_DefaultCaptureGeneration;
  42. /* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */
  43. typedef struct DevIdList
  44. {
  45. WCHAR *str;
  46. struct DevIdList *next;
  47. } DevIdList;
  48. static DevIdList *deviceid_list = NULL;
  49. /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
  50. static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
  51. static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,{ 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
  52. static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  53. static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  54. void
  55. WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid)
  56. {
  57. DevIdList *i;
  58. DevIdList *next;
  59. DevIdList *prev = NULL;
  60. for (i = deviceid_list; i; i = next) {
  61. next = i->next;
  62. if (SDL_wcscmp(i->str, devid) == 0) {
  63. if (prev) {
  64. prev->next = next;
  65. } else {
  66. deviceid_list = next;
  67. }
  68. SDL_RemoveAudioDevice(iscapture, i->str);
  69. SDL_free(i->str);
  70. SDL_free(i);
  71. }
  72. prev = i;
  73. }
  74. }
  75. static SDL_AudioFormat
  76. WaveFormatToSDLFormat(WAVEFORMATEX *waveformat)
  77. {
  78. if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
  79. return AUDIO_F32SYS;
  80. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
  81. return AUDIO_S16SYS;
  82. } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
  83. return AUDIO_S32SYS;
  84. } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  85. const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *) waveformat;
  86. if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  87. return AUDIO_F32SYS;
  88. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
  89. return AUDIO_S16SYS;
  90. } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
  91. return AUDIO_S32SYS;
  92. }
  93. }
  94. return 0;
  95. }
  96. void
  97. WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid)
  98. {
  99. DevIdList *devidlist;
  100. SDL_AudioSpec spec;
  101. /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
  102. In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
  103. phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
  104. available and switch automatically. (!!! FIXME...?) */
  105. /* see if we already have this one. */
  106. for (devidlist = deviceid_list; devidlist; devidlist = devidlist->next) {
  107. if (SDL_wcscmp(devidlist->str, devid) == 0) {
  108. return; /* we already have this. */
  109. }
  110. }
  111. devidlist = (DevIdList *) SDL_malloc(sizeof (*devidlist));
  112. if (!devidlist) {
  113. return; /* oh well. */
  114. }
  115. devid = SDL_wcsdup(devid);
  116. if (!devid) {
  117. SDL_free(devidlist);
  118. return; /* oh well. */
  119. }
  120. devidlist->str = (WCHAR *) devid;
  121. devidlist->next = deviceid_list;
  122. deviceid_list = devidlist;
  123. SDL_zero(spec);
  124. spec.channels = (Uint8)fmt->Format.nChannels;
  125. spec.freq = fmt->Format.nSamplesPerSec;
  126. spec.format = WaveFormatToSDLFormat((WAVEFORMATEX *) fmt);
  127. SDL_AddAudioDevice(iscapture, devname, &spec, (void *) devid);
  128. }
  129. static void
  130. WASAPI_DetectDevices(void)
  131. {
  132. WASAPI_EnumerateEndpoints();
  133. }
  134. static SDL_INLINE SDL_bool
  135. WasapiFailed(_THIS, const HRESULT err)
  136. {
  137. if (err == S_OK) {
  138. return SDL_FALSE;
  139. }
  140. if (err == AUDCLNT_E_DEVICE_INVALIDATED) {
  141. this->hidden->device_lost = SDL_TRUE;
  142. } else if (SDL_AtomicGet(&this->enabled)) {
  143. IAudioClient_Stop(this->hidden->client);
  144. SDL_OpenedAudioDeviceDisconnected(this);
  145. SDL_assert(!SDL_AtomicGet(&this->enabled));
  146. }
  147. return SDL_TRUE;
  148. }
  149. static int
  150. UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
  151. {
  152. /* Since WASAPI requires us to handle all audio conversion, and our
  153. device format might have changed, we might have to add/remove/change
  154. the audio stream that the higher level uses to convert data, so
  155. SDL keeps firing the callback as if nothing happened here. */
  156. if ( (this->callbackspec.channels == this->spec.channels) &&
  157. (this->callbackspec.format == this->spec.format) &&
  158. (this->callbackspec.freq == this->spec.freq) &&
  159. (this->callbackspec.samples == this->spec.samples) ) {
  160. /* no need to buffer/convert in an AudioStream! */
  161. SDL_FreeAudioStream(this->stream);
  162. this->stream = NULL;
  163. } else if ( (oldspec->channels == this->spec.channels) &&
  164. (oldspec->format == this->spec.format) &&
  165. (oldspec->freq == this->spec.freq) ) {
  166. /* The existing audio stream is okay to keep using. */
  167. } else {
  168. /* replace the audiostream for new format */
  169. SDL_FreeAudioStream(this->stream);
  170. if (this->iscapture) {
  171. this->stream = SDL_NewAudioStream(this->spec.format,
  172. this->spec.channels, this->spec.freq,
  173. this->callbackspec.format,
  174. this->callbackspec.channels,
  175. this->callbackspec.freq);
  176. } else {
  177. this->stream = SDL_NewAudioStream(this->callbackspec.format,
  178. this->callbackspec.channels,
  179. this->callbackspec.freq, this->spec.format,
  180. this->spec.channels, this->spec.freq);
  181. }
  182. if (!this->stream) {
  183. return -1; /* SDL_NewAudioStream should have called SDL_SetError. */
  184. }
  185. }
  186. /* make sure our scratch buffer can cover the new device spec. */
  187. if (this->spec.size > this->work_buffer_len) {
  188. Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size);
  189. if (ptr == NULL) {
  190. return SDL_OutOfMemory();
  191. }
  192. this->work_buffer = ptr;
  193. this->work_buffer_len = this->spec.size;
  194. }
  195. return 0;
  196. }
  197. static void ReleaseWasapiDevice(_THIS);
  198. static SDL_bool
  199. RecoverWasapiDevice(_THIS)
  200. {
  201. ReleaseWasapiDevice(this); /* dump the lost device's handles. */
  202. if (this->hidden->default_device_generation) {
  203. this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
  204. }
  205. /* this can fail for lots of reasons, but the most likely is we had a
  206. non-default device that was disconnected, so we can't recover. Default
  207. devices try to reinitialize whatever the new default is, so it's more
  208. likely to carry on here, but this handles a non-default device that
  209. simply had its format changed in the Windows Control Panel. */
  210. if (WASAPI_ActivateDevice(this, SDL_TRUE) == -1) {
  211. SDL_OpenedAudioDeviceDisconnected(this);
  212. return SDL_FALSE;
  213. }
  214. this->hidden->device_lost = SDL_FALSE;
  215. return SDL_TRUE; /* okay, carry on with new device details! */
  216. }
  217. static SDL_bool
  218. RecoverWasapiIfLost(_THIS)
  219. {
  220. const int generation = this->hidden->default_device_generation;
  221. SDL_bool lost = this->hidden->device_lost;
  222. if (!SDL_AtomicGet(&this->enabled)) {
  223. return SDL_FALSE; /* already failed. */
  224. }
  225. if (!this->hidden->client) {
  226. return SDL_TRUE; /* still waiting for activation. */
  227. }
  228. if (!lost && (generation > 0)) { /* is a default device? */
  229. const int newgen = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
  230. if (generation != newgen) { /* the desired default device was changed, jump over to it. */
  231. lost = SDL_TRUE;
  232. }
  233. }
  234. return lost ? RecoverWasapiDevice(this) : SDL_TRUE;
  235. }
  236. static Uint8 *
  237. WASAPI_GetDeviceBuf(_THIS)
  238. {
  239. /* get an endpoint buffer from WASAPI. */
  240. BYTE *buffer = NULL;
  241. while (RecoverWasapiIfLost(this) && this->hidden->render) {
  242. if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) {
  243. return (Uint8 *) buffer;
  244. }
  245. SDL_assert(buffer == NULL);
  246. }
  247. return (Uint8 *) buffer;
  248. }
  249. static void
  250. WASAPI_PlayDevice(_THIS)
  251. {
  252. if (this->hidden->render != NULL) { /* definitely activated? */
  253. /* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
  254. WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0));
  255. }
  256. }
  257. static void
  258. WASAPI_WaitDevice(_THIS)
  259. {
  260. while (RecoverWasapiIfLost(this) && this->hidden->client && this->hidden->event) {
  261. DWORD waitResult = WaitForSingleObjectEx(this->hidden->event, 200, FALSE);
  262. if (waitResult == WAIT_OBJECT_0) {
  263. const UINT32 maxpadding = this->spec.samples;
  264. UINT32 padding = 0;
  265. if (!WasapiFailed(this, IAudioClient_GetCurrentPadding(this->hidden->client, &padding))) {
  266. /*SDL_Log("WASAPI EVENT! padding=%u maxpadding=%u", (unsigned int)padding, (unsigned int)maxpadding);*/
  267. if (this->iscapture) {
  268. if (padding > 0) {
  269. break;
  270. }
  271. } else {
  272. if (padding <= maxpadding) {
  273. break;
  274. }
  275. }
  276. }
  277. } else if (waitResult != WAIT_TIMEOUT) {
  278. /*SDL_Log("WASAPI FAILED EVENT!");*/
  279. IAudioClient_Stop(this->hidden->client);
  280. SDL_OpenedAudioDeviceDisconnected(this);
  281. }
  282. }
  283. }
  284. static int
  285. WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
  286. {
  287. SDL_AudioStream *stream = this->hidden->capturestream;
  288. const int avail = SDL_AudioStreamAvailable(stream);
  289. if (avail > 0) {
  290. const int cpy = SDL_min(buflen, avail);
  291. SDL_AudioStreamGet(stream, buffer, cpy);
  292. return cpy;
  293. }
  294. while (RecoverWasapiIfLost(this)) {
  295. HRESULT ret;
  296. BYTE *ptr = NULL;
  297. UINT32 frames = 0;
  298. DWORD flags = 0;
  299. /* uhoh, client isn't activated yet, just return silence. */
  300. if (!this->hidden->capture) {
  301. /* Delay so we run at about the speed that audio would be arriving. */
  302. SDL_Delay(((this->spec.samples * 1000) / this->spec.freq));
  303. SDL_memset(buffer, this->spec.silence, buflen);
  304. return buflen;
  305. }
  306. ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  307. if (ret != AUDCLNT_S_BUFFER_EMPTY) {
  308. WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
  309. }
  310. if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) {
  311. WASAPI_WaitDevice(this);
  312. } else if (ret == S_OK) {
  313. const int total = ((int) frames) * this->hidden->framesize;
  314. const int cpy = SDL_min(buflen, total);
  315. const int leftover = total - cpy;
  316. const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
  317. if (silent) {
  318. SDL_memset(buffer, this->spec.silence, cpy);
  319. } else {
  320. SDL_memcpy(buffer, ptr, cpy);
  321. }
  322. if (leftover > 0) {
  323. ptr += cpy;
  324. if (silent) {
  325. SDL_memset(ptr, this->spec.silence, leftover); /* I guess this is safe? */
  326. }
  327. if (SDL_AudioStreamPut(stream, ptr, leftover) == -1) {
  328. return -1; /* uhoh, out of memory, etc. Kill device. :( */
  329. }
  330. }
  331. ret = IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames);
  332. WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
  333. return cpy;
  334. }
  335. }
  336. return -1; /* unrecoverable error. */
  337. }
  338. static void
  339. WASAPI_FlushCapture(_THIS)
  340. {
  341. BYTE *ptr = NULL;
  342. UINT32 frames = 0;
  343. DWORD flags = 0;
  344. if (!this->hidden->capture) {
  345. return; /* not activated yet? */
  346. }
  347. /* just read until we stop getting packets, throwing them away. */
  348. while (SDL_TRUE) {
  349. const HRESULT ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
  350. if (ret == AUDCLNT_S_BUFFER_EMPTY) {
  351. break; /* no more buffered data; we're done. */
  352. } else if (WasapiFailed(this, ret)) {
  353. break; /* failed for some other reason, abort. */
  354. } else if (WasapiFailed(this, IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames))) {
  355. break; /* something broke. */
  356. }
  357. }
  358. SDL_AudioStreamClear(this->hidden->capturestream);
  359. }
  360. static void
  361. ReleaseWasapiDevice(_THIS)
  362. {
  363. if (this->hidden->client) {
  364. IAudioClient_Stop(this->hidden->client);
  365. IAudioClient_Release(this->hidden->client);
  366. this->hidden->client = NULL;
  367. }
  368. if (this->hidden->render) {
  369. IAudioRenderClient_Release(this->hidden->render);
  370. this->hidden->render = NULL;
  371. }
  372. if (this->hidden->capture) {
  373. IAudioCaptureClient_Release(this->hidden->capture);
  374. this->hidden->capture = NULL;
  375. }
  376. if (this->hidden->waveformat) {
  377. CoTaskMemFree(this->hidden->waveformat);
  378. this->hidden->waveformat = NULL;
  379. }
  380. if (this->hidden->capturestream) {
  381. SDL_FreeAudioStream(this->hidden->capturestream);
  382. this->hidden->capturestream = NULL;
  383. }
  384. if (this->hidden->activation_handler) {
  385. WASAPI_PlatformDeleteActivationHandler(this->hidden->activation_handler);
  386. this->hidden->activation_handler = NULL;
  387. }
  388. if (this->hidden->event) {
  389. CloseHandle(this->hidden->event);
  390. this->hidden->event = NULL;
  391. }
  392. }
  393. static void
  394. WASAPI_CloseDevice(_THIS)
  395. {
  396. WASAPI_UnrefDevice(this);
  397. }
  398. void
  399. WASAPI_RefDevice(_THIS)
  400. {
  401. SDL_AtomicIncRef(&this->hidden->refcount);
  402. }
  403. void
  404. WASAPI_UnrefDevice(_THIS)
  405. {
  406. if (!SDL_AtomicDecRef(&this->hidden->refcount)) {
  407. return;
  408. }
  409. /* actual closing happens here. */
  410. /* don't touch this->hidden->task in here; it has to be reverted from
  411. our callback thread. We do that in WASAPI_ThreadDeinit().
  412. (likewise for this->hidden->coinitialized). */
  413. ReleaseWasapiDevice(this);
  414. SDL_free(this->hidden->devid);
  415. SDL_free(this->hidden);
  416. }
  417. /* This is called once a device is activated, possibly asynchronously. */
  418. int
  419. WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
  420. {
  421. /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
  422. !!! it will write into the kernel's audio buffer directly instead of
  423. !!! shared memory that a user-mode mixer then writes to the kernel with
  424. !!! everything else. Doing this means any other sound using this device will
  425. !!! stop playing, including the user's MP3 player and system notification
  426. !!! sounds. You'd probably need to release the device when the app isn't in
  427. !!! the foreground, to be a good citizen of the system. It's doable, but it's
  428. !!! more work and causes some annoyances, and I don't know what the latency
  429. !!! wins actually look like. Maybe add a hint to force exclusive mode at
  430. !!! some point. To be sure, defaulting to shared mode is the right thing to
  431. !!! do in any case. */
  432. const SDL_AudioSpec oldspec = this->spec;
  433. const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
  434. UINT32 bufsize = 0; /* this is in sample frames, not samples, not bytes. */
  435. REFERENCE_TIME default_period = 0;
  436. IAudioClient *client = this->hidden->client;
  437. IAudioRenderClient *render = NULL;
  438. IAudioCaptureClient *capture = NULL;
  439. WAVEFORMATEX *waveformat = NULL;
  440. SDL_AudioFormat test_format;
  441. SDL_AudioFormat wasapi_format = 0;
  442. HRESULT ret = S_OK;
  443. DWORD streamflags = 0;
  444. SDL_assert(client != NULL);
  445. #ifdef __WINRT__ /* CreateEventEx() arrived in Vista, so we need an #ifdef for XP. */
  446. this->hidden->event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
  447. #else
  448. this->hidden->event = CreateEventW(NULL, 0, 0, NULL);
  449. #endif
  450. if (this->hidden->event == NULL) {
  451. return WIN_SetError("WASAPI can't create an event handle");
  452. }
  453. ret = IAudioClient_GetMixFormat(client, &waveformat);
  454. if (FAILED(ret)) {
  455. return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret);
  456. }
  457. SDL_assert(waveformat != NULL);
  458. this->hidden->waveformat = waveformat;
  459. this->spec.channels = (Uint8) waveformat->nChannels;
  460. /* Make sure we have a valid format that we can convert to whatever WASAPI wants. */
  461. wasapi_format = WaveFormatToSDLFormat(waveformat);
  462. for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) {
  463. if (test_format == wasapi_format) {
  464. this->spec.format = test_format;
  465. break;
  466. }
  467. }
  468. if (!test_format) {
  469. return SDL_SetError("%s: Unsupported audio format", "wasapi");
  470. }
  471. ret = IAudioClient_GetDevicePeriod(client, &default_period, NULL);
  472. if (FAILED(ret)) {
  473. return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret);
  474. }
  475. #if 1 /* we're getting reports that WASAPI's resampler introduces distortions, so it's disabled for now. --ryan. */
  476. this->spec.freq = waveformat->nSamplesPerSec; /* force sampling rate so our resampler kicks in, if necessary. */
  477. #else
  478. /* favor WASAPI's resampler over our own */
  479. if (this->spec.freq != waveformat->nSamplesPerSec) {
  480. streamflags |= (AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY);
  481. waveformat->nSamplesPerSec = this->spec.freq;
  482. waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nChannels * (waveformat->wBitsPerSample / 8);
  483. }
  484. #endif
  485. streamflags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  486. ret = IAudioClient_Initialize(client, sharemode, streamflags, 0, 0, waveformat, NULL);
  487. if (FAILED(ret)) {
  488. return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret);
  489. }
  490. ret = IAudioClient_SetEventHandle(client, this->hidden->event);
  491. if (FAILED(ret)) {
  492. return WIN_SetErrorFromHRESULT("WASAPI can't set event handle", ret);
  493. }
  494. ret = IAudioClient_GetBufferSize(client, &bufsize);
  495. if (FAILED(ret)) {
  496. return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret);
  497. }
  498. /* Match the callback size to the period size to cut down on the number of
  499. interrupts waited for in each call to WaitDevice */
  500. {
  501. const float period_millis = default_period / 10000.0f;
  502. const float period_frames = period_millis * this->spec.freq / 1000.0f;
  503. this->spec.samples = (Uint16)SDL_ceilf(period_frames);
  504. }
  505. /* Update the fragment size as size in bytes */
  506. SDL_CalculateAudioSpec(&this->spec);
  507. this->hidden->framesize = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
  508. if (this->iscapture) {
  509. this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
  510. if (!this->hidden->capturestream) {
  511. return -1; /* already set SDL_Error */
  512. }
  513. ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void**) &capture);
  514. if (FAILED(ret)) {
  515. return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
  516. }
  517. SDL_assert(capture != NULL);
  518. this->hidden->capture = capture;
  519. ret = IAudioClient_Start(client);
  520. if (FAILED(ret)) {
  521. return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret);
  522. }
  523. WASAPI_FlushCapture(this); /* MSDN says you should flush capture endpoint right after startup. */
  524. } else {
  525. ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void**) &render);
  526. if (FAILED(ret)) {
  527. return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
  528. }
  529. SDL_assert(render != NULL);
  530. this->hidden->render = render;
  531. ret = IAudioClient_Start(client);
  532. if (FAILED(ret)) {
  533. return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret);
  534. }
  535. }
  536. if (updatestream) {
  537. return UpdateAudioStream(this, &oldspec);
  538. }
  539. return 0; /* good to go. */
  540. }
  541. static int
  542. WASAPI_OpenDevice(_THIS, const char *devname)
  543. {
  544. LPCWSTR devid = (LPCWSTR) this->handle;
  545. /* Initialize all variables that we clean on shutdown */
  546. this->hidden = (struct SDL_PrivateAudioData *)
  547. SDL_malloc((sizeof *this->hidden));
  548. if (this->hidden == NULL) {
  549. return SDL_OutOfMemory();
  550. }
  551. SDL_zerop(this->hidden);
  552. WASAPI_RefDevice(this); /* so CloseDevice() will unref to zero. */
  553. if (!devid) { /* is default device? */
  554. this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
  555. } else {
  556. this->hidden->devid = SDL_wcsdup(devid);
  557. if (!this->hidden->devid) {
  558. return SDL_OutOfMemory();
  559. }
  560. }
  561. if (WASAPI_ActivateDevice(this, SDL_FALSE) == -1) {
  562. return -1; /* already set error. */
  563. }
  564. /* Ready, but waiting for async device activation.
  565. Until activation is successful, we will report silence from capture
  566. devices and ignore data on playback devices.
  567. Also, since we don't know the _actual_ device format until after
  568. activation, we let the app have whatever it asks for. We set up
  569. an SDL_AudioStream to convert, if necessary, once the activation
  570. completes. */
  571. return 0;
  572. }
  573. static void
  574. WASAPI_ThreadInit(_THIS)
  575. {
  576. WASAPI_PlatformThreadInit(this);
  577. }
  578. static void
  579. WASAPI_ThreadDeinit(_THIS)
  580. {
  581. WASAPI_PlatformThreadDeinit(this);
  582. }
  583. static void
  584. WASAPI_Deinitialize(void)
  585. {
  586. DevIdList *devidlist;
  587. DevIdList *next;
  588. WASAPI_PlatformDeinit();
  589. for (devidlist = deviceid_list; devidlist; devidlist = next) {
  590. next = devidlist->next;
  591. SDL_free(devidlist->str);
  592. SDL_free(devidlist);
  593. }
  594. deviceid_list = NULL;
  595. }
  596. static SDL_bool
  597. WASAPI_Init(SDL_AudioDriverImpl * impl)
  598. {
  599. SDL_AtomicSet(&WASAPI_DefaultPlaybackGeneration, 1);
  600. SDL_AtomicSet(&WASAPI_DefaultCaptureGeneration, 1);
  601. if (WASAPI_PlatformInit() == -1) {
  602. return SDL_FALSE;
  603. }
  604. /* Set the function pointers */
  605. impl->DetectDevices = WASAPI_DetectDevices;
  606. impl->ThreadInit = WASAPI_ThreadInit;
  607. impl->ThreadDeinit = WASAPI_ThreadDeinit;
  608. impl->OpenDevice = WASAPI_OpenDevice;
  609. impl->PlayDevice = WASAPI_PlayDevice;
  610. impl->WaitDevice = WASAPI_WaitDevice;
  611. impl->GetDeviceBuf = WASAPI_GetDeviceBuf;
  612. impl->CaptureFromDevice = WASAPI_CaptureFromDevice;
  613. impl->FlushCapture = WASAPI_FlushCapture;
  614. impl->CloseDevice = WASAPI_CloseDevice;
  615. impl->Deinitialize = WASAPI_Deinitialize;
  616. impl->HasCaptureSupport = SDL_TRUE;
  617. return SDL_TRUE; /* this audio target is available. */
  618. }
  619. AudioBootStrap WASAPI_bootstrap = {
  620. "wasapi", "WASAPI", WASAPI_Init, SDL_FALSE
  621. };
  622. #endif /* SDL_AUDIO_DRIVER_WASAPI */
  623. /* vi: set ts=4 sw=4 expandtab: */