audio_driver_wasapi.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*************************************************************************/
  2. /* audio_driver_wasapi.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
  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. ~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 *device = NULL;
  138. hr = devices->Item(i, &device);
  139. ERR_BREAK(hr != S_OK);
  140. IPropertyStore *props = NULL;
  141. hr = 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 = device->GetId(&strId);
  149. ERR_BREAK(hr != S_OK);
  150. found = true;
  151. }
  152. PropVariantClear(&propvar);
  153. props->Release();
  154. 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. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  192. p_device->channels = pwfex->nChannels;
  193. p_device->format_tag = pwfex->wFormatTag;
  194. p_device->bits_per_sample = pwfex->wBitsPerSample;
  195. p_device->frame_size = (p_device->bits_per_sample / 8) * p_device->channels;
  196. if (p_device->format_tag == WAVE_FORMAT_EXTENSIBLE) {
  197. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  198. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  199. p_device->format_tag = WAVE_FORMAT_PCM;
  200. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  201. p_device->format_tag = WAVE_FORMAT_IEEE_FLOAT;
  202. } else {
  203. ERR_PRINT("WASAPI: Format not supported");
  204. ERR_FAIL_V(ERR_CANT_OPEN);
  205. }
  206. } else {
  207. if (p_device->format_tag != WAVE_FORMAT_PCM && p_device->format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  208. ERR_PRINT("WASAPI: Format not supported");
  209. ERR_FAIL_V(ERR_CANT_OPEN);
  210. }
  211. }
  212. DWORD streamflags = 0;
  213. if (mix_rate != pwfex->nSamplesPerSec) {
  214. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  215. pwfex->nSamplesPerSec = mix_rate;
  216. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  217. }
  218. hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_capture ? REFTIMES_PER_SEC : 0, 0, pwfex, NULL);
  219. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  220. if (p_capture) {
  221. hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);
  222. } else {
  223. hr = p_device->audio_client->GetService(IID_IAudioRenderClient, (void **)&p_device->render_client);
  224. }
  225. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  226. // Free memory
  227. CoTaskMemFree(pwfex);
  228. SAFE_RELEASE(device)
  229. return OK;
  230. }
  231. Error AudioDriverWASAPI::init_render_device(bool reinit) {
  232. Error err = audio_device_init(&audio_output, false, reinit);
  233. if (err != OK)
  234. return err;
  235. switch (audio_output.channels) {
  236. case 2: // Stereo
  237. case 4: // Surround 3.1
  238. case 6: // Surround 5.1
  239. case 8: // Surround 7.1
  240. channels = audio_output.channels;
  241. break;
  242. default:
  243. WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(audio_output.channels));
  244. channels = 2;
  245. break;
  246. }
  247. UINT32 max_frames;
  248. HRESULT hr = audio_output.audio_client->GetBufferSize(&max_frames);
  249. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  250. // Due to WASAPI Shared Mode we have no control of the buffer size
  251. buffer_frames = max_frames;
  252. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  253. samples_in.resize(buffer_frames * channels);
  254. input_position = 0;
  255. input_size = 0;
  256. print_verbose("WASAPI: detected " + itos(channels) + " channels");
  257. print_verbose("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  258. return OK;
  259. }
  260. Error AudioDriverWASAPI::init_capture_device(bool reinit) {
  261. Error err = audio_device_init(&audio_input, true, reinit);
  262. if (err != OK)
  263. return err;
  264. // Get the max frames
  265. UINT32 max_frames;
  266. HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames);
  267. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  268. // Set the buffer size
  269. input_buffer.resize(max_frames * CAPTURE_BUFFER_CHANNELS);
  270. input_position = 0;
  271. input_size = 0;
  272. return OK;
  273. }
  274. Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {
  275. if (p_device->active) {
  276. if (p_device->audio_client) {
  277. p_device->audio_client->Stop();
  278. }
  279. p_device->active = false;
  280. }
  281. SAFE_RELEASE(p_device->audio_client)
  282. SAFE_RELEASE(p_device->render_client)
  283. SAFE_RELEASE(p_device->capture_client)
  284. return OK;
  285. }
  286. Error AudioDriverWASAPI::finish_render_device() {
  287. return audio_device_finish(&audio_output);
  288. }
  289. Error AudioDriverWASAPI::finish_capture_device() {
  290. return audio_device_finish(&audio_input);
  291. }
  292. Error AudioDriverWASAPI::init() {
  293. mix_rate = GLOBAL_DEF_RST("audio/mix_rate", DEFAULT_MIX_RATE);
  294. Error err = init_render_device();
  295. if (err != OK) {
  296. ERR_PRINT("WASAPI: init_render_device error");
  297. }
  298. exit_thread = false;
  299. thread_exited = false;
  300. mutex = Mutex::create(true);
  301. thread = Thread::create(thread_func, this);
  302. return OK;
  303. }
  304. int AudioDriverWASAPI::get_mix_rate() const {
  305. return mix_rate;
  306. }
  307. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  308. return get_speaker_mode_by_total_channels(channels);
  309. }
  310. Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
  311. Array list;
  312. IMMDeviceCollection *devices = NULL;
  313. IMMDeviceEnumerator *enumerator = NULL;
  314. list.push_back(String("Default"));
  315. CoInitialize(NULL);
  316. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  317. ERR_FAIL_COND_V(hr != S_OK, Array());
  318. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  319. ERR_FAIL_COND_V(hr != S_OK, Array());
  320. UINT count = 0;
  321. hr = devices->GetCount(&count);
  322. ERR_FAIL_COND_V(hr != S_OK, Array());
  323. for (ULONG i = 0; i < count; i++) {
  324. IMMDevice *device = NULL;
  325. hr = devices->Item(i, &device);
  326. ERR_BREAK(hr != S_OK);
  327. IPropertyStore *props = NULL;
  328. hr = device->OpenPropertyStore(STGM_READ, &props);
  329. ERR_BREAK(hr != S_OK);
  330. PROPVARIANT propvar;
  331. PropVariantInit(&propvar);
  332. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  333. ERR_BREAK(hr != S_OK);
  334. list.push_back(String(propvar.pwszVal));
  335. PropVariantClear(&propvar);
  336. props->Release();
  337. device->Release();
  338. }
  339. devices->Release();
  340. enumerator->Release();
  341. return list;
  342. }
  343. Array AudioDriverWASAPI::get_device_list() {
  344. return audio_device_get_list(false);
  345. }
  346. String AudioDriverWASAPI::get_device() {
  347. lock();
  348. String name = audio_output.device_name;
  349. unlock();
  350. return name;
  351. }
  352. void AudioDriverWASAPI::set_device(String device) {
  353. lock();
  354. audio_output.new_device = device;
  355. unlock();
  356. }
  357. int32_t AudioDriverWASAPI::read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i) {
  358. if (format_tag == WAVE_FORMAT_PCM) {
  359. int32_t sample = 0;
  360. switch (bits_per_sample) {
  361. case 8:
  362. sample = int32_t(((int8_t *)buffer)[i]) << 24;
  363. break;
  364. case 16:
  365. sample = int32_t(((int16_t *)buffer)[i]) << 16;
  366. break;
  367. case 24:
  368. sample |= int32_t(((int8_t *)buffer)[i * 3 + 2]) << 24;
  369. sample |= int32_t(((int8_t *)buffer)[i * 3 + 1]) << 16;
  370. sample |= int32_t(((int8_t *)buffer)[i * 3 + 0]) << 8;
  371. break;
  372. case 32:
  373. sample = ((int32_t *)buffer)[i];
  374. break;
  375. }
  376. return sample;
  377. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  378. return int32_t(((float *)buffer)[i] * 32768.0) << 16;
  379. } else {
  380. ERR_PRINT("WASAPI: Unknown format tag");
  381. }
  382. return 0;
  383. }
  384. void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample) {
  385. if (format_tag == WAVE_FORMAT_PCM) {
  386. switch (bits_per_sample) {
  387. case 8:
  388. ((int8_t *)buffer)[i] = sample >> 24;
  389. break;
  390. case 16:
  391. ((int16_t *)buffer)[i] = sample >> 16;
  392. break;
  393. case 24:
  394. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  395. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  396. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  397. break;
  398. case 32:
  399. ((int32_t *)buffer)[i] = sample;
  400. break;
  401. }
  402. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  403. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  404. } else {
  405. ERR_PRINT("WASAPI: Unknown format tag");
  406. }
  407. }
  408. void AudioDriverWASAPI::thread_func(void *p_udata) {
  409. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  410. uint32_t avail_frames = 0;
  411. uint32_t write_ofs = 0;
  412. while (!ad->exit_thread) {
  413. uint32_t read_frames = 0;
  414. uint32_t written_frames = 0;
  415. if (avail_frames == 0) {
  416. ad->lock();
  417. ad->start_counting_ticks();
  418. if (ad->audio_output.active) {
  419. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  420. } else {
  421. for (unsigned int i = 0; i < ad->samples_in.size(); i++) {
  422. ad->samples_in.write[i] = 0;
  423. }
  424. }
  425. avail_frames = ad->buffer_frames;
  426. write_ofs = 0;
  427. ad->stop_counting_ticks();
  428. ad->unlock();
  429. }
  430. ad->lock();
  431. ad->start_counting_ticks();
  432. if (avail_frames > 0 && ad->audio_output.audio_client) {
  433. UINT32 cur_frames;
  434. bool invalidated = false;
  435. HRESULT hr = ad->audio_output.audio_client->GetCurrentPadding(&cur_frames);
  436. if (hr == S_OK) {
  437. // Check how much frames are available on the WASAPI buffer
  438. UINT32 write_frames = MIN(ad->buffer_frames - cur_frames, avail_frames);
  439. if (write_frames > 0) {
  440. BYTE *buffer = NULL;
  441. hr = ad->audio_output.render_client->GetBuffer(write_frames, &buffer);
  442. if (hr == S_OK) {
  443. // We're using WASAPI Shared Mode so we must convert the buffer
  444. if (ad->channels == ad->audio_output.channels) {
  445. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  446. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i, ad->samples_in.write[write_ofs++]);
  447. }
  448. } else {
  449. for (unsigned int i = 0; i < write_frames; i++) {
  450. for (unsigned int j = 0; j < MIN(ad->channels, ad->audio_output.channels); j++) {
  451. 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++]);
  452. }
  453. if (ad->audio_output.channels > ad->channels) {
  454. for (unsigned int j = ad->channels; j < ad->audio_output.channels; j++) {
  455. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, 0);
  456. }
  457. }
  458. }
  459. }
  460. hr = ad->audio_output.render_client->ReleaseBuffer(write_frames, 0);
  461. if (hr != S_OK) {
  462. ERR_PRINT("WASAPI: Release buffer error");
  463. }
  464. avail_frames -= write_frames;
  465. written_frames += write_frames;
  466. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  467. // Device is not valid anymore, reopen it
  468. Error err = ad->finish_render_device();
  469. if (err != OK) {
  470. ERR_PRINT("WASAPI: finish_render_device error");
  471. } else {
  472. // We reopened the device and samples_in may have resized, so invalidate the current avail_frames
  473. avail_frames = 0;
  474. }
  475. } else {
  476. ERR_PRINT("WASAPI: Get buffer error");
  477. ad->exit_thread = true;
  478. }
  479. }
  480. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  481. invalidated = true;
  482. } else {
  483. ERR_PRINT("WASAPI: GetCurrentPadding error");
  484. }
  485. if (invalidated) {
  486. // Device is not valid anymore
  487. WARN_PRINT("WASAPI: Current device invalidated, closing device");
  488. Error err = ad->finish_render_device();
  489. if (err != OK) {
  490. ERR_PRINT("WASAPI: finish_render_device error");
  491. }
  492. }
  493. }
  494. // If we're using the Default device and it changed finish it so we'll re-init the device
  495. if (ad->audio_output.device_name == "Default" && default_render_device_changed) {
  496. Error err = ad->finish_render_device();
  497. if (err != OK) {
  498. ERR_PRINT("WASAPI: finish_render_device error");
  499. }
  500. default_render_device_changed = false;
  501. }
  502. // User selected a new device, finish the current one so we'll init the new device
  503. if (ad->audio_output.device_name != ad->audio_output.new_device) {
  504. ad->audio_output.device_name = ad->audio_output.new_device;
  505. Error err = ad->finish_render_device();
  506. if (err != OK) {
  507. ERR_PRINT("WASAPI: finish_render_device error");
  508. }
  509. }
  510. if (!ad->audio_output.audio_client) {
  511. Error err = ad->init_render_device(true);
  512. if (err == OK) {
  513. ad->start();
  514. }
  515. avail_frames = 0;
  516. write_ofs = 0;
  517. }
  518. if (ad->audio_input.active) {
  519. UINT32 packet_length = 0;
  520. BYTE *data;
  521. UINT32 num_frames_available;
  522. DWORD flags;
  523. HRESULT hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  524. if (hr == S_OK) {
  525. while (packet_length != 0) {
  526. hr = ad->audio_input.capture_client->GetBuffer(&data, &num_frames_available, &flags, NULL, NULL);
  527. ERR_BREAK(hr != S_OK);
  528. // fixme: Only works for floating point atm
  529. for (int j = 0; j < num_frames_available; j++) {
  530. int32_t l, r;
  531. if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
  532. l = r = 0;
  533. } else {
  534. if (ad->audio_input.channels == 2) {
  535. l = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2);
  536. r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2 + 1);
  537. } else if (ad->audio_input.channels == 1) {
  538. l = r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j);
  539. } else {
  540. l = r = 0;
  541. ERR_PRINT("WASAPI: unsupported channel count in microphone!");
  542. }
  543. }
  544. ad->input_buffer_write(l);
  545. ad->input_buffer_write(r);
  546. }
  547. read_frames += num_frames_available;
  548. hr = ad->audio_input.capture_client->ReleaseBuffer(num_frames_available);
  549. ERR_BREAK(hr != S_OK);
  550. hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  551. ERR_BREAK(hr != S_OK);
  552. }
  553. }
  554. // If we're using the Default device and it changed finish it so we'll re-init the device
  555. if (ad->audio_input.device_name == "Default" && default_capture_device_changed) {
  556. Error err = ad->finish_capture_device();
  557. if (err != OK) {
  558. ERR_PRINT("WASAPI: finish_capture_device error");
  559. }
  560. default_capture_device_changed = false;
  561. }
  562. // User selected a new device, finish the current one so we'll init the new device
  563. if (ad->audio_input.device_name != ad->audio_input.new_device) {
  564. ad->audio_input.device_name = ad->audio_input.new_device;
  565. Error err = ad->finish_capture_device();
  566. if (err != OK) {
  567. ERR_PRINT("WASAPI: finish_capture_device error");
  568. }
  569. }
  570. if (!ad->audio_input.audio_client) {
  571. Error err = ad->init_capture_device(true);
  572. if (err == OK) {
  573. ad->capture_start();
  574. }
  575. }
  576. }
  577. ad->stop_counting_ticks();
  578. ad->unlock();
  579. // Let the thread rest a while if we haven't read or write anything
  580. if (written_frames == 0 && read_frames == 0) {
  581. OS::get_singleton()->delay_usec(1000);
  582. }
  583. }
  584. ad->thread_exited = true;
  585. }
  586. void AudioDriverWASAPI::start() {
  587. if (audio_output.audio_client) {
  588. HRESULT hr = audio_output.audio_client->Start();
  589. if (hr != S_OK) {
  590. ERR_PRINT("WASAPI: Start failed");
  591. } else {
  592. audio_output.active = true;
  593. }
  594. }
  595. }
  596. void AudioDriverWASAPI::lock() {
  597. if (mutex)
  598. mutex->lock();
  599. }
  600. void AudioDriverWASAPI::unlock() {
  601. if (mutex)
  602. mutex->unlock();
  603. }
  604. void AudioDriverWASAPI::finish() {
  605. if (thread) {
  606. exit_thread = true;
  607. Thread::wait_to_finish(thread);
  608. memdelete(thread);
  609. thread = NULL;
  610. }
  611. finish_capture_device();
  612. finish_render_device();
  613. if (mutex) {
  614. memdelete(mutex);
  615. mutex = NULL;
  616. }
  617. }
  618. Error AudioDriverWASAPI::capture_start() {
  619. Error err = init_capture_device();
  620. if (err != OK) {
  621. ERR_PRINT("WASAPI: init_capture_device error");
  622. return err;
  623. }
  624. if (audio_input.active) {
  625. return FAILED;
  626. }
  627. audio_input.audio_client->Start();
  628. audio_input.active = true;
  629. return OK;
  630. }
  631. Error AudioDriverWASAPI::capture_stop() {
  632. if (audio_input.active) {
  633. audio_input.audio_client->Stop();
  634. audio_input.active = false;
  635. return OK;
  636. }
  637. return FAILED;
  638. }
  639. void AudioDriverWASAPI::capture_set_device(const String &p_name) {
  640. lock();
  641. audio_input.new_device = p_name;
  642. unlock();
  643. }
  644. Array AudioDriverWASAPI::capture_get_device_list() {
  645. return audio_device_get_list(true);
  646. }
  647. String AudioDriverWASAPI::capture_get_device() {
  648. lock();
  649. String name = audio_input.device_name;
  650. unlock();
  651. return name;
  652. }
  653. AudioDriverWASAPI::AudioDriverWASAPI() {
  654. mutex = NULL;
  655. thread = NULL;
  656. samples_in.clear();
  657. channels = 0;
  658. mix_rate = 0;
  659. buffer_frames = 0;
  660. thread_exited = false;
  661. exit_thread = false;
  662. }
  663. #endif