audio_driver_wasapi.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 "os/os.h"
  33. #include "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 StringName capture_device_id;
  57. static bool default_render_device_changed = false;
  58. static bool default_capture_device_changed = false;
  59. class CMMNotificationClient : public IMMNotificationClient {
  60. LONG _cRef;
  61. IMMDeviceEnumerator *_pEnumerator;
  62. public:
  63. CMMNotificationClient() :
  64. _cRef(1),
  65. _pEnumerator(NULL) {}
  66. ~CMMNotificationClient() {
  67. if ((_pEnumerator) != NULL) {
  68. (_pEnumerator)->Release();
  69. (_pEnumerator) = NULL;
  70. }
  71. }
  72. ULONG STDMETHODCALLTYPE AddRef() {
  73. return InterlockedIncrement(&_cRef);
  74. }
  75. ULONG STDMETHODCALLTYPE Release() {
  76. ULONG ulRef = InterlockedDecrement(&_cRef);
  77. if (0 == ulRef) {
  78. delete this;
  79. }
  80. return ulRef;
  81. }
  82. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {
  83. if (IID_IUnknown == riid) {
  84. AddRef();
  85. *ppvInterface = (IUnknown *)this;
  86. } else if (__uuidof(IMMNotificationClient) == riid) {
  87. AddRef();
  88. *ppvInterface = (IMMNotificationClient *)this;
  89. } else {
  90. *ppvInterface = NULL;
  91. return E_NOINTERFACE;
  92. }
  93. return S_OK;
  94. }
  95. HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
  96. return S_OK;
  97. };
  98. HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
  99. return S_OK;
  100. }
  101. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
  102. return S_OK;
  103. }
  104. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
  105. if (role == eConsole) {
  106. if (flow == eRender) {
  107. default_render_device_changed = true;
  108. } else if (flow == eCapture) {
  109. default_capture_device_changed = true;
  110. capture_device_id = String(pwstrDeviceId);
  111. }
  112. }
  113. return S_OK;
  114. }
  115. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
  116. return S_OK;
  117. }
  118. };
  119. static CMMNotificationClient notif_client;
  120. Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_capture, bool reinit) {
  121. WAVEFORMATEX *pwfex;
  122. IMMDeviceEnumerator *enumerator = NULL;
  123. IMMDevice *device = NULL;
  124. CoInitialize(NULL);
  125. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  126. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  127. if (p_device->device_name == "Default") {
  128. hr = enumerator->GetDefaultAudioEndpoint(p_capture ? eCapture : eRender, eConsole, &device);
  129. } else {
  130. IMMDeviceCollection *devices = NULL;
  131. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  132. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  133. LPWSTR strId = NULL;
  134. bool found = false;
  135. UINT count = 0;
  136. hr = devices->GetCount(&count);
  137. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  138. for (ULONG i = 0; i < count && !found; i++) {
  139. IMMDevice *device = NULL;
  140. hr = devices->Item(i, &device);
  141. ERR_BREAK(hr != S_OK);
  142. IPropertyStore *props = NULL;
  143. hr = device->OpenPropertyStore(STGM_READ, &props);
  144. ERR_BREAK(hr != S_OK);
  145. PROPVARIANT propvar;
  146. PropVariantInit(&propvar);
  147. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  148. ERR_BREAK(hr != S_OK);
  149. if (p_device->device_name == String(propvar.pwszVal)) {
  150. hr = device->GetId(&strId);
  151. ERR_BREAK(hr != S_OK);
  152. found = true;
  153. }
  154. PropVariantClear(&propvar);
  155. props->Release();
  156. device->Release();
  157. }
  158. if (found) {
  159. hr = enumerator->GetDevice(strId, &device);
  160. }
  161. if (strId) {
  162. CoTaskMemFree(strId);
  163. }
  164. if (device == NULL) {
  165. hr = enumerator->GetDefaultAudioEndpoint(p_capture ? eCapture : eRender, eConsole, &device);
  166. }
  167. }
  168. if (reinit) {
  169. // In case we're trying to re-initialize the device prevent throwing this error on the console,
  170. // otherwise if there is currently no device available this will spam the console.
  171. if (hr != S_OK) {
  172. return ERR_CANT_OPEN;
  173. }
  174. } else {
  175. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  176. }
  177. hr = enumerator->RegisterEndpointNotificationCallback(&notif_client);
  178. SAFE_RELEASE(enumerator)
  179. if (hr != S_OK) {
  180. ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");
  181. }
  182. hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&p_device->audio_client);
  183. SAFE_RELEASE(device)
  184. if (reinit) {
  185. if (hr != S_OK) {
  186. return ERR_CANT_OPEN;
  187. }
  188. } else {
  189. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  190. }
  191. hr = p_device->audio_client->GetMixFormat(&pwfex);
  192. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  193. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  194. p_device->channels = pwfex->nChannels;
  195. p_device->format_tag = pwfex->wFormatTag;
  196. p_device->bits_per_sample = pwfex->wBitsPerSample;
  197. p_device->frame_size = (p_device->bits_per_sample / 8) * p_device->channels;
  198. if (p_device->format_tag == WAVE_FORMAT_EXTENSIBLE) {
  199. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  200. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  201. p_device->format_tag = WAVE_FORMAT_PCM;
  202. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  203. p_device->format_tag = WAVE_FORMAT_IEEE_FLOAT;
  204. } else {
  205. ERR_PRINT("WASAPI: Format not supported");
  206. ERR_FAIL_V(ERR_CANT_OPEN);
  207. }
  208. } else {
  209. if (p_device->format_tag != WAVE_FORMAT_PCM && p_device->format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  210. ERR_PRINT("WASAPI: Format not supported");
  211. ERR_FAIL_V(ERR_CANT_OPEN);
  212. }
  213. }
  214. DWORD streamflags = 0;
  215. if (mix_rate != pwfex->nSamplesPerSec) {
  216. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  217. pwfex->nSamplesPerSec = mix_rate;
  218. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  219. }
  220. hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_capture ? REFTIMES_PER_SEC : 0, 0, pwfex, NULL);
  221. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  222. if (p_capture) {
  223. hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);
  224. } else {
  225. hr = p_device->audio_client->GetService(IID_IAudioRenderClient, (void **)&p_device->render_client);
  226. }
  227. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  228. // Free memory
  229. CoTaskMemFree(pwfex);
  230. SAFE_RELEASE(device)
  231. return OK;
  232. }
  233. Error AudioDriverWASAPI::init_render_device(bool reinit) {
  234. Error err = audio_device_init(&audio_output, false, reinit);
  235. if (err != OK)
  236. return err;
  237. switch (audio_output.channels) {
  238. case 2: // Stereo
  239. case 4: // Surround 3.1
  240. case 6: // Surround 5.1
  241. case 8: // Surround 7.1
  242. channels = audio_output.channels;
  243. break;
  244. default:
  245. WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(audio_output.channels));
  246. channels = 2;
  247. break;
  248. }
  249. UINT32 max_frames;
  250. HRESULT hr = audio_output.audio_client->GetBufferSize(&max_frames);
  251. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  252. // Due to WASAPI Shared Mode we have no control of the buffer size
  253. buffer_frames = max_frames;
  254. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  255. samples_in.resize(buffer_frames * channels);
  256. input_position = 0;
  257. input_size = 0;
  258. if (OS::get_singleton()->is_stdout_verbose()) {
  259. print_line("WASAPI: detected " + itos(channels) + " channels");
  260. print_line("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  261. }
  262. return OK;
  263. }
  264. Error AudioDriverWASAPI::init_capture_device(bool reinit) {
  265. Error err = audio_device_init(&audio_input, true, reinit);
  266. if (err != OK)
  267. return err;
  268. // Get the max frames
  269. UINT32 max_frames;
  270. HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames);
  271. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  272. // Set the buffer size
  273. input_buffer.resize(max_frames * CAPTURE_BUFFER_CHANNELS);
  274. input_position = 0;
  275. input_size = 0;
  276. return OK;
  277. }
  278. Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {
  279. if (p_device->active) {
  280. if (p_device->audio_client) {
  281. p_device->audio_client->Stop();
  282. }
  283. p_device->active = false;
  284. }
  285. SAFE_RELEASE(p_device->audio_client)
  286. SAFE_RELEASE(p_device->render_client)
  287. SAFE_RELEASE(p_device->capture_client)
  288. return OK;
  289. }
  290. Error AudioDriverWASAPI::finish_render_device() {
  291. return audio_device_finish(&audio_output);
  292. }
  293. Error AudioDriverWASAPI::finish_capture_device() {
  294. return audio_device_finish(&audio_input);
  295. }
  296. Error AudioDriverWASAPI::init() {
  297. mix_rate = GLOBAL_DEF_RST("audio/mix_rate", DEFAULT_MIX_RATE);
  298. Error err = init_render_device();
  299. if (err != OK) {
  300. ERR_PRINT("WASAPI: init_render_device error");
  301. }
  302. exit_thread = false;
  303. thread_exited = false;
  304. mutex = Mutex::create(true);
  305. thread = Thread::create(thread_func, this);
  306. return OK;
  307. }
  308. int AudioDriverWASAPI::get_mix_rate() const {
  309. return mix_rate;
  310. }
  311. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  312. return get_speaker_mode_by_total_channels(channels);
  313. }
  314. Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
  315. Array list;
  316. IMMDeviceCollection *devices = NULL;
  317. IMMDeviceEnumerator *enumerator = NULL;
  318. list.push_back(String("Default"));
  319. CoInitialize(NULL);
  320. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  321. ERR_FAIL_COND_V(hr != S_OK, Array());
  322. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  323. ERR_FAIL_COND_V(hr != S_OK, Array());
  324. UINT count = 0;
  325. hr = devices->GetCount(&count);
  326. ERR_FAIL_COND_V(hr != S_OK, Array());
  327. for (ULONG i = 0; i < count; i++) {
  328. IMMDevice *device = NULL;
  329. hr = devices->Item(i, &device);
  330. ERR_BREAK(hr != S_OK);
  331. IPropertyStore *props = NULL;
  332. hr = device->OpenPropertyStore(STGM_READ, &props);
  333. ERR_BREAK(hr != S_OK);
  334. PROPVARIANT propvar;
  335. PropVariantInit(&propvar);
  336. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  337. ERR_BREAK(hr != S_OK);
  338. list.push_back(String(propvar.pwszVal));
  339. PropVariantClear(&propvar);
  340. props->Release();
  341. device->Release();
  342. }
  343. devices->Release();
  344. enumerator->Release();
  345. return list;
  346. }
  347. Array AudioDriverWASAPI::get_device_list() {
  348. return audio_device_get_list(false);
  349. }
  350. String AudioDriverWASAPI::get_device() {
  351. lock();
  352. String name = audio_output.device_name;
  353. unlock();
  354. return name;
  355. }
  356. void AudioDriverWASAPI::set_device(String device) {
  357. lock();
  358. audio_output.new_device = device;
  359. unlock();
  360. }
  361. int32_t AudioDriverWASAPI::read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i) {
  362. if (format_tag == WAVE_FORMAT_PCM) {
  363. int32_t sample = 0;
  364. switch (bits_per_sample) {
  365. case 8:
  366. sample = int32_t(((int8_t *)buffer)[i]) << 24;
  367. break;
  368. case 16:
  369. sample = int32_t(((int16_t *)buffer)[i]) << 16;
  370. break;
  371. case 24:
  372. sample |= int32_t(((int8_t *)buffer)[i * 3 + 2]) << 24;
  373. sample |= int32_t(((int8_t *)buffer)[i * 3 + 1]) << 16;
  374. sample |= int32_t(((int8_t *)buffer)[i * 3 + 0]) << 8;
  375. break;
  376. case 32:
  377. sample = ((int32_t *)buffer)[i];
  378. break;
  379. }
  380. return sample;
  381. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  382. return int32_t(((float *)buffer)[i] * 32768.0) << 16;
  383. } else {
  384. ERR_PRINT("WASAPI: Unknown format tag");
  385. }
  386. return 0;
  387. }
  388. void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample) {
  389. if (format_tag == WAVE_FORMAT_PCM) {
  390. switch (bits_per_sample) {
  391. case 8:
  392. ((int8_t *)buffer)[i] = sample >> 24;
  393. break;
  394. case 16:
  395. ((int16_t *)buffer)[i] = sample >> 16;
  396. break;
  397. case 24:
  398. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  399. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  400. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  401. break;
  402. case 32:
  403. ((int32_t *)buffer)[i] = sample;
  404. break;
  405. }
  406. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  407. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  408. } else {
  409. ERR_PRINT("WASAPI: Unknown format tag");
  410. }
  411. }
  412. void AudioDriverWASAPI::thread_func(void *p_udata) {
  413. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  414. uint32_t avail_frames = 0;
  415. uint32_t write_ofs = 0;
  416. while (!ad->exit_thread) {
  417. uint32_t read_frames = 0;
  418. uint32_t written_frames = 0;
  419. if (avail_frames == 0) {
  420. ad->lock();
  421. ad->start_counting_ticks();
  422. if (ad->audio_output.active) {
  423. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  424. } else {
  425. for (unsigned int i = 0; i < ad->samples_in.size(); i++) {
  426. ad->samples_in.write[i] = 0;
  427. }
  428. }
  429. avail_frames = ad->buffer_frames;
  430. write_ofs = 0;
  431. ad->stop_counting_ticks();
  432. ad->unlock();
  433. }
  434. ad->lock();
  435. ad->start_counting_ticks();
  436. if (avail_frames > 0 && ad->audio_output.audio_client) {
  437. UINT32 cur_frames;
  438. bool invalidated = false;
  439. HRESULT hr = ad->audio_output.audio_client->GetCurrentPadding(&cur_frames);
  440. if (hr == S_OK) {
  441. // Check how much frames are available on the WASAPI buffer
  442. UINT32 write_frames = MIN(ad->buffer_frames - cur_frames, avail_frames);
  443. if (write_frames > 0) {
  444. BYTE *buffer = NULL;
  445. hr = ad->audio_output.render_client->GetBuffer(write_frames, &buffer);
  446. if (hr == S_OK) {
  447. // We're using WASAPI Shared Mode so we must convert the buffer
  448. if (ad->channels == ad->audio_output.channels) {
  449. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  450. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i, ad->samples_in.write[write_ofs++]);
  451. }
  452. } else {
  453. for (unsigned int i = 0; i < write_frames; i++) {
  454. for (unsigned int j = 0; j < MIN(ad->channels, 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, ad->samples_in.write[write_ofs++]);
  456. }
  457. if (ad->audio_output.channels > ad->channels) {
  458. for (unsigned int j = ad->channels; j < ad->audio_output.channels; j++) {
  459. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, 0);
  460. }
  461. }
  462. }
  463. }
  464. hr = ad->audio_output.render_client->ReleaseBuffer(write_frames, 0);
  465. if (hr != S_OK) {
  466. ERR_PRINT("WASAPI: Release buffer error");
  467. }
  468. avail_frames -= write_frames;
  469. written_frames += write_frames;
  470. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  471. // Device is not valid anymore, reopen it
  472. Error err = ad->finish_render_device();
  473. if (err != OK) {
  474. ERR_PRINT("WASAPI: finish_render_device error");
  475. } else {
  476. // We reopened the device and samples_in may have resized, so invalidate the current avail_frames
  477. avail_frames = 0;
  478. }
  479. } else {
  480. ERR_PRINT("WASAPI: Get buffer error");
  481. ad->exit_thread = true;
  482. }
  483. }
  484. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  485. invalidated = true;
  486. } else {
  487. ERR_PRINT("WASAPI: GetCurrentPadding error");
  488. }
  489. if (invalidated) {
  490. // Device is not valid anymore
  491. WARN_PRINT("WASAPI: Current device invalidated, closing device");
  492. Error err = ad->finish_render_device();
  493. if (err != OK) {
  494. ERR_PRINT("WASAPI: finish_render_device error");
  495. }
  496. }
  497. }
  498. // If we're using the Default device and it changed finish it so we'll re-init the device
  499. if (ad->audio_output.device_name == "Default" && default_render_device_changed) {
  500. Error err = ad->finish_render_device();
  501. if (err != OK) {
  502. ERR_PRINT("WASAPI: finish_render_device error");
  503. }
  504. default_render_device_changed = false;
  505. }
  506. // User selected a new device, finish the current one so we'll init the new device
  507. if (ad->audio_output.device_name != ad->audio_output.new_device) {
  508. ad->audio_output.device_name = ad->audio_output.new_device;
  509. Error err = ad->finish_render_device();
  510. if (err != OK) {
  511. ERR_PRINT("WASAPI: finish_render_device error");
  512. }
  513. }
  514. if (!ad->audio_output.audio_client) {
  515. Error err = ad->init_render_device(true);
  516. if (err == OK) {
  517. ad->start();
  518. }
  519. }
  520. if (ad->audio_input.active) {
  521. UINT32 packet_length = 0;
  522. BYTE *data;
  523. UINT32 num_frames_available;
  524. DWORD flags;
  525. HRESULT hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  526. if (hr == S_OK) {
  527. while (packet_length != 0) {
  528. hr = ad->audio_input.capture_client->GetBuffer(&data, &num_frames_available, &flags, NULL, NULL);
  529. ERR_BREAK(hr != S_OK);
  530. // fixme: Only works for floating point atm
  531. for (int j = 0; j < num_frames_available; j++) {
  532. int32_t l, r;
  533. if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
  534. l = r = 0;
  535. } else {
  536. if (ad->audio_input.channels == 2) {
  537. l = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2);
  538. r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2 + 1);
  539. } else if (ad->audio_input.channels == 1) {
  540. l = r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j);
  541. } else {
  542. l = r = 0;
  543. ERR_PRINT("WASAPI: unsupported channel count in microphone!");
  544. }
  545. }
  546. ad->input_buffer_write(l);
  547. ad->input_buffer_write(r);
  548. }
  549. read_frames += num_frames_available;
  550. hr = ad->audio_input.capture_client->ReleaseBuffer(num_frames_available);
  551. ERR_BREAK(hr != S_OK);
  552. hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  553. ERR_BREAK(hr != S_OK);
  554. }
  555. }
  556. // If we're using the Default device and it changed finish it so we'll re-init the device
  557. if (ad->audio_input.device_name == "Default" && default_capture_device_changed) {
  558. Error err = ad->finish_capture_device();
  559. if (err != OK) {
  560. ERR_PRINT("WASAPI: finish_capture_device error");
  561. }
  562. default_capture_device_changed = false;
  563. }
  564. // User selected a new device, finish the current one so we'll init the new device
  565. if (ad->audio_input.device_name != ad->audio_input.new_device) {
  566. ad->audio_input.device_name = ad->audio_input.new_device;
  567. Error err = ad->finish_capture_device();
  568. if (err != OK) {
  569. ERR_PRINT("WASAPI: finish_capture_device error");
  570. }
  571. }
  572. if (!ad->audio_input.audio_client) {
  573. Error err = ad->init_capture_device(true);
  574. if (err == OK) {
  575. ad->capture_start();
  576. }
  577. }
  578. }
  579. ad->stop_counting_ticks();
  580. ad->unlock();
  581. // Let the thread rest a while if we haven't read or write anything
  582. if (written_frames == 0 && read_frames == 0) {
  583. OS::get_singleton()->delay_usec(1000);
  584. }
  585. }
  586. ad->thread_exited = true;
  587. }
  588. void AudioDriverWASAPI::start() {
  589. if (audio_output.audio_client) {
  590. HRESULT hr = audio_output.audio_client->Start();
  591. if (hr != S_OK) {
  592. ERR_PRINT("WASAPI: Start failed");
  593. } else {
  594. audio_output.active = true;
  595. }
  596. }
  597. }
  598. void AudioDriverWASAPI::lock() {
  599. if (mutex)
  600. mutex->lock();
  601. }
  602. void AudioDriverWASAPI::unlock() {
  603. if (mutex)
  604. mutex->unlock();
  605. }
  606. void AudioDriverWASAPI::finish() {
  607. if (thread) {
  608. exit_thread = true;
  609. Thread::wait_to_finish(thread);
  610. memdelete(thread);
  611. thread = NULL;
  612. }
  613. finish_capture_device();
  614. finish_render_device();
  615. if (mutex) {
  616. memdelete(mutex);
  617. mutex = NULL;
  618. }
  619. }
  620. Error AudioDriverWASAPI::capture_start() {
  621. Error err = init_capture_device();
  622. if (err != OK) {
  623. ERR_PRINT("WASAPI: init_capture_device error");
  624. return err;
  625. }
  626. if (audio_input.active == false) {
  627. audio_input.audio_client->Start();
  628. audio_input.active = true;
  629. return OK;
  630. }
  631. return FAILED;
  632. }
  633. Error AudioDriverWASAPI::capture_stop() {
  634. if (audio_input.active == true) {
  635. audio_input.audio_client->Stop();
  636. audio_input.active = false;
  637. return OK;
  638. }
  639. return FAILED;
  640. }
  641. void AudioDriverWASAPI::capture_set_device(const String &p_name) {
  642. lock();
  643. audio_input.new_device = p_name;
  644. unlock();
  645. }
  646. Array AudioDriverWASAPI::capture_get_device_list() {
  647. return audio_device_get_list(true);
  648. }
  649. String AudioDriverWASAPI::capture_get_device() {
  650. lock();
  651. String name = audio_input.device_name;
  652. unlock();
  653. return name;
  654. }
  655. AudioDriverWASAPI::AudioDriverWASAPI() {
  656. mutex = NULL;
  657. thread = NULL;
  658. samples_in.clear();
  659. channels = 0;
  660. mix_rate = 0;
  661. buffer_frames = 0;
  662. thread_exited = false;
  663. exit_thread = false;
  664. }
  665. #endif