audio_driver_wasapi.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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/config/project_settings.h"
  33. #include "core/os/os.h"
  34. #include <stdint.h> // INT32_MAX
  35. #include <functiondiscoverykeys.h>
  36. // Define IAudioClient3 if not already defined by MinGW headers
  37. #if defined __MINGW32__ || defined __MINGW64__
  38. #ifndef __IAudioClient3_FWD_DEFINED__
  39. #define __IAudioClient3_FWD_DEFINED__
  40. typedef interface IAudioClient3 IAudioClient3;
  41. #endif // __IAudioClient3_FWD_DEFINED__
  42. #ifndef __IAudioClient3_INTERFACE_DEFINED__
  43. #define __IAudioClient3_INTERFACE_DEFINED__
  44. MIDL_INTERFACE("7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42")
  45. IAudioClient3 : public IAudioClient2 {
  46. public:
  47. virtual HRESULT STDMETHODCALLTYPE GetSharedModeEnginePeriod(
  48. /* [annotation][in] */
  49. _In_ const WAVEFORMATEX *pFormat,
  50. /* [annotation][out] */
  51. _Out_ UINT32 *pDefaultPeriodInFrames,
  52. /* [annotation][out] */
  53. _Out_ UINT32 *pFundamentalPeriodInFrames,
  54. /* [annotation][out] */
  55. _Out_ UINT32 *pMinPeriodInFrames,
  56. /* [annotation][out] */
  57. _Out_ UINT32 *pMaxPeriodInFrames) = 0;
  58. virtual HRESULT STDMETHODCALLTYPE GetCurrentSharedModeEnginePeriod(
  59. /* [unique][annotation][out] */
  60. _Out_ WAVEFORMATEX * *ppFormat,
  61. /* [annotation][out] */
  62. _Out_ UINT32 * pCurrentPeriodInFrames) = 0;
  63. virtual HRESULT STDMETHODCALLTYPE InitializeSharedAudioStream(
  64. /* [annotation][in] */
  65. _In_ DWORD StreamFlags,
  66. /* [annotation][in] */
  67. _In_ UINT32 PeriodInFrames,
  68. /* [annotation][in] */
  69. _In_ const WAVEFORMATEX *pFormat,
  70. /* [annotation][in] */
  71. _In_opt_ LPCGUID AudioSessionGuid) = 0;
  72. };
  73. __CRT_UUID_DECL(IAudioClient3, 0x7ED4EE07, 0x8E67, 0x4CD4, 0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42)
  74. #endif // __IAudioClient3_INTERFACE_DEFINED__
  75. #endif // __MINGW32__ || __MINGW64__
  76. #ifndef PKEY_Device_FriendlyName
  77. #undef DEFINE_PROPERTYKEY
  78. /* clang-format off */
  79. #define DEFINE_PROPERTYKEY(id, a, b, c, d, e, f, g, h, i, j, k, l) \
  80. const PROPERTYKEY id = { { a, b, c, { d, e, f, g, h, i, j, k, } }, l };
  81. /* clang-format on */
  82. DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);
  83. #endif
  84. const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
  85. const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
  86. const IID IID_IAudioClient = __uuidof(IAudioClient);
  87. const IID IID_IAudioClient3 = __uuidof(IAudioClient3);
  88. const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
  89. const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);
  90. #define SAFE_RELEASE(memory) \
  91. if ((memory) != nullptr) { \
  92. (memory)->Release(); \
  93. (memory) = nullptr; \
  94. }
  95. #define REFTIMES_PER_SEC 10000000
  96. #define REFTIMES_PER_MILLISEC 10000
  97. #define CAPTURE_BUFFER_CHANNELS 2
  98. static bool default_render_device_changed = false;
  99. static bool default_capture_device_changed = false;
  100. class CMMNotificationClient : public IMMNotificationClient {
  101. LONG _cRef = 1;
  102. IMMDeviceEnumerator *_pEnumerator = nullptr;
  103. public:
  104. CMMNotificationClient() {}
  105. virtual ~CMMNotificationClient() {
  106. if ((_pEnumerator) != nullptr) {
  107. (_pEnumerator)->Release();
  108. (_pEnumerator) = nullptr;
  109. }
  110. }
  111. ULONG STDMETHODCALLTYPE AddRef() {
  112. return InterlockedIncrement(&_cRef);
  113. }
  114. ULONG STDMETHODCALLTYPE Release() {
  115. ULONG ulRef = InterlockedDecrement(&_cRef);
  116. if (0 == ulRef) {
  117. delete this;
  118. }
  119. return ulRef;
  120. }
  121. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {
  122. if (IID_IUnknown == riid) {
  123. AddRef();
  124. *ppvInterface = (IUnknown *)this;
  125. } else if (__uuidof(IMMNotificationClient) == riid) {
  126. AddRef();
  127. *ppvInterface = (IMMNotificationClient *)this;
  128. } else {
  129. *ppvInterface = nullptr;
  130. return E_NOINTERFACE;
  131. }
  132. return S_OK;
  133. }
  134. HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
  135. return S_OK;
  136. };
  137. HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
  138. return S_OK;
  139. }
  140. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
  141. return S_OK;
  142. }
  143. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
  144. if (role == eConsole) {
  145. if (flow == eRender) {
  146. default_render_device_changed = true;
  147. } else if (flow == eCapture) {
  148. default_capture_device_changed = true;
  149. }
  150. }
  151. return S_OK;
  152. }
  153. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
  154. return S_OK;
  155. }
  156. };
  157. static CMMNotificationClient notif_client;
  158. Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_capture, bool reinit) {
  159. WAVEFORMATEX *pwfex;
  160. IMMDeviceEnumerator *enumerator = nullptr;
  161. IMMDevice *device = nullptr;
  162. CoInitialize(nullptr);
  163. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  164. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  165. if (p_device->device_name == "Default") {
  166. hr = enumerator->GetDefaultAudioEndpoint(p_capture ? eCapture : eRender, eConsole, &device);
  167. } else {
  168. IMMDeviceCollection *devices = nullptr;
  169. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  170. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  171. LPWSTR strId = nullptr;
  172. bool found = false;
  173. UINT count = 0;
  174. hr = devices->GetCount(&count);
  175. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  176. for (ULONG i = 0; i < count && !found; i++) {
  177. IMMDevice *tmp_device = nullptr;
  178. hr = devices->Item(i, &tmp_device);
  179. ERR_BREAK(hr != S_OK);
  180. IPropertyStore *props = nullptr;
  181. hr = tmp_device->OpenPropertyStore(STGM_READ, &props);
  182. ERR_BREAK(hr != S_OK);
  183. PROPVARIANT propvar;
  184. PropVariantInit(&propvar);
  185. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  186. ERR_BREAK(hr != S_OK);
  187. if (p_device->device_name == String(propvar.pwszVal)) {
  188. hr = tmp_device->GetId(&strId);
  189. ERR_BREAK(hr != S_OK);
  190. found = true;
  191. }
  192. PropVariantClear(&propvar);
  193. props->Release();
  194. tmp_device->Release();
  195. }
  196. if (found) {
  197. hr = enumerator->GetDevice(strId, &device);
  198. }
  199. if (strId) {
  200. CoTaskMemFree(strId);
  201. }
  202. if (device == nullptr) {
  203. hr = enumerator->GetDefaultAudioEndpoint(p_capture ? eCapture : eRender, eConsole, &device);
  204. }
  205. }
  206. if (reinit) {
  207. // In case we're trying to re-initialize the device prevent throwing this error on the console,
  208. // otherwise if there is currently no device available this will spam the console.
  209. if (hr != S_OK) {
  210. return ERR_CANT_OPEN;
  211. }
  212. } else {
  213. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  214. }
  215. hr = enumerator->RegisterEndpointNotificationCallback(&notif_client);
  216. SAFE_RELEASE(enumerator)
  217. if (hr != S_OK) {
  218. ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");
  219. }
  220. bool using_audio_client_3 = !p_capture; // IID_IAudioClient3 is only used for adjustable output latency (not input)
  221. if (using_audio_client_3) {
  222. hr = device->Activate(IID_IAudioClient3, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);
  223. if (hr != S_OK) {
  224. // IID_IAudioClient3 will never activate on OS versions before Windows 10.
  225. // Older Windows versions should fall back gracefully.
  226. using_audio_client_3 = false;
  227. print_verbose("WASAPI: Couldn't activate device with IAudioClient3 interface, falling back to IAudioClient interface");
  228. } else {
  229. print_verbose("WASAPI: Activated device using IAudioClient3 interface");
  230. }
  231. }
  232. if (!using_audio_client_3) {
  233. hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);
  234. }
  235. SAFE_RELEASE(device)
  236. if (reinit) {
  237. if (hr != S_OK) {
  238. return ERR_CANT_OPEN;
  239. }
  240. } else {
  241. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  242. }
  243. if (using_audio_client_3) {
  244. AudioClientProperties audioProps;
  245. audioProps.cbSize = sizeof(AudioClientProperties);
  246. audioProps.bIsOffload = FALSE;
  247. audioProps.eCategory = AudioCategory_GameEffects;
  248. hr = ((IAudioClient3 *)p_device->audio_client)->SetClientProperties(&audioProps);
  249. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: SetClientProperties failed with error 0x" + String::num_uint64(hr, 16) + ".");
  250. }
  251. hr = p_device->audio_client->GetMixFormat(&pwfex);
  252. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  253. print_verbose("WASAPI: wFormatTag = " + itos(pwfex->wFormatTag));
  254. print_verbose("WASAPI: nChannels = " + itos(pwfex->nChannels));
  255. print_verbose("WASAPI: nSamplesPerSec = " + itos(pwfex->nSamplesPerSec));
  256. print_verbose("WASAPI: nAvgBytesPerSec = " + itos(pwfex->nAvgBytesPerSec));
  257. print_verbose("WASAPI: nBlockAlign = " + itos(pwfex->nBlockAlign));
  258. print_verbose("WASAPI: wBitsPerSample = " + itos(pwfex->wBitsPerSample));
  259. print_verbose("WASAPI: cbSize = " + itos(pwfex->cbSize));
  260. WAVEFORMATEX *closest = nullptr;
  261. hr = p_device->audio_client->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, pwfex, &closest);
  262. if (hr == S_FALSE) {
  263. WARN_PRINT("WASAPI: Mix format is not supported by the Device");
  264. if (closest) {
  265. print_verbose("WASAPI: closest->wFormatTag = " + itos(closest->wFormatTag));
  266. print_verbose("WASAPI: closest->nChannels = " + itos(closest->nChannels));
  267. print_verbose("WASAPI: closest->nSamplesPerSec = " + itos(closest->nSamplesPerSec));
  268. print_verbose("WASAPI: closest->nAvgBytesPerSec = " + itos(closest->nAvgBytesPerSec));
  269. print_verbose("WASAPI: closest->nBlockAlign = " + itos(closest->nBlockAlign));
  270. print_verbose("WASAPI: closest->wBitsPerSample = " + itos(closest->wBitsPerSample));
  271. print_verbose("WASAPI: closest->cbSize = " + itos(closest->cbSize));
  272. WARN_PRINT("WASAPI: Using closest match instead");
  273. pwfex = closest;
  274. }
  275. }
  276. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  277. p_device->channels = pwfex->nChannels;
  278. p_device->format_tag = pwfex->wFormatTag;
  279. p_device->bits_per_sample = pwfex->wBitsPerSample;
  280. p_device->frame_size = (p_device->bits_per_sample / 8) * p_device->channels;
  281. if (p_device->format_tag == WAVE_FORMAT_EXTENSIBLE) {
  282. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  283. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  284. p_device->format_tag = WAVE_FORMAT_PCM;
  285. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  286. p_device->format_tag = WAVE_FORMAT_IEEE_FLOAT;
  287. } else {
  288. ERR_PRINT("WASAPI: Format not supported");
  289. ERR_FAIL_V(ERR_CANT_OPEN);
  290. }
  291. } else {
  292. if (p_device->format_tag != WAVE_FORMAT_PCM && p_device->format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  293. ERR_PRINT("WASAPI: Format not supported");
  294. ERR_FAIL_V(ERR_CANT_OPEN);
  295. }
  296. }
  297. if (!using_audio_client_3) {
  298. DWORD streamflags = 0;
  299. if ((DWORD)mix_rate != pwfex->nSamplesPerSec) {
  300. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  301. pwfex->nSamplesPerSec = mix_rate;
  302. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  303. }
  304. hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_capture ? REFTIMES_PER_SEC : 0, 0, pwfex, nullptr);
  305. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16) + ".");
  306. UINT32 max_frames;
  307. HRESULT hr = p_device->audio_client->GetBufferSize(&max_frames);
  308. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  309. // Due to WASAPI Shared Mode we have no control of the buffer size
  310. buffer_frames = max_frames;
  311. } else {
  312. IAudioClient3 *device_audio_client_3 = (IAudioClient3 *)p_device->audio_client;
  313. // AUDCLNT_STREAMFLAGS_RATEADJUST is an invalid flag with IAudioClient3, therefore we have to use
  314. // the closest supported mix rate supported by the audio driver.
  315. mix_rate = pwfex->nSamplesPerSec;
  316. print_verbose("WASAPI: mix_rate = " + itos(mix_rate));
  317. UINT32 default_period_frames, fundamental_period_frames, min_period_frames, max_period_frames;
  318. hr = device_audio_client_3->GetSharedModeEnginePeriod(
  319. pwfex,
  320. &default_period_frames,
  321. &fundamental_period_frames,
  322. &min_period_frames,
  323. &max_period_frames);
  324. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: GetSharedModeEnginePeriod failed with error 0x" + String::num_uint64(hr, 16) + ".");
  325. // Period frames must be an integral multiple of fundamental_period_frames or IAudioClient3 initialization will fail,
  326. // so we need to select the closest multiple to the user-specified latency.
  327. UINT32 desired_period_frames = target_latency_ms * mix_rate / 1000;
  328. UINT32 period_frames = (desired_period_frames / fundamental_period_frames) * fundamental_period_frames;
  329. if (ABS((int64_t)period_frames - (int64_t)desired_period_frames) > ABS((int64_t)(period_frames + fundamental_period_frames) - (int64_t)desired_period_frames)) {
  330. period_frames = period_frames + fundamental_period_frames;
  331. }
  332. period_frames = CLAMP(period_frames, min_period_frames, max_period_frames);
  333. print_verbose("WASAPI: fundamental_period_frames = " + itos(fundamental_period_frames));
  334. print_verbose("WASAPI: min_period_frames = " + itos(min_period_frames));
  335. print_verbose("WASAPI: max_period_frames = " + itos(max_period_frames));
  336. print_verbose("WASAPI: selected a period frame size of " + itos(period_frames));
  337. buffer_frames = period_frames;
  338. hr = device_audio_client_3->InitializeSharedAudioStream(0, period_frames, pwfex, nullptr);
  339. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: InitializeSharedAudioStream failed with error 0x" + String::num_uint64(hr, 16) + ".");
  340. }
  341. if (p_capture) {
  342. hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);
  343. } else {
  344. hr = p_device->audio_client->GetService(IID_IAudioRenderClient, (void **)&p_device->render_client);
  345. }
  346. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  347. // Free memory
  348. CoTaskMemFree(pwfex);
  349. SAFE_RELEASE(device)
  350. return OK;
  351. }
  352. Error AudioDriverWASAPI::init_render_device(bool reinit) {
  353. Error err = audio_device_init(&audio_output, false, reinit);
  354. if (err != OK)
  355. return err;
  356. switch (audio_output.channels) {
  357. case 2: // Stereo
  358. case 4: // Surround 3.1
  359. case 6: // Surround 5.1
  360. case 8: // Surround 7.1
  361. channels = audio_output.channels;
  362. break;
  363. default:
  364. WARN_PRINT("WASAPI: Unsupported number of channels: " + itos(audio_output.channels));
  365. channels = 2;
  366. break;
  367. }
  368. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  369. samples_in.resize(buffer_frames * channels);
  370. input_position = 0;
  371. input_size = 0;
  372. print_verbose("WASAPI: detected " + itos(channels) + " channels");
  373. print_verbose("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  374. return OK;
  375. }
  376. Error AudioDriverWASAPI::init_capture_device(bool reinit) {
  377. Error err = audio_device_init(&audio_input, true, reinit);
  378. if (err != OK)
  379. return err;
  380. // Get the max frames
  381. UINT32 max_frames;
  382. HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames);
  383. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  384. input_buffer_init(max_frames);
  385. return OK;
  386. }
  387. Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {
  388. if (p_device->active) {
  389. if (p_device->audio_client) {
  390. p_device->audio_client->Stop();
  391. }
  392. p_device->active = false;
  393. }
  394. SAFE_RELEASE(p_device->audio_client)
  395. SAFE_RELEASE(p_device->render_client)
  396. SAFE_RELEASE(p_device->capture_client)
  397. return OK;
  398. }
  399. Error AudioDriverWASAPI::finish_render_device() {
  400. return audio_device_finish(&audio_output);
  401. }
  402. Error AudioDriverWASAPI::finish_capture_device() {
  403. return audio_device_finish(&audio_input);
  404. }
  405. Error AudioDriverWASAPI::init() {
  406. mix_rate = GLOBAL_GET("audio/driver/mix_rate");
  407. target_latency_ms = GLOBAL_GET("audio/output_latency");
  408. Error err = init_render_device();
  409. if (err != OK) {
  410. ERR_PRINT("WASAPI: init_render_device error");
  411. }
  412. exit_thread = false;
  413. thread_exited = false;
  414. thread.start(thread_func, this);
  415. return OK;
  416. }
  417. int AudioDriverWASAPI::get_mix_rate() const {
  418. return mix_rate;
  419. }
  420. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  421. return get_speaker_mode_by_total_channels(channels);
  422. }
  423. Array AudioDriverWASAPI::audio_device_get_list(bool p_capture) {
  424. Array list;
  425. IMMDeviceCollection *devices = nullptr;
  426. IMMDeviceEnumerator *enumerator = nullptr;
  427. list.push_back(String("Default"));
  428. CoInitialize(nullptr);
  429. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  430. ERR_FAIL_COND_V(hr != S_OK, Array());
  431. hr = enumerator->EnumAudioEndpoints(p_capture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  432. ERR_FAIL_COND_V(hr != S_OK, Array());
  433. UINT count = 0;
  434. hr = devices->GetCount(&count);
  435. ERR_FAIL_COND_V(hr != S_OK, Array());
  436. for (ULONG i = 0; i < count; i++) {
  437. IMMDevice *device = nullptr;
  438. hr = devices->Item(i, &device);
  439. ERR_BREAK(hr != S_OK);
  440. IPropertyStore *props = nullptr;
  441. hr = device->OpenPropertyStore(STGM_READ, &props);
  442. ERR_BREAK(hr != S_OK);
  443. PROPVARIANT propvar;
  444. PropVariantInit(&propvar);
  445. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  446. ERR_BREAK(hr != S_OK);
  447. list.push_back(String(propvar.pwszVal));
  448. PropVariantClear(&propvar);
  449. props->Release();
  450. device->Release();
  451. }
  452. devices->Release();
  453. enumerator->Release();
  454. return list;
  455. }
  456. Array AudioDriverWASAPI::get_device_list() {
  457. return audio_device_get_list(false);
  458. }
  459. String AudioDriverWASAPI::get_device() {
  460. lock();
  461. String name = audio_output.device_name;
  462. unlock();
  463. return name;
  464. }
  465. void AudioDriverWASAPI::set_device(String device) {
  466. lock();
  467. audio_output.new_device = device;
  468. unlock();
  469. }
  470. int32_t AudioDriverWASAPI::read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i) {
  471. if (format_tag == WAVE_FORMAT_PCM) {
  472. int32_t sample = 0;
  473. switch (bits_per_sample) {
  474. case 8:
  475. sample = int32_t(((int8_t *)buffer)[i]) << 24;
  476. break;
  477. case 16:
  478. sample = int32_t(((int16_t *)buffer)[i]) << 16;
  479. break;
  480. case 24:
  481. sample |= int32_t(((int8_t *)buffer)[i * 3 + 2]) << 24;
  482. sample |= int32_t(((int8_t *)buffer)[i * 3 + 1]) << 16;
  483. sample |= int32_t(((int8_t *)buffer)[i * 3 + 0]) << 8;
  484. break;
  485. case 32:
  486. sample = ((int32_t *)buffer)[i];
  487. break;
  488. }
  489. return sample;
  490. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  491. return int32_t(((float *)buffer)[i] * 32768.0) << 16;
  492. } else {
  493. ERR_PRINT("WASAPI: Unknown format tag");
  494. }
  495. return 0;
  496. }
  497. void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample) {
  498. if (format_tag == WAVE_FORMAT_PCM) {
  499. switch (bits_per_sample) {
  500. case 8:
  501. ((int8_t *)buffer)[i] = sample >> 24;
  502. break;
  503. case 16:
  504. ((int16_t *)buffer)[i] = sample >> 16;
  505. break;
  506. case 24:
  507. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  508. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  509. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  510. break;
  511. case 32:
  512. ((int32_t *)buffer)[i] = sample;
  513. break;
  514. }
  515. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  516. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  517. } else {
  518. ERR_PRINT("WASAPI: Unknown format tag");
  519. }
  520. }
  521. void AudioDriverWASAPI::thread_func(void *p_udata) {
  522. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  523. uint32_t avail_frames = 0;
  524. uint32_t write_ofs = 0;
  525. while (!ad->exit_thread) {
  526. uint32_t read_frames = 0;
  527. uint32_t written_frames = 0;
  528. if (avail_frames == 0) {
  529. ad->lock();
  530. ad->start_counting_ticks();
  531. if (ad->audio_output.active) {
  532. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  533. } else {
  534. for (int i = 0; i < ad->samples_in.size(); i++) {
  535. ad->samples_in.write[i] = 0;
  536. }
  537. }
  538. avail_frames = ad->buffer_frames;
  539. write_ofs = 0;
  540. ad->stop_counting_ticks();
  541. ad->unlock();
  542. }
  543. ad->lock();
  544. ad->start_counting_ticks();
  545. if (avail_frames > 0 && ad->audio_output.audio_client) {
  546. UINT32 cur_frames;
  547. bool invalidated = false;
  548. HRESULT hr = ad->audio_output.audio_client->GetCurrentPadding(&cur_frames);
  549. if (hr == S_OK) {
  550. // Check how much frames are available on the WASAPI buffer
  551. UINT32 write_frames = MIN(ad->buffer_frames - cur_frames, avail_frames);
  552. if (write_frames > 0) {
  553. BYTE *buffer = nullptr;
  554. hr = ad->audio_output.render_client->GetBuffer(write_frames, &buffer);
  555. if (hr == S_OK) {
  556. // We're using WASAPI Shared Mode so we must convert the buffer
  557. if (ad->channels == ad->audio_output.channels) {
  558. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  559. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i, ad->samples_in.write[write_ofs++]);
  560. }
  561. } else {
  562. for (unsigned int i = 0; i < write_frames; i++) {
  563. for (unsigned int j = 0; j < MIN(ad->channels, ad->audio_output.channels); j++) {
  564. 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++]);
  565. }
  566. if (ad->audio_output.channels > ad->channels) {
  567. for (unsigned int j = ad->channels; j < ad->audio_output.channels; j++) {
  568. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, 0);
  569. }
  570. }
  571. }
  572. }
  573. hr = ad->audio_output.render_client->ReleaseBuffer(write_frames, 0);
  574. if (hr != S_OK) {
  575. ERR_PRINT("WASAPI: Release buffer error");
  576. }
  577. avail_frames -= write_frames;
  578. written_frames += write_frames;
  579. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  580. // Device is not valid anymore, reopen it
  581. Error err = ad->finish_render_device();
  582. if (err != OK) {
  583. ERR_PRINT("WASAPI: finish_render_device error");
  584. } else {
  585. // We reopened the device and samples_in may have resized, so invalidate the current avail_frames
  586. avail_frames = 0;
  587. }
  588. } else {
  589. ERR_PRINT("WASAPI: Get buffer error");
  590. ad->exit_thread = true;
  591. }
  592. }
  593. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  594. invalidated = true;
  595. } else {
  596. ERR_PRINT("WASAPI: GetCurrentPadding error");
  597. }
  598. if (invalidated) {
  599. // Device is not valid anymore
  600. WARN_PRINT("WASAPI: Current device invalidated, closing device");
  601. Error err = ad->finish_render_device();
  602. if (err != OK) {
  603. ERR_PRINT("WASAPI: finish_render_device error");
  604. }
  605. }
  606. }
  607. // If we're using the Default device and it changed finish it so we'll re-init the device
  608. if (ad->audio_output.device_name == "Default" && default_render_device_changed) {
  609. Error err = ad->finish_render_device();
  610. if (err != OK) {
  611. ERR_PRINT("WASAPI: finish_render_device error");
  612. }
  613. default_render_device_changed = false;
  614. }
  615. // User selected a new device, finish the current one so we'll init the new device
  616. if (ad->audio_output.device_name != ad->audio_output.new_device) {
  617. ad->audio_output.device_name = ad->audio_output.new_device;
  618. Error err = ad->finish_render_device();
  619. if (err != OK) {
  620. ERR_PRINT("WASAPI: finish_render_device error");
  621. }
  622. }
  623. if (!ad->audio_output.audio_client) {
  624. Error err = ad->init_render_device(true);
  625. if (err == OK) {
  626. ad->start();
  627. }
  628. avail_frames = 0;
  629. write_ofs = 0;
  630. }
  631. if (ad->audio_input.active) {
  632. UINT32 packet_length = 0;
  633. BYTE *data;
  634. UINT32 num_frames_available;
  635. DWORD flags;
  636. HRESULT hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  637. if (hr == S_OK) {
  638. while (packet_length != 0) {
  639. hr = ad->audio_input.capture_client->GetBuffer(&data, &num_frames_available, &flags, nullptr, nullptr);
  640. ERR_BREAK(hr != S_OK);
  641. // fixme: Only works for floating point atm
  642. for (UINT32 j = 0; j < num_frames_available; j++) {
  643. int32_t l, r;
  644. if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
  645. l = r = 0;
  646. } else {
  647. if (ad->audio_input.channels == 2) {
  648. l = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2);
  649. r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2 + 1);
  650. } else if (ad->audio_input.channels == 1) {
  651. l = r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j);
  652. } else {
  653. l = r = 0;
  654. ERR_PRINT("WASAPI: unsupported channel count in microphone!");
  655. }
  656. }
  657. ad->input_buffer_write(l);
  658. ad->input_buffer_write(r);
  659. }
  660. read_frames += num_frames_available;
  661. hr = ad->audio_input.capture_client->ReleaseBuffer(num_frames_available);
  662. ERR_BREAK(hr != S_OK);
  663. hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  664. ERR_BREAK(hr != S_OK);
  665. }
  666. }
  667. // If we're using the Default device and it changed finish it so we'll re-init the device
  668. if (ad->audio_input.device_name == "Default" && default_capture_device_changed) {
  669. Error err = ad->finish_capture_device();
  670. if (err != OK) {
  671. ERR_PRINT("WASAPI: finish_capture_device error");
  672. }
  673. default_capture_device_changed = false;
  674. }
  675. // User selected a new device, finish the current one so we'll init the new device
  676. if (ad->audio_input.device_name != ad->audio_input.new_device) {
  677. ad->audio_input.device_name = ad->audio_input.new_device;
  678. Error err = ad->finish_capture_device();
  679. if (err != OK) {
  680. ERR_PRINT("WASAPI: finish_capture_device error");
  681. }
  682. }
  683. if (!ad->audio_input.audio_client) {
  684. Error err = ad->init_capture_device(true);
  685. if (err == OK) {
  686. ad->capture_start();
  687. }
  688. }
  689. }
  690. ad->stop_counting_ticks();
  691. ad->unlock();
  692. // Let the thread rest a while if we haven't read or write anything
  693. if (written_frames == 0 && read_frames == 0) {
  694. OS::get_singleton()->delay_usec(1000);
  695. }
  696. }
  697. ad->thread_exited = true;
  698. }
  699. void AudioDriverWASAPI::start() {
  700. if (audio_output.audio_client) {
  701. HRESULT hr = audio_output.audio_client->Start();
  702. if (hr != S_OK) {
  703. ERR_PRINT("WASAPI: Start failed");
  704. } else {
  705. audio_output.active = true;
  706. }
  707. }
  708. }
  709. void AudioDriverWASAPI::lock() {
  710. mutex.lock();
  711. }
  712. void AudioDriverWASAPI::unlock() {
  713. mutex.unlock();
  714. }
  715. void AudioDriverWASAPI::finish() {
  716. exit_thread = true;
  717. thread.wait_to_finish();
  718. finish_capture_device();
  719. finish_render_device();
  720. }
  721. Error AudioDriverWASAPI::capture_start() {
  722. Error err = init_capture_device();
  723. if (err != OK) {
  724. ERR_PRINT("WASAPI: init_capture_device error");
  725. return err;
  726. }
  727. if (audio_input.active) {
  728. return FAILED;
  729. }
  730. audio_input.audio_client->Start();
  731. audio_input.active = true;
  732. return OK;
  733. }
  734. Error AudioDriverWASAPI::capture_stop() {
  735. if (audio_input.active) {
  736. audio_input.audio_client->Stop();
  737. audio_input.active = false;
  738. return OK;
  739. }
  740. return FAILED;
  741. }
  742. void AudioDriverWASAPI::capture_set_device(const String &p_name) {
  743. lock();
  744. audio_input.new_device = p_name;
  745. unlock();
  746. }
  747. Array AudioDriverWASAPI::capture_get_device_list() {
  748. return audio_device_get_list(true);
  749. }
  750. String AudioDriverWASAPI::capture_get_device() {
  751. lock();
  752. String name = audio_input.device_name;
  753. unlock();
  754. return name;
  755. }
  756. AudioDriverWASAPI::AudioDriverWASAPI() {
  757. samples_in.clear();
  758. }
  759. #endif // WASAPI_ENABLED