SDL_wasapi.c 26 KB

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