audio_driver_wasapi.cpp 31 KB

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