audio_driver_wasapi.cpp 30 KB

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