audio_driver_wasapi.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. /**************************************************************************/
  2. /* audio_driver_wasapi.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifdef WASAPI_ENABLED
  31. #include "audio_driver_wasapi.h"
  32. #include "core/os/os.h"
  33. #include "core/project_settings.h"
  34. #include <functiondiscoverykeys.h>
  35. #ifndef PKEY_Device_FriendlyName
  36. #undef DEFINE_PROPERTYKEY
  37. /* clang-format off */
  38. #define DEFINE_PROPERTYKEY(id, a, b, c, d, e, f, g, h, i, j, k, l) \
  39. const PROPERTYKEY id = { { a, b, c, { d, e, f, g, h, i, j, k, } }, l };
  40. /* clang-format on */
  41. DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);
  42. #endif
  43. const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
  44. const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
  45. const IID IID_IAudioClient = __uuidof(IAudioClient);
  46. const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
  47. const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);
  48. #define SAFE_RELEASE(memory) \
  49. if ((memory) != NULL) { \
  50. (memory)->Release(); \
  51. (memory) = NULL; \
  52. }
  53. #define REFTIMES_PER_SEC 10000000
  54. #define REFTIMES_PER_MILLISEC 10000
  55. #define CAPTURE_BUFFER_CHANNELS 2
  56. static bool default_render_device_changed = false;
  57. static bool default_capture_device_changed = false;
  58. class CMMNotificationClient : public IMMNotificationClient {
  59. LONG _cRef;
  60. IMMDeviceEnumerator *_pEnumerator;
  61. public:
  62. CMMNotificationClient() :
  63. _cRef(1),
  64. _pEnumerator(NULL) {}
  65. virtual ~CMMNotificationClient() {
  66. if ((_pEnumerator) != NULL) {
  67. (_pEnumerator)->Release();
  68. (_pEnumerator) = NULL;
  69. }
  70. }
  71. ULONG STDMETHODCALLTYPE AddRef() {
  72. return InterlockedIncrement(&_cRef);
  73. }
  74. ULONG STDMETHODCALLTYPE Release() {
  75. ULONG ulRef = InterlockedDecrement(&_cRef);
  76. if (0 == ulRef) {
  77. delete this;
  78. }
  79. return ulRef;
  80. }
  81. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {
  82. if (IID_IUnknown == riid) {
  83. AddRef();
  84. *ppvInterface = (IUnknown *)this;
  85. } else if (__uuidof(IMMNotificationClient) == riid) {
  86. AddRef();
  87. *ppvInterface = (IMMNotificationClient *)this;
  88. } else {
  89. *ppvInterface = NULL;
  90. return E_NOINTERFACE;
  91. }
  92. return S_OK;
  93. }
  94. HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
  95. return S_OK;
  96. };
  97. HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
  98. return S_OK;
  99. }
  100. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
  101. return S_OK;
  102. }
  103. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
  104. if (role == eConsole) {
  105. if (flow == eRender) {
  106. default_render_device_changed = true;
  107. } else if (flow == eCapture) {
  108. default_capture_device_changed = true;
  109. }
  110. }
  111. return S_OK;
  112. }
  113. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
  114. return S_OK;
  115. }
  116. };
  117. static CMMNotificationClient notif_client;
  118. Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_capture, bool reinit) {
  119. WAVEFORMATEX *pwfex;
  120. IMMDeviceEnumerator *enumerator = NULL;
  121. IMMDevice *device = NULL;
  122. CoInitialize(NULL);
  123. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  124. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  125. if (p_device->device_name == "Default") {
  126. hr = enumerator->GetDefaultAudioEndpoint(p_capture ? eCapture : eRender, eConsole, &device);
  127. } else {
  128. IMMDeviceCollection *devices = NULL;
  129. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  130. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  131. LPWSTR strId = NULL;
  132. bool found = false;
  133. UINT count = 0;
  134. hr = devices->GetCount(&count);
  135. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  136. for (ULONG i = 0; i < count && !found; i++) {
  137. IMMDevice *tmp_device = NULL;
  138. hr = devices->Item(i, &tmp_device);
  139. ERR_BREAK(hr != S_OK);
  140. IPropertyStore *props = NULL;
  141. hr = tmp_device->OpenPropertyStore(STGM_READ, &props);
  142. ERR_BREAK(hr != S_OK);
  143. PROPVARIANT propvar;
  144. PropVariantInit(&propvar);
  145. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  146. ERR_BREAK(hr != S_OK);
  147. if (p_device->device_name == String(propvar.pwszVal)) {
  148. hr = tmp_device->GetId(&strId);
  149. ERR_BREAK(hr != S_OK);
  150. found = true;
  151. }
  152. PropVariantClear(&propvar);
  153. props->Release();
  154. tmp_device->Release();
  155. }
  156. if (found) {
  157. hr = enumerator->GetDevice(strId, &device);
  158. }
  159. if (strId) {
  160. CoTaskMemFree(strId);
  161. }
  162. if (device == NULL) {
  163. hr = enumerator->GetDefaultAudioEndpoint(p_capture ? eCapture : eRender, eConsole, &device);
  164. }
  165. }
  166. if (reinit) {
  167. // In case we're trying to re-initialize the device prevent throwing this error on the console,
  168. // otherwise if there is currently no device available this will spam the console.
  169. if (hr != S_OK) {
  170. return ERR_CANT_OPEN;
  171. }
  172. } else {
  173. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  174. }
  175. hr = enumerator->RegisterEndpointNotificationCallback(&notif_client);
  176. SAFE_RELEASE(enumerator)
  177. if (hr != S_OK) {
  178. ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");
  179. }
  180. hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&p_device->audio_client);
  181. SAFE_RELEASE(device)
  182. if (reinit) {
  183. if (hr != S_OK) {
  184. return ERR_CANT_OPEN;
  185. }
  186. } else {
  187. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  188. }
  189. hr = p_device->audio_client->GetMixFormat(&pwfex);
  190. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  191. print_verbose("WASAPI: wFormatTag = " + itos(pwfex->wFormatTag));
  192. print_verbose("WASAPI: nChannels = " + itos(pwfex->nChannels));
  193. print_verbose("WASAPI: nSamplesPerSec = " + itos(pwfex->nSamplesPerSec));
  194. print_verbose("WASAPI: nAvgBytesPerSec = " + itos(pwfex->nAvgBytesPerSec));
  195. print_verbose("WASAPI: nBlockAlign = " + itos(pwfex->nBlockAlign));
  196. print_verbose("WASAPI: wBitsPerSample = " + itos(pwfex->wBitsPerSample));
  197. print_verbose("WASAPI: cbSize = " + itos(pwfex->cbSize));
  198. WAVEFORMATEX *closest = NULL;
  199. hr = p_device->audio_client->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, pwfex, &closest);
  200. if (hr == S_FALSE) {
  201. WARN_PRINT("WASAPI: Mix format is not supported by the Device");
  202. if (closest) {
  203. print_verbose("WASAPI: closest->wFormatTag = " + itos(closest->wFormatTag));
  204. print_verbose("WASAPI: closest->nChannels = " + itos(closest->nChannels));
  205. print_verbose("WASAPI: closest->nSamplesPerSec = " + itos(closest->nSamplesPerSec));
  206. print_verbose("WASAPI: closest->nAvgBytesPerSec = " + itos(closest->nAvgBytesPerSec));
  207. print_verbose("WASAPI: closest->nBlockAlign = " + itos(closest->nBlockAlign));
  208. print_verbose("WASAPI: closest->wBitsPerSample = " + itos(closest->wBitsPerSample));
  209. print_verbose("WASAPI: closest->cbSize = " + itos(closest->cbSize));
  210. WARN_PRINT("WASAPI: Using closest match instead");
  211. pwfex = closest;
  212. }
  213. }
  214. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  215. p_device->channels = pwfex->nChannels;
  216. p_device->format_tag = pwfex->wFormatTag;
  217. p_device->bits_per_sample = pwfex->wBitsPerSample;
  218. p_device->frame_size = (p_device->bits_per_sample / 8) * p_device->channels;
  219. if (p_device->format_tag == WAVE_FORMAT_EXTENSIBLE) {
  220. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  221. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  222. p_device->format_tag = WAVE_FORMAT_PCM;
  223. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  224. p_device->format_tag = WAVE_FORMAT_IEEE_FLOAT;
  225. } else {
  226. ERR_PRINT("WASAPI: Format not supported");
  227. ERR_FAIL_V(ERR_CANT_OPEN);
  228. }
  229. } else {
  230. if (p_device->format_tag != WAVE_FORMAT_PCM && p_device->format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  231. ERR_PRINT("WASAPI: Format not supported");
  232. ERR_FAIL_V(ERR_CANT_OPEN);
  233. }
  234. }
  235. DWORD streamflags = 0;
  236. if ((DWORD)mix_rate != pwfex->nSamplesPerSec) {
  237. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  238. pwfex->nSamplesPerSec = mix_rate;
  239. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  240. }
  241. hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_capture ? REFTIMES_PER_SEC : 0, 0, pwfex, NULL);
  242. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16) + ".");
  243. if (p_capture) {
  244. hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);
  245. } else {
  246. hr = p_device->audio_client->GetService(IID_IAudioRenderClient, (void **)&p_device->render_client);
  247. }
  248. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  249. // Free memory
  250. CoTaskMemFree(pwfex);
  251. SAFE_RELEASE(device)
  252. return OK;
  253. }
  254. Error AudioDriverWASAPI::init_render_device(bool reinit) {
  255. Error err = audio_device_init(&audio_output, false, reinit);
  256. if (err != OK)
  257. return err;
  258. switch (audio_output.channels) {
  259. case 1: // Mono
  260. case 3: // Surround 2.1
  261. case 5: // Surround 5.0
  262. case 7: // Surround 7.0
  263. // We will downmix as required.
  264. channels = audio_output.channels + 1;
  265. break;
  266. case 2: // Stereo
  267. case 4: // Surround 3.1
  268. case 6: // Surround 5.1
  269. case 8: // Surround 7.1
  270. channels = audio_output.channels;
  271. break;
  272. default:
  273. WARN_PRINT("WASAPI: Unsupported number of channels: " + itos(audio_output.channels));
  274. channels = 2;
  275. break;
  276. }
  277. UINT32 max_frames;
  278. HRESULT hr = audio_output.audio_client->GetBufferSize(&max_frames);
  279. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  280. // Due to WASAPI Shared Mode we have no control of the buffer size
  281. buffer_frames = max_frames;
  282. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  283. samples_in.resize(buffer_frames * channels);
  284. input_position = 0;
  285. input_size = 0;
  286. print_verbose("WASAPI: detected " + itos(audio_output.channels) + " channels");
  287. print_verbose("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  288. return OK;
  289. }
  290. Error AudioDriverWASAPI::init_capture_device(bool reinit) {
  291. Error err = audio_device_init(&audio_input, true, reinit);
  292. if (err != OK)
  293. return err;
  294. // Get the max frames
  295. UINT32 max_frames;
  296. HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames);
  297. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  298. input_buffer_init(max_frames);
  299. return OK;
  300. }
  301. Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {
  302. if (p_device->active.is_set()) {
  303. if (p_device->audio_client) {
  304. p_device->audio_client->Stop();
  305. }
  306. p_device->active.clear();
  307. }
  308. SAFE_RELEASE(p_device->audio_client)
  309. SAFE_RELEASE(p_device->render_client)
  310. SAFE_RELEASE(p_device->capture_client)
  311. return OK;
  312. }
  313. Error AudioDriverWASAPI::finish_render_device() {
  314. return audio_device_finish(&audio_output);
  315. }
  316. Error AudioDriverWASAPI::finish_capture_device() {
  317. return audio_device_finish(&audio_input);
  318. }
  319. Error AudioDriverWASAPI::init() {
  320. mix_rate = GLOBAL_GET("audio/mix_rate");
  321. exit_thread.clear();
  322. Error err = init_render_device();
  323. ERR_FAIL_COND_V_MSG(err != OK, err, "WASAPI: init_render_device error.");
  324. thread.start(thread_func, this);
  325. return OK;
  326. }
  327. int AudioDriverWASAPI::get_mix_rate() const {
  328. return mix_rate;
  329. }
  330. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  331. return get_speaker_mode_by_total_channels(channels);
  332. }
  333. Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
  334. Array list;
  335. IMMDeviceCollection *devices = NULL;
  336. IMMDeviceEnumerator *enumerator = NULL;
  337. list.push_back(String("Default"));
  338. CoInitialize(NULL);
  339. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  340. ERR_FAIL_COND_V(hr != S_OK, Array());
  341. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  342. ERR_FAIL_COND_V(hr != S_OK, Array());
  343. UINT count = 0;
  344. hr = devices->GetCount(&count);
  345. ERR_FAIL_COND_V(hr != S_OK, Array());
  346. for (ULONG i = 0; i < count; i++) {
  347. IMMDevice *device = NULL;
  348. hr = devices->Item(i, &device);
  349. ERR_BREAK(hr != S_OK);
  350. IPropertyStore *props = NULL;
  351. hr = device->OpenPropertyStore(STGM_READ, &props);
  352. ERR_BREAK(hr != S_OK);
  353. PROPVARIANT propvar;
  354. PropVariantInit(&propvar);
  355. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  356. ERR_BREAK(hr != S_OK);
  357. list.push_back(String(propvar.pwszVal));
  358. PropVariantClear(&propvar);
  359. props->Release();
  360. device->Release();
  361. }
  362. devices->Release();
  363. enumerator->Release();
  364. return list;
  365. }
  366. Array AudioDriverWASAPI::get_device_list() {
  367. return audio_device_get_list(false);
  368. }
  369. String AudioDriverWASAPI::get_device() {
  370. lock();
  371. String name = audio_output.device_name;
  372. unlock();
  373. return name;
  374. }
  375. void AudioDriverWASAPI::set_device(String device) {
  376. lock();
  377. audio_output.new_device = device;
  378. unlock();
  379. }
  380. int32_t AudioDriverWASAPI::read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i) {
  381. if (format_tag == WAVE_FORMAT_PCM) {
  382. int32_t sample = 0;
  383. switch (bits_per_sample) {
  384. case 8:
  385. sample = int32_t(((int8_t *)buffer)[i]) << 24;
  386. break;
  387. case 16:
  388. sample = int32_t(((int16_t *)buffer)[i]) << 16;
  389. break;
  390. case 24:
  391. sample |= int32_t(((int8_t *)buffer)[i * 3 + 2]) << 24;
  392. sample |= int32_t(((int8_t *)buffer)[i * 3 + 1]) << 16;
  393. sample |= int32_t(((int8_t *)buffer)[i * 3 + 0]) << 8;
  394. break;
  395. case 32:
  396. sample = ((int32_t *)buffer)[i];
  397. break;
  398. }
  399. return sample;
  400. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  401. return int32_t(((float *)buffer)[i] * 32768.0) << 16;
  402. } else {
  403. ERR_PRINT("WASAPI: Unknown format tag");
  404. }
  405. return 0;
  406. }
  407. void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample) {
  408. if (format_tag == WAVE_FORMAT_PCM) {
  409. switch (bits_per_sample) {
  410. case 8:
  411. ((int8_t *)buffer)[i] = sample >> 24;
  412. break;
  413. case 16:
  414. ((int16_t *)buffer)[i] = sample >> 16;
  415. break;
  416. case 24:
  417. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  418. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  419. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  420. break;
  421. case 32:
  422. ((int32_t *)buffer)[i] = sample;
  423. break;
  424. }
  425. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  426. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  427. } else {
  428. ERR_PRINT("WASAPI: Unknown format tag");
  429. }
  430. }
  431. void AudioDriverWASAPI::thread_func(void *p_udata) {
  432. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  433. uint32_t avail_frames = 0;
  434. uint32_t write_ofs = 0;
  435. while (!ad->exit_thread.is_set()) {
  436. uint32_t read_frames = 0;
  437. uint32_t written_frames = 0;
  438. if (avail_frames == 0) {
  439. ad->lock();
  440. ad->start_counting_ticks();
  441. if (ad->audio_output.active.is_set()) {
  442. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  443. } else {
  444. for (int i = 0; i < ad->samples_in.size(); i++) {
  445. ad->samples_in.write[i] = 0;
  446. }
  447. }
  448. avail_frames = ad->buffer_frames;
  449. write_ofs = 0;
  450. ad->stop_counting_ticks();
  451. ad->unlock();
  452. }
  453. ad->lock();
  454. ad->start_counting_ticks();
  455. if (avail_frames > 0 && ad->audio_output.audio_client) {
  456. UINT32 cur_frames;
  457. bool invalidated = false;
  458. HRESULT hr = ad->audio_output.audio_client->GetCurrentPadding(&cur_frames);
  459. if (hr == S_OK) {
  460. // Check how much frames are available on the WASAPI buffer
  461. UINT32 write_frames = MIN(ad->buffer_frames - cur_frames, avail_frames);
  462. if (write_frames > 0) {
  463. BYTE *buffer = NULL;
  464. hr = ad->audio_output.render_client->GetBuffer(write_frames, &buffer);
  465. if (hr == S_OK) {
  466. // We're using WASAPI Shared Mode so we must convert the buffer
  467. if (ad->channels == ad->audio_output.channels) {
  468. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  469. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i, ad->samples_in.write[write_ofs++]);
  470. }
  471. } else if (ad->channels == ad->audio_output.channels + 1) {
  472. // Pass all channels except the last two as-is, and then mix the last two
  473. // together as one channel. E.g. stereo -> mono, or 3.1 -> 2.1.
  474. unsigned int last_chan = ad->audio_output.channels - 1;
  475. for (unsigned int i = 0; i < write_frames; i++) {
  476. for (unsigned int j = 0; j < last_chan; j++) {
  477. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, ad->samples_in.write[write_ofs++]);
  478. }
  479. int32_t l = ad->samples_in.write[write_ofs++];
  480. int32_t r = ad->samples_in.write[write_ofs++];
  481. int32_t c = (int32_t)(((int64_t)l + (int64_t)r) / 2);
  482. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + last_chan, c);
  483. }
  484. } else {
  485. for (unsigned int i = 0; i < write_frames; i++) {
  486. for (unsigned int j = 0; j < MIN(ad->channels, ad->audio_output.channels); j++) {
  487. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, ad->samples_in.write[write_ofs++]);
  488. }
  489. if (ad->audio_output.channels > ad->channels) {
  490. for (unsigned int j = ad->channels; j < ad->audio_output.channels; j++) {
  491. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, 0);
  492. }
  493. }
  494. }
  495. }
  496. hr = ad->audio_output.render_client->ReleaseBuffer(write_frames, 0);
  497. if (hr != S_OK) {
  498. ERR_PRINT("WASAPI: Release buffer error");
  499. }
  500. avail_frames -= write_frames;
  501. written_frames += write_frames;
  502. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  503. // Device is not valid anymore, reopen it
  504. Error err = ad->finish_render_device();
  505. if (err != OK) {
  506. ERR_PRINT("WASAPI: finish_render_device error");
  507. } else {
  508. // We reopened the device and samples_in may have resized, so invalidate the current avail_frames
  509. avail_frames = 0;
  510. }
  511. } else {
  512. ERR_PRINT("WASAPI: Get buffer error");
  513. ad->exit_thread.set();
  514. }
  515. }
  516. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  517. invalidated = true;
  518. } else {
  519. ERR_PRINT("WASAPI: GetCurrentPadding error");
  520. }
  521. if (invalidated) {
  522. // Device is not valid anymore
  523. WARN_PRINT("WASAPI: Current device invalidated, closing device");
  524. Error err = ad->finish_render_device();
  525. if (err != OK) {
  526. ERR_PRINT("WASAPI: finish_render_device error");
  527. }
  528. }
  529. }
  530. // If we're using the Default device and it changed finish it so we'll re-init the device
  531. if (ad->audio_output.device_name == "Default" && default_render_device_changed) {
  532. Error err = ad->finish_render_device();
  533. if (err != OK) {
  534. ERR_PRINT("WASAPI: finish_render_device error");
  535. }
  536. default_render_device_changed = false;
  537. }
  538. // User selected a new device, finish the current one so we'll init the new device
  539. if (ad->audio_output.device_name != ad->audio_output.new_device) {
  540. ad->audio_output.device_name = ad->audio_output.new_device;
  541. Error err = ad->finish_render_device();
  542. if (err != OK) {
  543. ERR_PRINT("WASAPI: finish_render_device error");
  544. }
  545. }
  546. if (!ad->audio_output.audio_client) {
  547. Error err = ad->init_render_device(true);
  548. if (err == OK) {
  549. ad->start();
  550. }
  551. avail_frames = 0;
  552. write_ofs = 0;
  553. }
  554. if (ad->audio_input.active.is_set()) {
  555. UINT32 packet_length = 0;
  556. BYTE *data;
  557. UINT32 num_frames_available;
  558. DWORD flags;
  559. HRESULT hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  560. if (hr == S_OK) {
  561. while (packet_length != 0) {
  562. hr = ad->audio_input.capture_client->GetBuffer(&data, &num_frames_available, &flags, NULL, NULL);
  563. ERR_BREAK(hr != S_OK);
  564. // fixme: Only works for floating point atm
  565. for (UINT32 j = 0; j < num_frames_available; j++) {
  566. int32_t l, r;
  567. if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
  568. l = r = 0;
  569. } else {
  570. if (ad->audio_input.channels == 2) {
  571. l = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2);
  572. r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2 + 1);
  573. } else if (ad->audio_input.channels == 1) {
  574. l = r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j);
  575. } else {
  576. l = r = 0;
  577. ERR_PRINT("WASAPI: unsupported channel count in microphone!");
  578. }
  579. }
  580. ad->input_buffer_write(l);
  581. ad->input_buffer_write(r);
  582. }
  583. read_frames += num_frames_available;
  584. hr = ad->audio_input.capture_client->ReleaseBuffer(num_frames_available);
  585. ERR_BREAK(hr != S_OK);
  586. hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  587. ERR_BREAK(hr != S_OK);
  588. }
  589. }
  590. // If we're using the Default device and it changed finish it so we'll re-init the device
  591. if (ad->audio_input.device_name == "Default" && default_capture_device_changed) {
  592. Error err = ad->finish_capture_device();
  593. if (err != OK) {
  594. ERR_PRINT("WASAPI: finish_capture_device error");
  595. }
  596. default_capture_device_changed = false;
  597. }
  598. // User selected a new device, finish the current one so we'll init the new device
  599. if (ad->audio_input.device_name != ad->audio_input.new_device) {
  600. ad->audio_input.device_name = ad->audio_input.new_device;
  601. Error err = ad->finish_capture_device();
  602. if (err != OK) {
  603. ERR_PRINT("WASAPI: finish_capture_device error");
  604. }
  605. }
  606. if (!ad->audio_input.audio_client) {
  607. Error err = ad->init_capture_device(true);
  608. if (err == OK) {
  609. ad->capture_start();
  610. }
  611. }
  612. }
  613. ad->stop_counting_ticks();
  614. ad->unlock();
  615. // Let the thread rest a while if we haven't read or write anything
  616. if (written_frames == 0 && read_frames == 0) {
  617. OS::get_singleton()->delay_usec(1000);
  618. }
  619. }
  620. }
  621. void AudioDriverWASAPI::start() {
  622. if (audio_output.audio_client) {
  623. HRESULT hr = audio_output.audio_client->Start();
  624. if (hr != S_OK) {
  625. ERR_PRINT("WASAPI: Start failed");
  626. } else {
  627. audio_output.active.set();
  628. }
  629. }
  630. }
  631. void AudioDriverWASAPI::lock() {
  632. mutex.lock();
  633. }
  634. void AudioDriverWASAPI::unlock() {
  635. mutex.unlock();
  636. }
  637. void AudioDriverWASAPI::finish() {
  638. exit_thread.set();
  639. thread.wait_to_finish();
  640. finish_capture_device();
  641. finish_render_device();
  642. }
  643. Error AudioDriverWASAPI::capture_start() {
  644. Error err = init_capture_device();
  645. if (err != OK) {
  646. ERR_PRINT("WASAPI: init_capture_device error");
  647. return err;
  648. }
  649. if (audio_input.active.is_set()) {
  650. return FAILED;
  651. }
  652. audio_input.audio_client->Start();
  653. audio_input.active.set();
  654. return OK;
  655. }
  656. Error AudioDriverWASAPI::capture_stop() {
  657. if (audio_input.active.is_set()) {
  658. audio_input.audio_client->Stop();
  659. audio_input.active.clear();
  660. return OK;
  661. }
  662. return FAILED;
  663. }
  664. void AudioDriverWASAPI::capture_set_device(const String &p_name) {
  665. lock();
  666. audio_input.new_device = p_name;
  667. unlock();
  668. }
  669. Array AudioDriverWASAPI::capture_get_device_list() {
  670. return audio_device_get_list(true);
  671. }
  672. String AudioDriverWASAPI::capture_get_device() {
  673. lock();
  674. String name = audio_input.device_name;
  675. unlock();
  676. return name;
  677. }
  678. AudioDriverWASAPI::AudioDriverWASAPI() {
  679. samples_in.clear();
  680. channels = 0;
  681. mix_rate = 0;
  682. buffer_frames = 0;
  683. }
  684. #endif