audio_driver_wasapi.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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/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_output_device_changed = false;
  99. static bool default_input_device_changed = false;
  100. // Silence warning due to a COM API weirdness (GH-35194).
  101. #if defined(__GNUC__) && !defined(__clang__)
  102. #pragma GCC diagnostic push
  103. #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
  104. #endif
  105. class CMMNotificationClient : public IMMNotificationClient {
  106. LONG _cRef = 1;
  107. IMMDeviceEnumerator *_pEnumerator = nullptr;
  108. public:
  109. CMMNotificationClient() {}
  110. virtual ~CMMNotificationClient() {
  111. if ((_pEnumerator) != nullptr) {
  112. (_pEnumerator)->Release();
  113. (_pEnumerator) = nullptr;
  114. }
  115. }
  116. ULONG STDMETHODCALLTYPE AddRef() {
  117. return InterlockedIncrement(&_cRef);
  118. }
  119. ULONG STDMETHODCALLTYPE Release() {
  120. ULONG ulRef = InterlockedDecrement(&_cRef);
  121. if (0 == ulRef) {
  122. delete this;
  123. }
  124. return ulRef;
  125. }
  126. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {
  127. if (IID_IUnknown == riid) {
  128. AddRef();
  129. *ppvInterface = (IUnknown *)this;
  130. } else if (__uuidof(IMMNotificationClient) == riid) {
  131. AddRef();
  132. *ppvInterface = (IMMNotificationClient *)this;
  133. } else {
  134. *ppvInterface = nullptr;
  135. return E_NOINTERFACE;
  136. }
  137. return S_OK;
  138. }
  139. HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
  140. return S_OK;
  141. }
  142. HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
  143. return S_OK;
  144. }
  145. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
  146. return S_OK;
  147. }
  148. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
  149. if (role == eConsole) {
  150. if (flow == eRender) {
  151. default_output_device_changed = true;
  152. } else if (flow == eCapture) {
  153. default_input_device_changed = true;
  154. }
  155. }
  156. return S_OK;
  157. }
  158. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
  159. return S_OK;
  160. }
  161. };
  162. #if defined(__GNUC__) && !defined(__clang__)
  163. #pragma GCC diagnostic pop
  164. #endif
  165. static CMMNotificationClient notif_client;
  166. Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_input, bool p_reinit, bool p_no_audio_client_3) {
  167. WAVEFORMATEX *pwfex;
  168. IMMDeviceEnumerator *enumerator = nullptr;
  169. IMMDevice *output_device = nullptr;
  170. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  171. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  172. if (p_device->device_name == "Default") {
  173. hr = enumerator->GetDefaultAudioEndpoint(p_input ? eCapture : eRender, eConsole, &output_device);
  174. } else {
  175. IMMDeviceCollection *devices = nullptr;
  176. hr = enumerator->EnumAudioEndpoints(p_input ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  177. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  178. LPWSTR strId = nullptr;
  179. bool found = false;
  180. UINT count = 0;
  181. hr = devices->GetCount(&count);
  182. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  183. for (ULONG i = 0; i < count && !found; i++) {
  184. IMMDevice *tmp_device = nullptr;
  185. hr = devices->Item(i, &tmp_device);
  186. ERR_BREAK(hr != S_OK);
  187. IPropertyStore *props = nullptr;
  188. hr = tmp_device->OpenPropertyStore(STGM_READ, &props);
  189. ERR_BREAK(hr != S_OK);
  190. PROPVARIANT propvar;
  191. PropVariantInit(&propvar);
  192. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  193. ERR_BREAK(hr != S_OK);
  194. if (p_device->device_name == String(propvar.pwszVal)) {
  195. hr = tmp_device->GetId(&strId);
  196. ERR_BREAK(hr != S_OK);
  197. found = true;
  198. }
  199. PropVariantClear(&propvar);
  200. props->Release();
  201. tmp_device->Release();
  202. }
  203. if (found) {
  204. hr = enumerator->GetDevice(strId, &output_device);
  205. }
  206. if (strId) {
  207. CoTaskMemFree(strId);
  208. }
  209. if (output_device == nullptr) {
  210. hr = enumerator->GetDefaultAudioEndpoint(p_input ? eCapture : eRender, eConsole, &output_device);
  211. }
  212. }
  213. if (p_reinit) {
  214. // In case we're trying to re-initialize the device, prevent throwing this error on the console,
  215. // otherwise if there is currently no device available this will spam the console.
  216. if (hr != S_OK) {
  217. return ERR_CANT_OPEN;
  218. }
  219. } else {
  220. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  221. }
  222. hr = enumerator->RegisterEndpointNotificationCallback(&notif_client);
  223. SAFE_RELEASE(enumerator)
  224. if (hr != S_OK) {
  225. ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");
  226. }
  227. using_audio_client_3 = !p_input; // IID_IAudioClient3 is only used for adjustable output latency (not input)
  228. if (p_no_audio_client_3) {
  229. using_audio_client_3 = false;
  230. }
  231. if (using_audio_client_3) {
  232. hr = output_device->Activate(IID_IAudioClient3, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);
  233. if (hr != S_OK) {
  234. // IID_IAudioClient3 will never activate on OS versions before Windows 10.
  235. // Older Windows versions should fall back gracefully.
  236. using_audio_client_3 = false;
  237. print_verbose("WASAPI: Couldn't activate output_device with IAudioClient3 interface, falling back to IAudioClient interface");
  238. } else {
  239. print_verbose("WASAPI: Activated output_device using IAudioClient3 interface");
  240. }
  241. }
  242. if (!using_audio_client_3) {
  243. hr = output_device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);
  244. }
  245. SAFE_RELEASE(output_device)
  246. if (p_reinit) {
  247. if (hr != S_OK) {
  248. return ERR_CANT_OPEN;
  249. }
  250. } else {
  251. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  252. }
  253. if (using_audio_client_3) {
  254. AudioClientProperties audioProps{};
  255. audioProps.cbSize = sizeof(AudioClientProperties);
  256. audioProps.bIsOffload = FALSE;
  257. audioProps.eCategory = AudioCategory_GameEffects;
  258. hr = ((IAudioClient3 *)p_device->audio_client)->SetClientProperties(&audioProps);
  259. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: SetClientProperties failed with error 0x" + String::num_uint64(hr, 16) + ".");
  260. }
  261. hr = p_device->audio_client->GetMixFormat(&pwfex);
  262. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  263. print_verbose("WASAPI: wFormatTag = " + itos(pwfex->wFormatTag));
  264. print_verbose("WASAPI: nChannels = " + itos(pwfex->nChannels));
  265. print_verbose("WASAPI: nSamplesPerSec = " + itos(pwfex->nSamplesPerSec));
  266. print_verbose("WASAPI: nAvgBytesPerSec = " + itos(pwfex->nAvgBytesPerSec));
  267. print_verbose("WASAPI: nBlockAlign = " + itos(pwfex->nBlockAlign));
  268. print_verbose("WASAPI: wBitsPerSample = " + itos(pwfex->wBitsPerSample));
  269. print_verbose("WASAPI: cbSize = " + itos(pwfex->cbSize));
  270. WAVEFORMATEX *closest = nullptr;
  271. hr = p_device->audio_client->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, pwfex, &closest);
  272. if (hr == S_FALSE) {
  273. WARN_PRINT("WASAPI: Mix format is not supported by the output_device");
  274. if (closest) {
  275. print_verbose("WASAPI: closest->wFormatTag = " + itos(closest->wFormatTag));
  276. print_verbose("WASAPI: closest->nChannels = " + itos(closest->nChannels));
  277. print_verbose("WASAPI: closest->nSamplesPerSec = " + itos(closest->nSamplesPerSec));
  278. print_verbose("WASAPI: closest->nAvgBytesPerSec = " + itos(closest->nAvgBytesPerSec));
  279. print_verbose("WASAPI: closest->nBlockAlign = " + itos(closest->nBlockAlign));
  280. print_verbose("WASAPI: closest->wBitsPerSample = " + itos(closest->wBitsPerSample));
  281. print_verbose("WASAPI: closest->cbSize = " + itos(closest->cbSize));
  282. WARN_PRINT("WASAPI: Using closest match instead");
  283. pwfex = closest;
  284. }
  285. }
  286. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  287. p_device->channels = pwfex->nChannels;
  288. p_device->format_tag = pwfex->wFormatTag;
  289. p_device->bits_per_sample = pwfex->wBitsPerSample;
  290. p_device->frame_size = (p_device->bits_per_sample / 8) * p_device->channels;
  291. if (p_device->format_tag == WAVE_FORMAT_EXTENSIBLE) {
  292. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  293. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  294. p_device->format_tag = WAVE_FORMAT_PCM;
  295. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  296. p_device->format_tag = WAVE_FORMAT_IEEE_FLOAT;
  297. } else {
  298. ERR_PRINT("WASAPI: Format not supported");
  299. ERR_FAIL_V(ERR_CANT_OPEN);
  300. }
  301. } else {
  302. if (p_device->format_tag != WAVE_FORMAT_PCM && p_device->format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  303. ERR_PRINT("WASAPI: Format not supported");
  304. ERR_FAIL_V(ERR_CANT_OPEN);
  305. }
  306. }
  307. if (!using_audio_client_3) {
  308. DWORD streamflags = 0;
  309. if ((DWORD)mix_rate != pwfex->nSamplesPerSec) {
  310. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  311. pwfex->nSamplesPerSec = mix_rate;
  312. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  313. }
  314. hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_input ? REFTIMES_PER_SEC : 0, 0, pwfex, nullptr);
  315. ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16) + ".");
  316. UINT32 max_frames;
  317. hr = p_device->audio_client->GetBufferSize(&max_frames);
  318. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  319. // Due to WASAPI Shared Mode we have no control of the buffer size
  320. if (!p_input) {
  321. buffer_frames = max_frames;
  322. int64_t latency = 0;
  323. audio_output.audio_client->GetStreamLatency(&latency);
  324. // WASAPI REFERENCE_TIME units are 100 nanoseconds per unit
  325. // https://docs.microsoft.com/en-us/windows/win32/directshow/reference-time
  326. // Convert REFTIME to seconds as godot uses for latency
  327. real_latency = (float)latency / (float)REFTIMES_PER_SEC;
  328. }
  329. } else {
  330. IAudioClient3 *device_audio_client_3 = (IAudioClient3 *)p_device->audio_client;
  331. // AUDCLNT_STREAMFLAGS_RATEADJUST is an invalid flag with IAudioClient3, therefore we have to use
  332. // the closest supported mix rate supported by the audio driver.
  333. mix_rate = pwfex->nSamplesPerSec;
  334. print_verbose("WASAPI: mix_rate = " + itos(mix_rate));
  335. UINT32 default_period_frames, fundamental_period_frames, min_period_frames, max_period_frames;
  336. hr = device_audio_client_3->GetSharedModeEnginePeriod(
  337. pwfex,
  338. &default_period_frames,
  339. &fundamental_period_frames,
  340. &min_period_frames,
  341. &max_period_frames);
  342. if (hr != S_OK) {
  343. print_verbose("WASAPI: GetSharedModeEnginePeriod failed with error 0x" + String::num_uint64(hr, 16) + ", falling back to IAudioClient.");
  344. CoTaskMemFree(pwfex);
  345. SAFE_RELEASE(output_device)
  346. return audio_device_init(p_device, p_input, p_reinit, true);
  347. }
  348. // Period frames must be an integral multiple of fundamental_period_frames or IAudioClient3 initialization will fail,
  349. // so we need to select the closest multiple to the user-specified latency.
  350. UINT32 desired_period_frames = target_latency_ms * mix_rate / 1000;
  351. UINT32 period_frames = (desired_period_frames / fundamental_period_frames) * fundamental_period_frames;
  352. if (ABS((int64_t)period_frames - (int64_t)desired_period_frames) > ABS((int64_t)(period_frames + fundamental_period_frames) - (int64_t)desired_period_frames)) {
  353. period_frames = period_frames + fundamental_period_frames;
  354. }
  355. period_frames = CLAMP(period_frames, min_period_frames, max_period_frames);
  356. print_verbose("WASAPI: fundamental_period_frames = " + itos(fundamental_period_frames));
  357. print_verbose("WASAPI: min_period_frames = " + itos(min_period_frames));
  358. print_verbose("WASAPI: max_period_frames = " + itos(max_period_frames));
  359. print_verbose("WASAPI: selected a period frame size of " + itos(period_frames));
  360. buffer_frames = period_frames;
  361. hr = device_audio_client_3->InitializeSharedAudioStream(0, period_frames, pwfex, nullptr);
  362. if (hr != S_OK) {
  363. print_verbose("WASAPI: InitializeSharedAudioStream failed with error 0x" + String::num_uint64(hr, 16) + ", falling back to IAudioClient.");
  364. CoTaskMemFree(pwfex);
  365. SAFE_RELEASE(output_device);
  366. return audio_device_init(p_device, p_input, p_reinit, true);
  367. } else {
  368. uint32_t output_latency_in_frames;
  369. WAVEFORMATEX *current_pwfex;
  370. hr = device_audio_client_3->GetCurrentSharedModeEnginePeriod(&current_pwfex, &output_latency_in_frames);
  371. if (hr == OK) {
  372. real_latency = (float)output_latency_in_frames / (float)current_pwfex->nSamplesPerSec;
  373. CoTaskMemFree(current_pwfex);
  374. } else {
  375. print_verbose("WASAPI: GetCurrentSharedModeEnginePeriod failed with error 0x" + String::num_uint64(hr, 16) + ", falling back to IAudioClient.");
  376. CoTaskMemFree(pwfex);
  377. SAFE_RELEASE(output_device);
  378. return audio_device_init(p_device, p_input, p_reinit, true);
  379. }
  380. }
  381. }
  382. if (p_input) {
  383. hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);
  384. } else {
  385. hr = p_device->audio_client->GetService(IID_IAudioRenderClient, (void **)&p_device->render_client);
  386. }
  387. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  388. // Free memory
  389. CoTaskMemFree(pwfex);
  390. SAFE_RELEASE(output_device)
  391. return OK;
  392. }
  393. Error AudioDriverWASAPI::init_output_device(bool p_reinit) {
  394. Error err = audio_device_init(&audio_output, false, p_reinit);
  395. if (err != OK) {
  396. return err;
  397. }
  398. switch (audio_output.channels) {
  399. case 1: // Mono
  400. case 3: // Surround 2.1
  401. case 5: // Surround 5.0
  402. case 7: // Surround 7.0
  403. // We will downmix as required.
  404. channels = audio_output.channels + 1;
  405. break;
  406. case 2: // Stereo
  407. case 4: // Surround 3.1
  408. case 6: // Surround 5.1
  409. case 8: // Surround 7.1
  410. channels = audio_output.channels;
  411. break;
  412. default:
  413. WARN_PRINT("WASAPI: Unsupported number of channels: " + itos(audio_output.channels));
  414. channels = 2;
  415. break;
  416. }
  417. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  418. samples_in.resize(buffer_frames * channels);
  419. input_position = 0;
  420. input_size = 0;
  421. print_verbose("WASAPI: detected " + itos(audio_output.channels) + " channels");
  422. print_verbose("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  423. return OK;
  424. }
  425. Error AudioDriverWASAPI::init_input_device(bool p_reinit) {
  426. Error err = audio_device_init(&audio_input, true, p_reinit);
  427. if (err != OK) {
  428. return err;
  429. }
  430. // Get the max frames
  431. UINT32 max_frames;
  432. HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames);
  433. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  434. input_buffer_init(max_frames);
  435. return OK;
  436. }
  437. Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {
  438. if (p_device->active.is_set()) {
  439. if (p_device->audio_client) {
  440. p_device->audio_client->Stop();
  441. }
  442. p_device->active.clear();
  443. }
  444. SAFE_RELEASE(p_device->audio_client)
  445. SAFE_RELEASE(p_device->render_client)
  446. SAFE_RELEASE(p_device->capture_client)
  447. return OK;
  448. }
  449. Error AudioDriverWASAPI::finish_output_device() {
  450. return audio_device_finish(&audio_output);
  451. }
  452. Error AudioDriverWASAPI::finish_input_device() {
  453. return audio_device_finish(&audio_input);
  454. }
  455. Error AudioDriverWASAPI::init() {
  456. mix_rate = _get_configured_mix_rate();
  457. target_latency_ms = GLOBAL_GET("audio/driver/output_latency");
  458. Error err = init_output_device();
  459. if (err != OK) {
  460. ERR_PRINT("WASAPI: init_output_device error");
  461. }
  462. exit_thread.clear();
  463. thread.start(thread_func, this);
  464. return OK;
  465. }
  466. int AudioDriverWASAPI::get_mix_rate() const {
  467. return mix_rate;
  468. }
  469. float AudioDriverWASAPI::get_latency() {
  470. return real_latency;
  471. }
  472. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  473. return get_speaker_mode_by_total_channels(channels);
  474. }
  475. PackedStringArray AudioDriverWASAPI::audio_device_get_list(bool p_input) {
  476. PackedStringArray list;
  477. IMMDeviceCollection *devices = nullptr;
  478. IMMDeviceEnumerator *enumerator = nullptr;
  479. list.push_back(String("Default"));
  480. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  481. ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());
  482. hr = enumerator->EnumAudioEndpoints(p_input ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);
  483. ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());
  484. UINT count = 0;
  485. hr = devices->GetCount(&count);
  486. ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());
  487. for (ULONG i = 0; i < count; i++) {
  488. IMMDevice *output_device = nullptr;
  489. hr = devices->Item(i, &output_device);
  490. ERR_BREAK(hr != S_OK);
  491. IPropertyStore *props = nullptr;
  492. hr = output_device->OpenPropertyStore(STGM_READ, &props);
  493. ERR_BREAK(hr != S_OK);
  494. PROPVARIANT propvar;
  495. PropVariantInit(&propvar);
  496. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  497. ERR_BREAK(hr != S_OK);
  498. list.push_back(String(propvar.pwszVal));
  499. PropVariantClear(&propvar);
  500. props->Release();
  501. output_device->Release();
  502. }
  503. devices->Release();
  504. enumerator->Release();
  505. return list;
  506. }
  507. PackedStringArray AudioDriverWASAPI::get_output_device_list() {
  508. return audio_device_get_list(false);
  509. }
  510. String AudioDriverWASAPI::get_output_device() {
  511. lock();
  512. String name = audio_output.device_name;
  513. unlock();
  514. return name;
  515. }
  516. void AudioDriverWASAPI::set_output_device(const String &p_name) {
  517. lock();
  518. audio_output.new_device = p_name;
  519. unlock();
  520. }
  521. int32_t AudioDriverWASAPI::read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i) {
  522. if (format_tag == WAVE_FORMAT_PCM) {
  523. int32_t sample = 0;
  524. switch (bits_per_sample) {
  525. case 8:
  526. sample = int32_t(((int8_t *)buffer)[i]) << 24;
  527. break;
  528. case 16:
  529. sample = int32_t(((int16_t *)buffer)[i]) << 16;
  530. break;
  531. case 24:
  532. sample |= int32_t(((int8_t *)buffer)[i * 3 + 2]) << 24;
  533. sample |= int32_t(((int8_t *)buffer)[i * 3 + 1]) << 16;
  534. sample |= int32_t(((int8_t *)buffer)[i * 3 + 0]) << 8;
  535. break;
  536. case 32:
  537. sample = ((int32_t *)buffer)[i];
  538. break;
  539. }
  540. return sample;
  541. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  542. return int32_t(((float *)buffer)[i] * 32768.0) << 16;
  543. } else {
  544. ERR_PRINT("WASAPI: Unknown format tag");
  545. }
  546. return 0;
  547. }
  548. void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample) {
  549. if (format_tag == WAVE_FORMAT_PCM) {
  550. switch (bits_per_sample) {
  551. case 8:
  552. ((int8_t *)buffer)[i] = sample >> 24;
  553. break;
  554. case 16:
  555. ((int16_t *)buffer)[i] = sample >> 16;
  556. break;
  557. case 24:
  558. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  559. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  560. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  561. break;
  562. case 32:
  563. ((int32_t *)buffer)[i] = sample;
  564. break;
  565. }
  566. } else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  567. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  568. } else {
  569. ERR_PRINT("WASAPI: Unknown format tag");
  570. }
  571. }
  572. void AudioDriverWASAPI::thread_func(void *p_udata) {
  573. CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  574. AudioDriverWASAPI *ad = static_cast<AudioDriverWASAPI *>(p_udata);
  575. uint32_t avail_frames = 0;
  576. uint32_t write_ofs = 0;
  577. while (!ad->exit_thread.is_set()) {
  578. uint32_t read_frames = 0;
  579. uint32_t written_frames = 0;
  580. if (avail_frames == 0) {
  581. ad->lock();
  582. ad->start_counting_ticks();
  583. if (ad->audio_output.active.is_set()) {
  584. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  585. } else {
  586. for (int i = 0; i < ad->samples_in.size(); i++) {
  587. ad->samples_in.write[i] = 0;
  588. }
  589. }
  590. avail_frames = ad->buffer_frames;
  591. write_ofs = 0;
  592. ad->stop_counting_ticks();
  593. ad->unlock();
  594. }
  595. ad->lock();
  596. ad->start_counting_ticks();
  597. if (avail_frames > 0 && ad->audio_output.audio_client) {
  598. UINT32 buffer_size;
  599. UINT32 cur_frames;
  600. bool invalidated = false;
  601. HRESULT hr = ad->audio_output.audio_client->GetBufferSize(&buffer_size);
  602. if (hr != S_OK) {
  603. ERR_PRINT("WASAPI: GetBufferSize error");
  604. }
  605. hr = ad->audio_output.audio_client->GetCurrentPadding(&cur_frames);
  606. if (hr == S_OK) {
  607. // Check how much frames are available on the WASAPI buffer
  608. UINT32 write_frames = MIN(buffer_size - cur_frames, avail_frames);
  609. if (write_frames > 0) {
  610. BYTE *buffer = nullptr;
  611. hr = ad->audio_output.render_client->GetBuffer(write_frames, &buffer);
  612. if (hr == S_OK) {
  613. // We're using WASAPI Shared Mode so we must convert the buffer
  614. if (ad->channels == ad->audio_output.channels) {
  615. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  616. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i, ad->samples_in.write[write_ofs++]);
  617. }
  618. } else if (ad->channels == ad->audio_output.channels + 1) {
  619. // Pass all channels except the last two as-is, and then mix the last two
  620. // together as one channel. E.g. stereo -> mono, or 3.1 -> 2.1.
  621. unsigned int last_chan = ad->audio_output.channels - 1;
  622. for (unsigned int i = 0; i < write_frames; i++) {
  623. for (unsigned int j = 0; j < last_chan; j++) {
  624. 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++]);
  625. }
  626. int32_t l = ad->samples_in.write[write_ofs++];
  627. int32_t r = ad->samples_in.write[write_ofs++];
  628. int32_t c = (int32_t)(((int64_t)l + (int64_t)r) / 2);
  629. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + last_chan, c);
  630. }
  631. } else {
  632. for (unsigned int i = 0; i < write_frames; i++) {
  633. for (unsigned int j = 0; j < MIN(ad->channels, ad->audio_output.channels); j++) {
  634. 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++]);
  635. }
  636. if (ad->audio_output.channels > ad->channels) {
  637. for (unsigned int j = ad->channels; j < ad->audio_output.channels; j++) {
  638. ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, 0);
  639. }
  640. }
  641. }
  642. }
  643. hr = ad->audio_output.render_client->ReleaseBuffer(write_frames, 0);
  644. if (hr != S_OK) {
  645. ERR_PRINT("WASAPI: Release buffer error");
  646. }
  647. avail_frames -= write_frames;
  648. written_frames += write_frames;
  649. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  650. // output_device is not valid anymore, reopen it
  651. Error err = ad->finish_output_device();
  652. if (err != OK) {
  653. ERR_PRINT("WASAPI: finish_output_device error");
  654. } else {
  655. // We reopened the output device and samples_in may have resized, so invalidate the current avail_frames
  656. avail_frames = 0;
  657. }
  658. } else {
  659. ERR_PRINT("WASAPI: Get buffer error");
  660. ad->exit_thread.set();
  661. }
  662. }
  663. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  664. invalidated = true;
  665. } else {
  666. ERR_PRINT("WASAPI: GetCurrentPadding error");
  667. }
  668. if (invalidated) {
  669. // output_device is not valid anymore
  670. WARN_PRINT("WASAPI: Current output_device invalidated, closing output_device");
  671. Error err = ad->finish_output_device();
  672. if (err != OK) {
  673. ERR_PRINT("WASAPI: finish_output_device error");
  674. }
  675. }
  676. }
  677. // If we're using the Default output device and it changed finish it so we'll re-init the output device
  678. if (ad->audio_output.device_name == "Default" && default_output_device_changed) {
  679. Error err = ad->finish_output_device();
  680. if (err != OK) {
  681. ERR_PRINT("WASAPI: finish_output_device error");
  682. }
  683. default_output_device_changed = false;
  684. }
  685. // User selected a new output device, finish the current one so we'll init the new output device
  686. if (ad->audio_output.device_name != ad->audio_output.new_device) {
  687. ad->audio_output.device_name = ad->audio_output.new_device;
  688. Error err = ad->finish_output_device();
  689. if (err != OK) {
  690. ERR_PRINT("WASAPI: finish_output_device error");
  691. }
  692. }
  693. if (!ad->audio_output.audio_client) {
  694. Error err = ad->init_output_device(true);
  695. if (err == OK) {
  696. ad->start();
  697. }
  698. avail_frames = 0;
  699. write_ofs = 0;
  700. }
  701. if (ad->audio_input.active.is_set()) {
  702. UINT32 packet_length = 0;
  703. BYTE *data;
  704. UINT32 num_frames_available;
  705. DWORD flags;
  706. HRESULT hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  707. if (hr == S_OK) {
  708. while (packet_length != 0) {
  709. hr = ad->audio_input.capture_client->GetBuffer(&data, &num_frames_available, &flags, nullptr, nullptr);
  710. ERR_BREAK(hr != S_OK);
  711. // fixme: Only works for floating point atm
  712. for (UINT32 j = 0; j < num_frames_available; j++) {
  713. int32_t l, r;
  714. if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
  715. l = r = 0;
  716. } else {
  717. if (ad->audio_input.channels == 2) {
  718. l = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2);
  719. r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2 + 1);
  720. } else if (ad->audio_input.channels == 1) {
  721. l = r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j);
  722. } else {
  723. l = r = 0;
  724. ERR_PRINT("WASAPI: unsupported channel count in microphone!");
  725. }
  726. }
  727. ad->input_buffer_write(l);
  728. ad->input_buffer_write(r);
  729. }
  730. read_frames += num_frames_available;
  731. hr = ad->audio_input.capture_client->ReleaseBuffer(num_frames_available);
  732. ERR_BREAK(hr != S_OK);
  733. hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);
  734. ERR_BREAK(hr != S_OK);
  735. }
  736. }
  737. // If we're using the Default output device and it changed finish it so we'll re-init the output device
  738. if (ad->audio_input.device_name == "Default" && default_input_device_changed) {
  739. Error err = ad->finish_input_device();
  740. if (err != OK) {
  741. ERR_PRINT("WASAPI: finish_input_device error");
  742. }
  743. default_input_device_changed = false;
  744. }
  745. // User selected a new input device, finish the current one so we'll init the new input device
  746. if (ad->audio_input.device_name != ad->audio_input.new_device) {
  747. ad->audio_input.device_name = ad->audio_input.new_device;
  748. Error err = ad->finish_input_device();
  749. if (err != OK) {
  750. ERR_PRINT("WASAPI: finish_input_device error");
  751. }
  752. }
  753. if (!ad->audio_input.audio_client) {
  754. Error err = ad->init_input_device(true);
  755. if (err == OK) {
  756. ad->input_start();
  757. }
  758. }
  759. }
  760. ad->stop_counting_ticks();
  761. ad->unlock();
  762. // Let the thread rest a while if we haven't read or write anything
  763. if (written_frames == 0 && read_frames == 0) {
  764. OS::get_singleton()->delay_usec(1000);
  765. }
  766. }
  767. CoUninitialize();
  768. }
  769. void AudioDriverWASAPI::start() {
  770. if (audio_output.audio_client) {
  771. HRESULT hr = audio_output.audio_client->Start();
  772. if (hr != S_OK) {
  773. ERR_PRINT("WASAPI: Start failed");
  774. } else {
  775. audio_output.active.set();
  776. }
  777. }
  778. }
  779. void AudioDriverWASAPI::lock() {
  780. mutex.lock();
  781. }
  782. void AudioDriverWASAPI::unlock() {
  783. mutex.unlock();
  784. }
  785. void AudioDriverWASAPI::finish() {
  786. exit_thread.set();
  787. thread.wait_to_finish();
  788. finish_input_device();
  789. finish_output_device();
  790. }
  791. Error AudioDriverWASAPI::input_start() {
  792. Error err = init_input_device();
  793. if (err != OK) {
  794. ERR_PRINT("WASAPI: init_input_device error");
  795. return err;
  796. }
  797. if (audio_input.active.is_set()) {
  798. return FAILED;
  799. }
  800. audio_input.audio_client->Start();
  801. audio_input.active.set();
  802. return OK;
  803. }
  804. Error AudioDriverWASAPI::input_stop() {
  805. if (audio_input.active.is_set()) {
  806. audio_input.audio_client->Stop();
  807. audio_input.active.clear();
  808. return OK;
  809. }
  810. return FAILED;
  811. }
  812. PackedStringArray AudioDriverWASAPI::get_input_device_list() {
  813. return audio_device_get_list(true);
  814. }
  815. String AudioDriverWASAPI::get_input_device() {
  816. lock();
  817. String name = audio_input.device_name;
  818. unlock();
  819. return name;
  820. }
  821. void AudioDriverWASAPI::set_input_device(const String &p_name) {
  822. lock();
  823. audio_input.new_device = p_name;
  824. unlock();
  825. }
  826. AudioDriverWASAPI::AudioDriverWASAPI() {
  827. samples_in.clear();
  828. }
  829. #endif // WASAPI_ENABLED