Path: blob/master/drivers/wasapi/audio_driver_wasapi.cpp
9903 views
/**************************************************************************/1/* audio_driver_wasapi.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#ifdef WASAPI_ENABLED3132#include "audio_driver_wasapi.h"3334#include "core/config/project_settings.h"35#include "core/os/os.h"3637#include <functiondiscoverykeys.h>3839#include <wrl/client.h>40using Microsoft::WRL::ComPtr;4142// Define IAudioClient3 if not already defined by MinGW headers43#if defined __MINGW32__ || defined __MINGW64__4445#ifndef __IAudioClient3_FWD_DEFINED__46#define __IAudioClient3_FWD_DEFINED__4748typedef interface IAudioClient3 IAudioClient3;4950#endif // __IAudioClient3_FWD_DEFINED__5152#ifndef __IAudioClient3_INTERFACE_DEFINED__53#define __IAudioClient3_INTERFACE_DEFINED__5455// clang-format off56MIDL_INTERFACE("7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42")57IAudioClient3 : public IAudioClient2 {58public:59virtual HRESULT STDMETHODCALLTYPE GetSharedModeEnginePeriod(60/* [annotation][in] */61_In_ const WAVEFORMATEX *pFormat,62/* [annotation][out] */63_Out_ UINT32 *pDefaultPeriodInFrames,64/* [annotation][out] */65_Out_ UINT32 *pFundamentalPeriodInFrames,66/* [annotation][out] */67_Out_ UINT32 *pMinPeriodInFrames,68/* [annotation][out] */69_Out_ UINT32 *pMaxPeriodInFrames) = 0;7071virtual HRESULT STDMETHODCALLTYPE GetCurrentSharedModeEnginePeriod(72/* [unique][annotation][out] */73_Out_ WAVEFORMATEX * *ppFormat,74/* [annotation][out] */75_Out_ UINT32 * pCurrentPeriodInFrames) = 0;7677virtual HRESULT STDMETHODCALLTYPE InitializeSharedAudioStream(78/* [annotation][in] */79_In_ DWORD StreamFlags,80/* [annotation][in] */81_In_ UINT32 PeriodInFrames,82/* [annotation][in] */83_In_ const WAVEFORMATEX *pFormat,84/* [annotation][in] */85_In_opt_ LPCGUID AudioSessionGuid) = 0;86};87// clang-format on88__CRT_UUID_DECL(IAudioClient3, 0x7ED4EE07, 0x8E67, 0x4CD4, 0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42)8990#endif // __IAudioClient3_INTERFACE_DEFINED__9192#endif // __MINGW32__ || __MINGW64__9394#ifndef PKEY_Device_FriendlyNameGodot9596#undef DEFINE_PROPERTYKEY97/* clang-format off */98#define DEFINE_PROPERTYKEY(id, a, b, c, d, e, f, g, h, i, j, k, l) \99const PROPERTYKEY id = { { a, b, c, { d, e, f, g, h, i, j, k, } }, l };100/* clang-format on */101102DEFINE_PROPERTYKEY(PKEY_Device_FriendlyNameGodot, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);103#endif104105const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);106const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);107const IID IID_IAudioClient = __uuidof(IAudioClient);108const IID IID_IAudioClient3 = __uuidof(IAudioClient3);109const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);110const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);111112#define SAFE_RELEASE(memory) \113if ((memory) != nullptr) { \114(memory)->Release(); \115(memory) = nullptr; \116}117118#define REFTIMES_PER_SEC 10000000119#define REFTIMES_PER_MILLISEC 10000120121#define CAPTURE_BUFFER_CHANNELS 2122123static bool default_output_device_changed = false;124static bool default_input_device_changed = false;125static int output_reinit_countdown = 0;126static int input_reinit_countdown = 0;127128GODOT_GCC_WARNING_PUSH_AND_IGNORE("-Wnon-virtual-dtor") // Silence warning due to a COM API weirdness (GH-35194).129130class CMMNotificationClient : public IMMNotificationClient {131LONG _cRef = 1;132133public:134ComPtr<IMMDeviceEnumerator> enumerator = nullptr;135136CMMNotificationClient() {}137virtual ~CMMNotificationClient() {}138139ULONG STDMETHODCALLTYPE AddRef() {140return InterlockedIncrement(&_cRef);141}142143ULONG STDMETHODCALLTYPE Release() {144ULONG ulRef = InterlockedDecrement(&_cRef);145if (0 == ulRef) {146delete this;147}148return ulRef;149}150151HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {152if (IID_IUnknown == riid) {153AddRef();154*ppvInterface = (IUnknown *)this;155} else if (__uuidof(IMMNotificationClient) == riid) {156AddRef();157*ppvInterface = (IMMNotificationClient *)this;158} else {159*ppvInterface = nullptr;160return E_NOINTERFACE;161}162return S_OK;163}164165HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {166return S_OK;167}168169HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {170return S_OK;171}172173HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {174return S_OK;175}176177HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {178if (role == eConsole) {179if (flow == eRender) {180default_output_device_changed = true;181} else if (flow == eCapture) {182default_input_device_changed = true;183}184}185186return S_OK;187}188189HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {190return S_OK;191}192};193194GODOT_GCC_WARNING_POP195196static CMMNotificationClient notif_client;197198Error AudioDriverWASAPI::audio_device_init(AudioDeviceWASAPI *p_device, bool p_input, bool p_reinit, bool p_no_audio_client_3) {199// This function can be called recursively, so clean up before starting:200audio_device_finish(p_device);201202WAVEFORMATEX *pwfex;203ComPtr<IMMDeviceEnumerator> enumerator = nullptr;204ComPtr<IMMDevice> output_device = nullptr;205206HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);207ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);208209if (p_device->device_name == "Default") {210hr = enumerator->GetDefaultAudioEndpoint(p_input ? eCapture : eRender, eConsole, &output_device);211} else {212ComPtr<IMMDeviceCollection> devices = nullptr;213214hr = enumerator->EnumAudioEndpoints(p_input ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);215ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);216217LPWSTR strId = nullptr;218bool found = false;219220UINT count = 0;221hr = devices->GetCount(&count);222ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);223224for (ULONG i = 0; i < count && !found; i++) {225ComPtr<IMMDevice> tmp_device = nullptr;226227hr = devices->Item(i, &tmp_device);228ERR_BREAK_MSG(hr != S_OK, "Cannot get devices item.");229230ComPtr<IPropertyStore> props = nullptr;231hr = tmp_device->OpenPropertyStore(STGM_READ, &props);232ERR_BREAK_MSG(hr != S_OK, "Cannot open property store.");233234PROPVARIANT propvar;235PropVariantInit(&propvar);236237hr = props->GetValue(PKEY_Device_FriendlyNameGodot, &propvar);238ERR_BREAK_MSG(hr != S_OK, "Cannot get value.");239240if (p_device->device_name == String(propvar.pwszVal)) {241hr = tmp_device->GetId(&strId);242if (unlikely(hr != S_OK)) {243PropVariantClear(&propvar);244ERR_PRINT("Cannot get device ID string.");245break;246}247248found = true;249}250251PropVariantClear(&propvar);252}253254if (found) {255hr = enumerator->GetDevice(strId, &output_device);256}257258if (strId) {259CoTaskMemFree(strId);260}261262if (output_device == nullptr) {263hr = enumerator->GetDefaultAudioEndpoint(p_input ? eCapture : eRender, eConsole, &output_device);264}265}266267if (p_reinit) {268// In case we're trying to re-initialize the device, prevent throwing this error on the console,269// otherwise if there is currently no device available this will spam the console.270if (hr != S_OK) {271return ERR_CANT_OPEN;272}273} else {274ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);275}276277if (notif_client.enumerator != nullptr) {278notif_client.enumerator->UnregisterEndpointNotificationCallback(¬if_client);279notif_client.enumerator = nullptr;280}281hr = enumerator->RegisterEndpointNotificationCallback(¬if_client);282if (hr == S_OK) {283notif_client.enumerator = enumerator;284} else {285ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");286}287288using_audio_client_3 = !p_input; // IID_IAudioClient3 is only used for adjustable output latency (not input)289290if (p_no_audio_client_3) {291using_audio_client_3 = false;292}293294if (using_audio_client_3) {295hr = output_device->Activate(IID_IAudioClient3, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);296if (hr != S_OK) {297// IID_IAudioClient3 will never activate on OS versions before Windows 10.298// Older Windows versions should fall back gracefully.299using_audio_client_3 = false;300print_verbose("WASAPI: Couldn't activate output_device with IAudioClient3 interface, falling back to IAudioClient interface");301} else {302print_verbose("WASAPI: Activated output_device using IAudioClient3 interface");303}304}305if (!using_audio_client_3) {306hr = output_device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, (void **)&p_device->audio_client);307}308309if (p_reinit) {310if (hr != S_OK) {311return ERR_CANT_OPEN;312}313} else {314ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);315}316317if (using_audio_client_3) {318AudioClientProperties audioProps{};319audioProps.cbSize = sizeof(AudioClientProperties);320audioProps.bIsOffload = FALSE;321audioProps.eCategory = AudioCategory_GameEffects;322323hr = ((IAudioClient3 *)p_device->audio_client)->SetClientProperties(&audioProps);324ERR_FAIL_COND_V_MSG(hr != S_OK, ERR_CANT_OPEN, "WASAPI: SetClientProperties failed with error 0x" + String::num_uint64(hr, 16) + ".");325}326327hr = p_device->audio_client->GetMixFormat(&pwfex);328ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);329// From this point onward, CoTaskMemFree(pwfex) must be called before returning or pwfex will leak!330331print_verbose("WASAPI: wFormatTag = " + itos(pwfex->wFormatTag));332print_verbose("WASAPI: nChannels = " + itos(pwfex->nChannels));333print_verbose("WASAPI: nSamplesPerSec = " + itos(pwfex->nSamplesPerSec));334print_verbose("WASAPI: nAvgBytesPerSec = " + itos(pwfex->nAvgBytesPerSec));335print_verbose("WASAPI: nBlockAlign = " + itos(pwfex->nBlockAlign));336print_verbose("WASAPI: wBitsPerSample = " + itos(pwfex->wBitsPerSample));337print_verbose("WASAPI: cbSize = " + itos(pwfex->cbSize));338339WAVEFORMATEX *closest = nullptr;340hr = p_device->audio_client->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, pwfex, &closest);341if (hr == S_FALSE) {342WARN_PRINT("WASAPI: Mix format is not supported by the output_device");343if (closest) {344print_verbose("WASAPI: closest->wFormatTag = " + itos(closest->wFormatTag));345print_verbose("WASAPI: closest->nChannels = " + itos(closest->nChannels));346print_verbose("WASAPI: closest->nSamplesPerSec = " + itos(closest->nSamplesPerSec));347print_verbose("WASAPI: closest->nAvgBytesPerSec = " + itos(closest->nAvgBytesPerSec));348print_verbose("WASAPI: closest->nBlockAlign = " + itos(closest->nBlockAlign));349print_verbose("WASAPI: closest->wBitsPerSample = " + itos(closest->wBitsPerSample));350print_verbose("WASAPI: closest->cbSize = " + itos(closest->cbSize));351352WARN_PRINT("WASAPI: Using closest match instead");353CoTaskMemFree(pwfex);354pwfex = closest;355}356}357358// Since we're using WASAPI Shared Mode we can't control any of these, we just tag along359p_device->channels = pwfex->nChannels;360p_device->format_tag = pwfex->wFormatTag;361p_device->bits_per_sample = pwfex->wBitsPerSample;362p_device->frame_size = (p_device->bits_per_sample / 8) * p_device->channels;363364if (p_device->format_tag == WAVE_FORMAT_EXTENSIBLE) {365WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;366367if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {368p_device->format_tag = WAVE_FORMAT_PCM;369} else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {370p_device->format_tag = WAVE_FORMAT_IEEE_FLOAT;371} else {372ERR_PRINT("WASAPI: Format not supported");373CoTaskMemFree(pwfex);374ERR_FAIL_V(ERR_CANT_OPEN);375}376} else {377if (p_device->format_tag != WAVE_FORMAT_PCM && p_device->format_tag != WAVE_FORMAT_IEEE_FLOAT) {378ERR_PRINT("WASAPI: Format not supported");379CoTaskMemFree(pwfex);380ERR_FAIL_V(ERR_CANT_OPEN);381}382}383384if (!using_audio_client_3) {385DWORD streamflags = 0;386if ((DWORD)mix_rate != pwfex->nSamplesPerSec) {387streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;388pwfex->nSamplesPerSec = mix_rate;389pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);390}391hr = p_device->audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, p_input ? REFTIMES_PER_SEC : 0, 0, pwfex, nullptr);392393if (p_reinit) {394// In case we're trying to re-initialize the device, prevent throwing this error on the console,395// otherwise if there is currently no device available this will spam the console.396if (hr != S_OK) {397print_verbose("WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16) + ".");398CoTaskMemFree(pwfex);399return ERR_CANT_OPEN;400}401} else {402if (unlikely(hr != S_OK)) {403CoTaskMemFree(pwfex);404ERR_FAIL_V_MSG(ERR_CANT_OPEN, "WASAPI: Initialize failed with error 0x" + String::num_uint64(hr, 16) + ".");405}406}407408UINT32 max_frames;409hr = p_device->audio_client->GetBufferSize(&max_frames);410if (unlikely(hr != S_OK)) {411CoTaskMemFree(pwfex);412ERR_FAIL_V(ERR_CANT_OPEN);413}414415// Due to WASAPI Shared Mode we have no control of the buffer size416if (!p_input) {417buffer_frames = max_frames;418419int64_t latency = 0;420audio_output.audio_client->GetStreamLatency(&latency);421// WASAPI REFERENCE_TIME units are 100 nanoseconds per unit422// https://docs.microsoft.com/en-us/windows/win32/directshow/reference-time423// Convert REFTIME to seconds as godot uses for latency424real_latency = (float)latency / (float)REFTIMES_PER_SEC;425}426427} else {428IAudioClient3 *device_audio_client_3 = (IAudioClient3 *)p_device->audio_client;429430// AUDCLNT_STREAMFLAGS_RATEADJUST is an invalid flag with IAudioClient3, therefore we have to use431// the closest supported mix rate supported by the audio driver.432mix_rate = pwfex->nSamplesPerSec;433print_verbose("WASAPI: mix_rate = " + itos(mix_rate));434435UINT32 default_period_frames, fundamental_period_frames, min_period_frames, max_period_frames;436hr = device_audio_client_3->GetSharedModeEnginePeriod(437pwfex,438&default_period_frames,439&fundamental_period_frames,440&min_period_frames,441&max_period_frames);442if (hr != S_OK) {443print_verbose("WASAPI: GetSharedModeEnginePeriod failed with error 0x" + String::num_uint64(hr, 16) + ", falling back to IAudioClient.");444CoTaskMemFree(pwfex);445return audio_device_init(p_device, p_input, p_reinit, true);446}447448// Period frames must be an integral multiple of fundamental_period_frames or IAudioClient3 initialization will fail,449// so we need to select the closest multiple to the user-specified latency.450UINT32 desired_period_frames = target_latency_ms * mix_rate / 1000;451UINT32 period_frames = (desired_period_frames / fundamental_period_frames) * fundamental_period_frames;452if (Math::abs((int64_t)period_frames - (int64_t)desired_period_frames) > Math::abs((int64_t)(period_frames + fundamental_period_frames) - (int64_t)desired_period_frames)) {453period_frames = period_frames + fundamental_period_frames;454}455period_frames = CLAMP(period_frames, min_period_frames, max_period_frames);456print_verbose("WASAPI: fundamental_period_frames = " + itos(fundamental_period_frames));457print_verbose("WASAPI: min_period_frames = " + itos(min_period_frames));458print_verbose("WASAPI: max_period_frames = " + itos(max_period_frames));459print_verbose("WASAPI: selected a period frame size of " + itos(period_frames));460buffer_frames = period_frames;461462hr = device_audio_client_3->InitializeSharedAudioStream(0, period_frames, pwfex, nullptr);463if (hr != S_OK) {464print_verbose("WASAPI: InitializeSharedAudioStream failed with error 0x" + String::num_uint64(hr, 16) + ", falling back to IAudioClient.");465CoTaskMemFree(pwfex);466return audio_device_init(p_device, p_input, p_reinit, true);467} else {468uint32_t output_latency_in_frames;469WAVEFORMATEX *current_pwfex;470hr = device_audio_client_3->GetCurrentSharedModeEnginePeriod(¤t_pwfex, &output_latency_in_frames);471if (hr == OK) {472real_latency = (float)output_latency_in_frames / (float)current_pwfex->nSamplesPerSec;473CoTaskMemFree(current_pwfex);474} else {475print_verbose("WASAPI: GetCurrentSharedModeEnginePeriod failed with error 0x" + String::num_uint64(hr, 16) + ", falling back to IAudioClient.");476CoTaskMemFree(pwfex);477return audio_device_init(p_device, p_input, p_reinit, true);478}479}480}481482if (p_input) {483hr = p_device->audio_client->GetService(IID_IAudioCaptureClient, (void **)&p_device->capture_client);484} else {485hr = p_device->audio_client->GetService(IID_IAudioRenderClient, (void **)&p_device->render_client);486}487if (unlikely(hr != S_OK)) {488CoTaskMemFree(pwfex);489ERR_FAIL_V(ERR_CANT_OPEN);490}491492// Free memory493CoTaskMemFree(pwfex);494495return OK;496}497498Error AudioDriverWASAPI::init_output_device(bool p_reinit) {499Error err = audio_device_init(&audio_output, false, p_reinit);500if (err != OK) {501// We've tried to init the device, but have failed. Time to clean up.502Error finish_err = finish_output_device();503if (finish_err != OK) {504ERR_PRINT("WASAPI: finish_output_device error after failed output audio_device_init");505}506return err;507}508509switch (audio_output.channels) {510case 1: // Mono511case 3: // Surround 2.1512case 5: // Surround 5.0513case 7: // Surround 7.0514// We will downmix as required.515channels = audio_output.channels + 1;516break;517518case 2: // Stereo519case 4: // Surround 3.1520case 6: // Surround 5.1521case 8: // Surround 7.1522channels = audio_output.channels;523break;524525default:526WARN_PRINT("WASAPI: Unsupported number of channels: " + itos(audio_output.channels));527channels = 2;528break;529}530531// Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)532samples_in.resize(buffer_frames * channels);533534input_position = 0;535input_size = 0;536537print_verbose("WASAPI: detected " + itos(audio_output.channels) + " channels");538print_verbose("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");539540return OK;541}542543Error AudioDriverWASAPI::init_input_device(bool p_reinit) {544Error err = audio_device_init(&audio_input, true, p_reinit);545if (err != OK) {546// We've tried to init the device, but have failed. Time to clean up.547Error finish_err = finish_input_device();548if (finish_err != OK) {549ERR_PRINT("WASAPI: finish_input_device error after failed input audio_device_init");550}551return err;552}553554// Get the max frames555UINT32 max_frames;556HRESULT hr = audio_input.audio_client->GetBufferSize(&max_frames);557ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);558559input_buffer_init(max_frames);560561return OK;562}563564Error AudioDriverWASAPI::audio_device_finish(AudioDeviceWASAPI *p_device) {565if (p_device->active.is_set()) {566if (p_device->audio_client) {567p_device->audio_client->Stop();568}569p_device->active.clear();570}571572SAFE_RELEASE(p_device->audio_client)573SAFE_RELEASE(p_device->render_client)574SAFE_RELEASE(p_device->capture_client)575576return OK;577}578579Error AudioDriverWASAPI::finish_output_device() {580return audio_device_finish(&audio_output);581}582583Error AudioDriverWASAPI::finish_input_device() {584return audio_device_finish(&audio_input);585}586587Error AudioDriverWASAPI::init() {588mix_rate = _get_configured_mix_rate();589590target_latency_ms = Engine::get_singleton()->get_audio_output_latency();591592exit_thread.clear();593594Error err = init_output_device();595ERR_FAIL_COND_V_MSG(err != OK, err, "WASAPI: init_output_device error.");596597thread.start(thread_func, this);598599return OK;600}601602int AudioDriverWASAPI::get_mix_rate() const {603return mix_rate;604}605606float AudioDriverWASAPI::get_latency() {607return real_latency;608}609610AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {611return get_speaker_mode_by_total_channels(channels);612}613614PackedStringArray AudioDriverWASAPI::audio_device_get_list(bool p_input) {615PackedStringArray list;616ComPtr<IMMDeviceCollection> devices = nullptr;617ComPtr<IMMDeviceEnumerator> enumerator = nullptr;618619list.push_back(String("Default"));620621HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);622ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());623624hr = enumerator->EnumAudioEndpoints(p_input ? eCapture : eRender, DEVICE_STATE_ACTIVE, &devices);625ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());626627UINT count = 0;628hr = devices->GetCount(&count);629ERR_FAIL_COND_V(hr != S_OK, PackedStringArray());630631for (ULONG i = 0; i < count; i++) {632ComPtr<IMMDevice> output_device = nullptr;633634hr = devices->Item(i, &output_device);635ERR_BREAK(hr != S_OK);636637ComPtr<IPropertyStore> props = nullptr;638hr = output_device->OpenPropertyStore(STGM_READ, &props);639ERR_BREAK(hr != S_OK);640641PROPVARIANT propvar;642PropVariantInit(&propvar);643644hr = props->GetValue(PKEY_Device_FriendlyNameGodot, &propvar);645ERR_BREAK(hr != S_OK);646647list.push_back(String(propvar.pwszVal));648649PropVariantClear(&propvar);650}651652return list;653}654655PackedStringArray AudioDriverWASAPI::get_output_device_list() {656return audio_device_get_list(false);657}658659String AudioDriverWASAPI::get_output_device() {660lock();661String name = audio_output.device_name;662unlock();663664return name;665}666667void AudioDriverWASAPI::set_output_device(const String &p_name) {668lock();669audio_output.new_device = p_name;670unlock();671}672673int32_t AudioDriverWASAPI::read_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i) {674if (format_tag == WAVE_FORMAT_PCM) {675int32_t sample = 0;676switch (bits_per_sample) {677case 8:678sample = int32_t(((int8_t *)buffer)[i]) << 24;679break;680681case 16:682sample = int32_t(((int16_t *)buffer)[i]) << 16;683break;684685case 24:686sample |= int32_t(((int8_t *)buffer)[i * 3 + 2]) << 24;687sample |= int32_t(((int8_t *)buffer)[i * 3 + 1]) << 16;688sample |= int32_t(((int8_t *)buffer)[i * 3 + 0]) << 8;689break;690691case 32:692sample = ((int32_t *)buffer)[i];693break;694}695696return sample;697} else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {698return int32_t(((float *)buffer)[i] * 32768.0) << 16;699} else {700ERR_PRINT("WASAPI: Unknown format tag");701}702703return 0;704}705706void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE *buffer, int i, int32_t sample) {707if (format_tag == WAVE_FORMAT_PCM) {708switch (bits_per_sample) {709case 8:710((int8_t *)buffer)[i] = sample >> 24;711break;712713case 16:714((int16_t *)buffer)[i] = sample >> 16;715break;716717case 24:718((int8_t *)buffer)[i * 3 + 2] = sample >> 24;719((int8_t *)buffer)[i * 3 + 1] = sample >> 16;720((int8_t *)buffer)[i * 3 + 0] = sample >> 8;721break;722723case 32:724((int32_t *)buffer)[i] = sample;725break;726}727} else if (format_tag == WAVE_FORMAT_IEEE_FLOAT) {728((float *)buffer)[i] = (sample >> 16) / 32768.f;729} else {730ERR_PRINT("WASAPI: Unknown format tag");731}732}733734void AudioDriverWASAPI::thread_func(void *p_udata) {735CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);736737AudioDriverWASAPI *ad = static_cast<AudioDriverWASAPI *>(p_udata);738uint32_t avail_frames = 0;739uint32_t write_ofs = 0;740741while (!ad->exit_thread.is_set()) {742uint32_t read_frames = 0;743uint32_t written_frames = 0;744745if (avail_frames == 0) {746ad->lock();747ad->start_counting_ticks();748749if (ad->audio_output.active.is_set()) {750ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());751} else {752for (int i = 0; i < ad->samples_in.size(); i++) {753ad->samples_in.write[i] = 0;754}755}756757avail_frames = ad->buffer_frames;758write_ofs = 0;759760ad->stop_counting_ticks();761ad->unlock();762}763764ad->lock();765ad->start_counting_ticks();766767if (avail_frames > 0 && ad->audio_output.audio_client) {768UINT32 buffer_size;769UINT32 cur_frames;770bool invalidated = false;771HRESULT hr = ad->audio_output.audio_client->GetBufferSize(&buffer_size);772if (hr != S_OK) {773ERR_PRINT("WASAPI: GetBufferSize error");774}775hr = ad->audio_output.audio_client->GetCurrentPadding(&cur_frames);776if (hr == S_OK) {777// Check how much frames are available on the WASAPI buffer778UINT32 write_frames = MIN(buffer_size - cur_frames, avail_frames);779if (write_frames > 0) {780BYTE *buffer = nullptr;781hr = ad->audio_output.render_client->GetBuffer(write_frames, &buffer);782if (hr == S_OK) {783// We're using WASAPI Shared Mode so we must convert the buffer784if (ad->channels == ad->audio_output.channels) {785for (unsigned int i = 0; i < write_frames * ad->channels; i++) {786ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i, ad->samples_in.write[write_ofs++]);787}788} else if (ad->channels == ad->audio_output.channels + 1) {789// Pass all channels except the last two as-is, and then mix the last two790// together as one channel. E.g. stereo -> mono, or 3.1 -> 2.1.791unsigned int last_chan = ad->audio_output.channels - 1;792for (unsigned int i = 0; i < write_frames; i++) {793for (unsigned int j = 0; j < last_chan; j++) {794ad->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++]);795}796int32_t l = ad->samples_in.write[write_ofs++];797int32_t r = ad->samples_in.write[write_ofs++];798int32_t c = (int32_t)(((int64_t)l + (int64_t)r) / 2);799ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + last_chan, c);800}801} else {802for (unsigned int i = 0; i < write_frames; i++) {803for (unsigned int j = 0; j < MIN(ad->channels, ad->audio_output.channels); j++) {804ad->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++]);805}806if (ad->audio_output.channels > ad->channels) {807for (unsigned int j = ad->channels; j < ad->audio_output.channels; j++) {808ad->write_sample(ad->audio_output.format_tag, ad->audio_output.bits_per_sample, buffer, i * ad->audio_output.channels + j, 0);809}810}811}812}813814hr = ad->audio_output.render_client->ReleaseBuffer(write_frames, 0);815if (hr != S_OK) {816ERR_PRINT("WASAPI: Release buffer error");817}818819avail_frames -= write_frames;820written_frames += write_frames;821} else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {822// output_device is not valid anymore, reopen it823824Error err = ad->finish_output_device();825if (err != OK) {826ERR_PRINT("WASAPI: finish_output_device error");827} else {828// We reopened the output device and samples_in may have resized, so invalidate the current avail_frames829avail_frames = 0;830}831} else {832ERR_PRINT("WASAPI: Get buffer error");833ad->exit_thread.set();834}835}836} else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {837invalidated = true;838} else {839ERR_PRINT("WASAPI: GetCurrentPadding error");840}841842if (invalidated) {843// output_device is not valid anymore844WARN_PRINT("WASAPI: Current output_device invalidated, closing output_device");845846Error err = ad->finish_output_device();847if (err != OK) {848ERR_PRINT("WASAPI: finish_output_device error");849}850}851}852853// If we're using the Default output device and it changed finish it so we'll re-init the output device854if (ad->audio_output.device_name == "Default" && default_output_device_changed) {855Error err = ad->finish_output_device();856if (err != OK) {857ERR_PRINT("WASAPI: finish_output_device error");858}859860default_output_device_changed = false;861}862863// User selected a new output device, finish the current one so we'll init the new output device864if (ad->audio_output.device_name != ad->audio_output.new_device) {865ad->audio_output.device_name = ad->audio_output.new_device;866Error err = ad->finish_output_device();867if (err != OK) {868ERR_PRINT("WASAPI: finish_output_device error");869}870}871872if (!ad->audio_output.audio_client) {873if (output_reinit_countdown < 1) {874Error err = ad->init_output_device(true);875if (err == OK) {876ad->start();877} else {878output_reinit_countdown = 1000;879}880} else {881output_reinit_countdown--;882}883884avail_frames = 0;885write_ofs = 0;886}887888if (ad->audio_input.active.is_set()) {889UINT32 packet_length = 0;890BYTE *data;891UINT32 num_frames_available;892DWORD flags;893894HRESULT hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);895if (hr == S_OK) {896while (packet_length != 0) {897hr = ad->audio_input.capture_client->GetBuffer(&data, &num_frames_available, &flags, nullptr, nullptr);898ERR_BREAK(hr != S_OK);899900// fixme: Only works for floating point atm901for (UINT32 j = 0; j < num_frames_available; j++) {902int32_t l, r;903904if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {905l = r = 0;906} else {907if (ad->audio_input.channels == 2) {908l = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2);909r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j * 2 + 1);910} else if (ad->audio_input.channels == 1) {911l = r = read_sample(ad->audio_input.format_tag, ad->audio_input.bits_per_sample, data, j);912} else {913l = r = 0;914ERR_PRINT("WASAPI: unsupported channel count in microphone!");915}916}917918ad->input_buffer_write(l);919ad->input_buffer_write(r);920}921922read_frames += num_frames_available;923924hr = ad->audio_input.capture_client->ReleaseBuffer(num_frames_available);925ERR_BREAK(hr != S_OK);926927hr = ad->audio_input.capture_client->GetNextPacketSize(&packet_length);928ERR_BREAK(hr != S_OK);929}930}931932// If we're using the Default output device and it changed finish it so we'll re-init the output device933if (ad->audio_input.device_name == "Default" && default_input_device_changed) {934Error err = ad->finish_input_device();935if (err != OK) {936ERR_PRINT("WASAPI: finish_input_device error");937}938939default_input_device_changed = false;940}941942// User selected a new input device, finish the current one so we'll init the new input device943if (ad->audio_input.device_name != ad->audio_input.new_device) {944ad->audio_input.device_name = ad->audio_input.new_device;945Error err = ad->finish_input_device();946if (err != OK) {947ERR_PRINT("WASAPI: finish_input_device error");948}949}950951if (!ad->audio_input.audio_client) {952if (input_reinit_countdown < 1) {953Error err = ad->init_input_device(true);954if (err == OK) {955ad->input_start();956} else {957input_reinit_countdown = 1000;958}959} else {960input_reinit_countdown--;961}962}963}964965ad->stop_counting_ticks();966ad->unlock();967968// Let the thread rest a while if we haven't read or write anything969if (written_frames == 0 && read_frames == 0) {970OS::get_singleton()->delay_usec(1000);971}972}973CoUninitialize();974}975976void AudioDriverWASAPI::start() {977if (audio_output.audio_client) {978HRESULT hr = audio_output.audio_client->Start();979if (hr != S_OK) {980ERR_PRINT("WASAPI: Start failed");981} else {982audio_output.active.set();983}984}985}986987void AudioDriverWASAPI::lock() {988mutex.lock();989}990991void AudioDriverWASAPI::unlock() {992mutex.unlock();993}994995void AudioDriverWASAPI::finish() {996exit_thread.set();997if (thread.is_started()) {998thread.wait_to_finish();999}10001001finish_input_device();1002finish_output_device();1003}10041005Error AudioDriverWASAPI::input_start() {1006Error err = init_input_device();1007if (err != OK) {1008ERR_PRINT("WASAPI: init_input_device error");1009return err;1010}10111012if (audio_input.active.is_set()) {1013return FAILED;1014}10151016audio_input.audio_client->Start();1017audio_input.active.set();1018return OK;1019}10201021Error AudioDriverWASAPI::input_stop() {1022if (audio_input.active.is_set()) {1023audio_input.audio_client->Stop();1024audio_input.active.clear();10251026return OK;1027}10281029return FAILED;1030}10311032PackedStringArray AudioDriverWASAPI::get_input_device_list() {1033return audio_device_get_list(true);1034}10351036String AudioDriverWASAPI::get_input_device() {1037lock();1038String name = audio_input.device_name;1039unlock();10401041return name;1042}10431044void AudioDriverWASAPI::set_input_device(const String &p_name) {1045lock();1046audio_input.new_device = p_name;1047unlock();1048}10491050AudioDriverWASAPI::AudioDriverWASAPI() {1051samples_in.clear();1052}10531054#endif // WASAPI_ENABLED105510561057