From d4ce33ed42ea69487b47c609d12a2d62db53313f Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 00:05:32 -0500 Subject: [PATCH 1/2] runtime: serve a silent output endpoint when the host has none The title creates its MMDeviceEnumerator through CoCreateInstance. On a host with no render endpoint, GetDefaultAudioEndpoint(eRender) is 0x80070490, the title's audio device start leaves its own output-device lock held, the audio engine never mixes, and the boot stops on an int3 about 47 s in. A console always has an output. com_shim's CoCreateInstance now hands that class to shims/silent_audio.cpp. A host enumerator with a default render endpoint is returned unchanged. Otherwise (no endpoint, no enumerator, or LEONIDA_AUDIO=silent) render questions get an in-process endpoint: IMMDevice with a read-only property store, IAudioClient/2/3 at 48 kHz float 7.1, and IAudioRenderClient, IAudioClock, ISimpleAudioVolume and IAudioStreamVolume. A clock drains the padding in real time and an event-driven stream's event is signalled every 10 ms. Every sample is discarded; no host audio device is opened. Capture keeps the host's answer. One [rt] line names the reason when the silent device is first served. silent_audio_test covers stand-in hosts with and without an endpoint, no host, a render stream over a few periods, and the CoCreateInstance hook with LEONIDA_AUDIO=silent. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 33 + runtime/CMakeLists.txt | 18 + runtime/README.md | 1 + runtime/shims/com_shim.cpp | 8 +- runtime/shims/silent_audio.cpp | 941 +++++++++++++++++++++++++++++ runtime/shims/silent_audio.h | 60 ++ runtime/test/silent_audio_test.cpp | 585 ++++++++++++++++++ scripts/build_runtime.ps1 | 2 +- 8 files changed, 1646 insertions(+), 2 deletions(-) create mode 100644 runtime/shims/silent_audio.cpp create mode 100644 runtime/shims/silent_audio.h create mode 100644 runtime/test/silent_audio_test.cpp diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 9c1b28c7b..c1366c1b5 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -228,6 +228,39 @@ calls succeed and do nothing: there is no audio processor, so the game gets no s fail hard, which is why every call succeeds. `acphal_test` covers the call shapes. The table under [The retail executable](#the-retail-executable-rt-5) was measured before this shim and still lists these nine as unimplemented; they are served now. +## Audio output off the console (WASAPI) + +Off the console the title's sound goes out through WASAPI, not through the `AcpHal` path above: it creates an +`MMDeviceEnumerator` with `CoCreateInstance` (one call, `CLSCTX_ALL`, `IID_IMMDeviceEnumerator`), asks it for the +default render endpoint and activates an `IAudioClient` on it. A console always has an output. A host with none +answers `GetDefaultAudioEndpoint(eRender, ...)` with `0x80070490` (`ERROR_NOT_FOUND`), and the title's device start +then takes an error path that leaves its own output-device lock held by a job worker: the audio engine never mixes, a +main-thread command buffer fills up, and the title stops on an `int3` about 47 s into the boot (measured under Wine with +its audio drivers disabled; refusing the enumerator itself stops it the same way, and a host null sink removes the stop). + +So `CoCreateInstance` of that class goes to `runtime/shims/silent_audio.cpp` (hooked in `shims/com_shim.cpp`). When +the host's enumerator has a default render endpoint it is returned unchanged. When it has none, or cannot be made, or +`LEONIDA_AUDIO=silent` is set, the title gets an enumerator whose render answers are a **silent output endpoint** of the +runtime's own: `GetDefaultAudioEndpoint(eRender)`, `EnumAudioEndpoints(eRender)` (active devices) and `GetDevice` with +its ID give an active `IMMDevice` whose property store has a friendly name and the device format; `Activate` gives an +`IAudioClient`, `IAudioClient2` or `IAudioClient3` (any other interface is `E_NOINTERFACE`, logged once). The client +takes any PCM or float format in shared mode (event-driven or polled), and `GetService` gives `IAudioRenderClient` +(a scratch buffer), `IAudioClock`, `ISimpleAudioVolume` and `IAudioStreamVolume`. A clock consumes the written frames +in real time, so `GetCurrentPadding` drains, and an event-driven stream's event is signalled every 10 ms period +while it runs, so a title that paces its mixer on the event keeps running. Capture questions keep the host's answer +(with `LEONIDA_AUDIO=silent` the host's enumerator is only made when one comes). Endpoint notification callbacks are +accepted and never called. Nothing opens or touches a host audio device, and every sample is discarded. The first +silent device handed out prints one `[rt] audio: serving the silent output endpoint ()` line, the reason being +the host's failed call or `LEONIDA_AUDIO=silent`. + +The mix format is 48 kHz, 32-bit float, 7.1 (eight channels, mask `0x63F`). 48 kHz float is the shared-mode +format of the Windows audio engine and of the console's. 7.1 is the console's case, and a hypothesis, not measured +here: the console's system mixer takes a 7.1 bed whatever output is plugged in and downmixes it for stereo, so a +console title is built for eight channels, where stereo would be the usual answer of a PC with headphones. The stream +itself takes any channel count, so a title that asks for fewer is not refused. `silent_audio_test` +covers the enumerator over stand-in hosts with and without an endpoint and with none, a render stream run for a +few periods with its event and padding checked, and the `CoCreateInstance` hook with `LEONIDA_AUDIO=silent`. + ## Console paths and the write overlay A title's file calls name the console's drives, so `GAME:\data\x.sps` is a file inside the installed game folder. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 48c8af360..2763e9d1b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -196,6 +196,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/library_loader.cpp shims/process.cpp shims/com_shim.cpp + shims/silent_audio.cpp shims/bcrypt_rng.cpp shims/xapu_chad.cpp shims/dstorage.cpp @@ -460,6 +461,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) add_executable(com_shim_test test/com_shim_test.cpp shims/com_shim.cpp + shims/silent_audio.cpp shims/registry.cpp ) target_include_directories(com_shim_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) @@ -467,6 +469,19 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(com_shim_test PRIVATE /W4 /permissive- /utf-8) target_link_options(com_shim_test PRIVATE /OPT:NOREF) + # The silent output endpoint (MMDeviceEnumerator through CoCreateInstance): stand-in hosts, a render stream on + # its clock, and the CoCreateInstance hook with LEONIDA_AUDIO=silent. No host audio device is opened. + add_executable(silent_audio_test + test/silent_audio_test.cpp + shims/silent_audio.cpp + shims/com_shim.cpp + shims/registry.cpp + ) + target_include_directories(silent_audio_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(silent_audio_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(silent_audio_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(silent_audio_test PRIVATE /OPT:NOREF) + # BCrypt RNG and algorithm provider shims. add_executable(bcrypt_rng_test test/bcrypt_rng_test.cpp @@ -1504,6 +1519,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET com_shim_test) add_test(NAME com_shim COMMAND com_shim_test) endif() + if(WIN32 AND TARGET silent_audio_test) + add_test(NAME silent_audio COMMAND silent_audio_test) + endif() if(WIN32 AND TARGET bcrypt_rng_test) add_test(NAME bcrypt_rng COMMAND bcrypt_rng_test) add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded) diff --git a/runtime/README.md b/runtime/README.md index fadaa47ef..aa9b2d308 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -358,6 +358,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. | | `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. | | `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | +| `LEONIDA_AUDIO` | unset | `silent` (any case) makes the title's `MMDeviceEnumerator` answer every render question with the runtime's silent output endpoint, even on a host that has an output (`shims/silent_audio.cpp`, read at each `CoCreateInstance`): no host audio device is opened and every sample is thrown away, for muted test runs. Unset, or any other value, the host's endpoint answers when there is one and the silent endpoint only when the host has none. Capture keeps the host's answer either way. See [docs/runtime_imports.md](../docs/runtime_imports.md#audio-output-off-the-console-wasapi). | The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own diff --git a/runtime/shims/com_shim.cpp b/runtime/shims/com_shim.cpp index 55962e215..8156b1917 100644 --- a/runtime/shims/com_shim.cpp +++ b/runtime/shims/com_shim.cpp @@ -1,7 +1,8 @@ // COM lifecycle and helper shims for api-ms-win-core-com-l1-1-0..3.dll. // // game_scarlett_master.exe imports CoInitializeEx, CoUninitialize, CoCreateInstance, CoCreateGuid, CoTaskMemFree, -// PropVariantClear, and StringFromGUID2 through api-ms-win-core-com-l1-1-0.dll. When the host (or a host library) has +// PropVariantClear, and StringFromGUID2 through api-ms-win-core-com-l1-1-0.dll. CoCreateInstance of the +// MMDeviceEnumerator goes to silent_audio.cpp, which serves a silent output endpoint when the host has none. When the host (or a host library) has // already initialized a thread as STA, a guest call to CoInitializeEx(nullptr, COINIT_MULTITHREADED) fails with // RPC_E_CHANGED_MODE (0x80010106) and an unbalanced CoUninitialize can tear down host COM early. // @@ -15,6 +16,7 @@ #include #include "shims.h" +#include "silent_audio.h" namespace rt::com_shim { namespace { @@ -128,6 +130,10 @@ void WINAPI co_uninitialize() { HRESULT WINAPI co_create_instance(REFCLSID rclsid, LPUNKNOWN outer, DWORD cls_context, REFIID riid, LPVOID* ppv) { if (!ppv) return E_POINTER; *ppv = nullptr; + // The audio device enumerator: the host's when it has an output, else (or with LEONIDA_AUDIO=silent) one that + // also answers with the silent output endpoint (silent_audio.h). + if (!outer && IsEqualCLSID(rclsid, rt::silent_audio::kClsidMMDeviceEnumerator)) + return rt::silent_audio::create_enumerator(cls_context, riid, ppv); return ::CoCreateInstance(rclsid, outer, cls_context, riid, ppv); } diff --git a/runtime/shims/silent_audio.cpp b/runtime/shims/silent_audio.cpp new file mode 100644 index 000000000..d6b650d27 --- /dev/null +++ b/runtime/shims/silent_audio.cpp @@ -0,0 +1,941 @@ +// The silent output endpoint (silent_audio.h): IMMDeviceEnumerator, IMMDevice, IPropertyStore, IAudioClient3 and its +// services, all in-process. Nothing here opens a host audio device; the samples a title writes go to a scratch buffer. +// +// No function-local statics or thread_local here: like com_shim.cpp, this runs on threads the title made. +#include "silent_audio.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace rt::silent_audio { +namespace { + +constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); // 0x80070490 + +// KSDATAFORMAT_SUBTYPE_IEEE_FLOAT and KSDATAFORMAT_SUBTYPE_PCM. +constexpr GUID kSubtypeFloat{0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; +constexpr GUID kSubtypePcm{0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + +// Property keys (functiondiscoverykeys_devpkey.h, mmdeviceapi.h), spelled out so no INITGUID unit is needed. +constexpr GUID kDeviceFmtid{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}; +constexpr GUID kInterfaceFmtid{0x026e516e, 0xb814, 0x414b, {0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22}}; +constexpr GUID kEngineFmtid{0xf19f064d, 0x082c, 0x4e27, {0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c}}; +constexpr GUID kOemFmtid{0xe4870e26, 0x3cc5, 0x4cd2, {0xba, 0x46, 0xca, 0x0a, 0x9a, 0x70, 0xed, 0x04}}; +constexpr GUID kEndpointFmtid{0x1da5d803, 0xd492, 0x4edd, {0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e}}; +constexpr PROPERTYKEY kKeyFriendlyName{kDeviceFmtid, 14}; // PKEY_Device_FriendlyName +constexpr PROPERTYKEY kKeyDeviceDesc{kDeviceFmtid, 2}; // PKEY_Device_DeviceDesc +constexpr PROPERTYKEY kKeyInterfaceName{kInterfaceFmtid, 2}; // PKEY_DeviceInterface_FriendlyName +constexpr PROPERTYKEY kKeyDeviceFormat{kEngineFmtid, 0}; // PKEY_AudioEngine_DeviceFormat +constexpr PROPERTYKEY kKeyOemFormat{kOemFmtid, 3}; // PKEY_AudioEngine_OEMFormat +constexpr PROPERTYKEY kKeyFormFactor{kEndpointFmtid, 0}; // PKEY_AudioEndpoint_FormFactor +constexpr PROPERTYKEY kKeyPhysicalSpeakers{kEndpointFmtid, 3}; // PKEY_AudioEndpoint_PhysicalSpeakers +constexpr PROPERTYKEY kKeyEndpointGuid{kEndpointFmtid, 4}; // PKEY_AudioEndpoint_GUID +constexpr PROPERTYKEY kKeys[] = {kKeyFriendlyName, kKeyDeviceDesc, kKeyInterfaceName, kKeyDeviceFormat, + kKeyOemFormat, kKeyFormFactor, kKeyPhysicalSpeakers, kKeyEndpointGuid}; +constexpr uint32_t kFormFactorSpeakers = 1; +constexpr wchar_t kEndpointGuid[] = L"{5a4c2a5e-1e0d-4c1b-9a51-6c656f6e6964}"; + +constexpr uint32_t kMaxChannels = 32; + +LONG g_served = 0; +LONG g_logged = 0; +SRWLOCK g_iid_lock = SRWLOCK_INIT; +GUID g_iids_logged[16]{}; +uint32_t g_iid_count = 0; + +bool same_key(const PROPERTYKEY& a, const PROPERTYKEY& b) { + return a.pid == b.pid && IsEqualGUID(a.fmtid, b.fmtid); +} + +// One [rt] line per interface the silent endpoint does not have. +void log_missing_iid_once(const char* where, REFIID riid) { + AcquireSRWLockExclusive(&g_iid_lock); + bool seen = false; + for (uint32_t i = 0; i < g_iid_count; ++i) seen = seen || IsEqualGUID(g_iids_logged[i], riid); + if (!seen && g_iid_count < 16) g_iids_logged[g_iid_count++] = riid; + ReleaseSRWLockExclusive(&g_iid_lock); + if (seen) return; + wchar_t text[64]{}; + StringFromGUID2(riid, text, 64); + std::fprintf(stderr, "[rt] audio: the silent output endpoint has no %ls (%s); E_NOINTERFACE\n", text, where); +} + +void note_served(const char* reason) { + InterlockedIncrement(&g_served); + if (InterlockedExchange(&g_logged, 1) == 0) { + std::fprintf(stderr, + "[rt] audio: serving the silent output endpoint (%s): 48 kHz float 7.1, every sample discarded, " + "no host audio device opened\n", + reason); + } +} + +void mix_format(WAVEFORMATEXTENSIBLE* f) { + std::memset(f, 0, sizeof *f); + f->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + f->Format.nChannels = kChannels; + f->Format.nSamplesPerSec = kSampleRate; + f->Format.wBitsPerSample = 32; + f->Format.nBlockAlign = static_cast(kChannels * 4); + f->Format.nAvgBytesPerSec = kSampleRate * kChannels * 4; + f->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); + f->Samples.wValidBitsPerSample = 32; + f->dwChannelMask = kChannelMask; + f->SubFormat = kSubtypeFloat; +} + +WAVEFORMATEX* alloc_mix_format() { + auto* f = static_cast(CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE))); + if (f) mix_format(f); + return reinterpret_cast(f); +} + +bool is_float(const WAVEFORMATEX* f) { + if (f->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) return true; + return f->wFormatTag == WAVE_FORMAT_EXTENSIBLE && f->cbSize >= 22 && + IsEqualGUID(reinterpret_cast(f)->SubFormat, kSubtypeFloat); +} + +// A format a shared-mode stream could carry: PCM or float, 1..32 channels, 8..384 kHz, a consistent block. +bool valid_format(const WAVEFORMATEX* f) { + if (f->nChannels == 0 || f->nChannels > kMaxChannels) return false; + if (f->nSamplesPerSec < 8000 || f->nSamplesPerSec > 384000) return false; + if (f->wBitsPerSample == 0 || f->wBitsPerSample % 8 != 0 || f->wBitsPerSample > 64) return false; + if (f->nBlockAlign != f->nChannels * (f->wBitsPerSample / 8)) return false; + if (f->wFormatTag == WAVE_FORMAT_PCM || f->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) return true; + if (f->wFormatTag != WAVE_FORMAT_EXTENSIBLE || f->cbSize < 22) return false; + const GUID& sub = reinterpret_cast(f)->SubFormat; + return IsEqualGUID(sub, kSubtypeFloat) || IsEqualGUID(sub, kSubtypePcm); +} + +bool is_mix_format(const WAVEFORMATEX* f) { + return f->nSamplesPerSec == kSampleRate && f->nChannels == kChannels && f->wBitsPerSample == 32 && is_float(f); +} + +int64_t qpc_now() { + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} + +int64_t qpc_frequency() { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return f.QuadPart; +} + +wchar_t* co_task_string(const wchar_t* s) { + const size_t n = std::wcslen(s) + 1; + auto* out = static_cast(CoTaskMemAlloc(n * sizeof(wchar_t))); + if (out) std::wmemcpy(out, s, n); + return out; +} + +// IUnknown for an object with one interface. +template +class Unknown : public Iface { +public: + ULONG STDMETHODCALLTYPE AddRef() override { return static_cast(InterlockedIncrement(&refs_)); } + ULONG STDMETHODCALLTYPE Release() override { + const LONG n = InterlockedDecrement(&refs_); + if (n == 0) delete this; + return static_cast(n); + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!IsEqualIID(riid, __uuidof(IUnknown)) && !answers(riid)) return E_NOINTERFACE; + *ppv = static_cast(this); + AddRef(); + return S_OK; + } + +protected: + virtual ~Unknown() = default; + virtual bool answers(REFIID riid) const { return IsEqualIID(riid, __uuidof(Iface)); } + +private: + LONG refs_ = 1; +}; + +// ---- IAudioClient3 -------------------------------------------------------------------------------------------- + +class AudioClient final : public Unknown { +public: + // IAudioClient + HRESULT STDMETHODCALLTYPE Initialize(AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME buffer_hns, + REFERENCE_TIME, const WAVEFORMATEX* format, LPCGUID) override { + return init(mode, flags, buffer_hns, 0, format); + } + HRESULT STDMETHODCALLTYPE GetBufferSize(UINT32* frames) override { + if (!frames) return E_POINTER; + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + *frames = buffer_frames_; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetStreamLatency(REFERENCE_TIME* latency) override { + if (!latency) return E_POINTER; + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + *latency = kDefaultPeriodHns; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetCurrentPadding(UINT32* padding) override { + if (!padding) return E_POINTER; + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + advance(qpc_now()); + *padding = static_cast(written_ - played_); + return S_OK; + } + HRESULT STDMETHODCALLTYPE IsFormatSupported(AUDCLNT_SHAREMODE mode, const WAVEFORMATEX* format, + WAVEFORMATEX** closest) override { + if (closest) *closest = nullptr; + if (!format) return E_POINTER; + if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE) return AUDCLNT_E_UNSUPPORTED_FORMAT; + if (mode != AUDCLNT_SHAREMODE_SHARED) return E_INVALIDARG; + if (!closest) return E_POINTER; + if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT; + if (is_mix_format(format)) return S_OK; + *closest = alloc_mix_format(); + return *closest ? S_FALSE : E_OUTOFMEMORY; + } + HRESULT STDMETHODCALLTYPE GetMixFormat(WAVEFORMATEX** format) override { + if (!format) return E_POINTER; + *format = alloc_mix_format(); + return *format ? S_OK : E_OUTOFMEMORY; + } + HRESULT STDMETHODCALLTYPE GetDevicePeriod(REFERENCE_TIME* default_period, REFERENCE_TIME* minimum) override { + if (!default_period && !minimum) return E_POINTER; + if (default_period) *default_period = kDefaultPeriodHns; + if (minimum) *minimum = kMinimumPeriodHns; + return S_OK; + } + HRESULT STDMETHODCALLTYPE Start() override { + HANDLE signal = nullptr; + { + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + if (running_) return AUDCLNT_E_NOT_STOPPED; + if (event_mode_ && !event_) return AUDCLNT_E_EVENTHANDLE_NOT_SET; + anchor_qpc_ = qpc_now(); + played_at_anchor_ = played_; + running_ = true; + signal = event_; + } + if (signal) SetEvent(signal); + return S_OK; + } + HRESULT STDMETHODCALLTYPE Stop() override { + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + if (!running_) return S_FALSE; + advance(qpc_now()); + running_ = false; + return S_OK; + } + HRESULT STDMETHODCALLTYPE Reset() override { + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + if (running_) return AUDCLNT_E_NOT_STOPPED; + if (pending_) return AUDCLNT_E_BUFFER_OPERATION_PENDING; + if (written_ == 0 && played_ == 0) return S_FALSE; + written_ = played_ = played_at_anchor_ = 0; + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetEventHandle(HANDLE event) override { + if (!event || event == INVALID_HANDLE_VALUE) return E_INVALIDARG; + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + if (!event_mode_) return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED; + event_ = event; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetService(REFIID riid, void** ppv) override; + + // IAudioClient2 + HRESULT STDMETHODCALLTYPE IsOffloadCapable(AUDIO_STREAM_CATEGORY, BOOL* capable) override { + if (!capable) return E_POINTER; + *capable = FALSE; + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetClientProperties(const AudioClientProperties* properties) override { + if (!properties) return E_POINTER; + Lock l(lock_); + return initialized_ ? AUDCLNT_E_ALREADY_INITIALIZED : S_OK; + } + HRESULT STDMETHODCALLTYPE GetBufferSizeLimits(const WAVEFORMATEX* format, BOOL, REFERENCE_TIME* min_hns, + REFERENCE_TIME* max_hns) override { + if (!format || !min_hns || !max_hns) return E_POINTER; + if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT; + *min_hns = kDefaultPeriodHns; + *max_hns = 20000000; // 2 s + return S_OK; + } + + // IAudioClient3: one engine period only, 10 ms. + HRESULT STDMETHODCALLTYPE GetSharedModeEnginePeriod(const WAVEFORMATEX* format, UINT32* default_frames, + UINT32* fundamental, UINT32* min_frames, + UINT32* max_frames) override { + if (!format || !default_frames || !fundamental || !min_frames || !max_frames) return E_POINTER; + if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT; + const UINT32 period = static_cast(format->nSamplesPerSec / 100); + *default_frames = *fundamental = *min_frames = *max_frames = period; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetCurrentSharedModeEnginePeriod(WAVEFORMATEX** format, UINT32* frames) override { + if (!format || !frames) return E_POINTER; + *format = alloc_mix_format(); + if (!*format) return E_OUTOFMEMORY; + *frames = kSampleRate / 100; + return S_OK; + } + HRESULT STDMETHODCALLTYPE InitializeSharedAudioStream(DWORD flags, UINT32 period_frames, + const WAVEFORMATEX* format, LPCGUID) override { + if (!format) return E_POINTER; + const REFERENCE_TIME hns = format->nSamplesPerSec + ? static_cast(period_frames) * 10000000 / format->nSamplesPerSec + : 0; + return init(AUDCLNT_SHAREMODE_SHARED, flags, 0, hns, format); + } + + // For the services. + HRESULT get_buffer(UINT32 frames, BYTE** data) { + if (!data) return E_POINTER; + *data = nullptr; + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + if (pending_) return AUDCLNT_E_OUT_OF_ORDER; + advance(qpc_now()); + const uint64_t padding = written_ - played_; + if (frames > buffer_frames_ - padding) return AUDCLNT_E_BUFFER_TOO_LARGE; + pending_ = true; + pending_frames_ = frames; + *data = frames ? scratch_.data() : nullptr; + return S_OK; + } + HRESULT release_buffer(UINT32 frames) { + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + if (!pending_) return frames ? AUDCLNT_E_OUT_OF_ORDER : S_OK; + if (frames > pending_frames_) return AUDCLNT_E_INVALID_SIZE; + // A write after the stream ran dry plays from now on (advance re-anchors), as a device fed silence in the gap. + advance(qpc_now()); + written_ += frames; + pending_ = false; + pending_frames_ = 0; + return S_OK; + } + void position(UINT64* frames, UINT64* qpc_hns) { + Lock l(lock_); + const int64_t now = qpc_now(); + advance(now); + *frames = played_; + if (qpc_hns) { + const int64_t f = qpc_frequency(); + *qpc_hns = static_cast((now / f) * 10000000 + (now % f) * 10000000 / f); + } + } + uint32_t rate() const { return rate_; } + uint32_t channels() const { return channels_; } + float volume(uint32_t i) { + Lock l(lock_); + return i < kMaxChannels ? channel_volume_[i] : 0.0f; + } + void set_volume(uint32_t i, float v) { + Lock l(lock_); + if (i < kMaxChannels) channel_volume_[i] = v; + } + float master_ = 1.0f; + BOOL mute_ = FALSE; + +private: + struct Lock { + explicit Lock(SRWLOCK& s) : s_(s) { AcquireSRWLockExclusive(&s_); } + ~Lock() { ReleaseSRWLockExclusive(&s_); } + SRWLOCK& s_; + }; + + ~AudioClient() override { + if (thread_) { + SetEvent(stop_); + WaitForSingleObject(thread_, INFINITE); + CloseHandle(thread_); + } + if (stop_) CloseHandle(stop_); + } + + bool answers(REFIID riid) const override { + return IsEqualIID(riid, __uuidof(IAudioClient)) || IsEqualIID(riid, __uuidof(IAudioClient2)) || + IsEqualIID(riid, __uuidof(IAudioClient3)); + } + + HRESULT init(AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME buffer_hns, REFERENCE_TIME period_hns, + const WAVEFORMATEX* format) { + if (!format) return E_POINTER; + if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE) return AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED; + if (mode != AUDCLNT_SHAREMODE_SHARED) return E_INVALIDARG; + if (flags & AUDCLNT_STREAMFLAGS_LOOPBACK) return AUDCLNT_E_WRONG_ENDPOINT_TYPE; + // Any PCM or float format is taken, not only the mix format: the samples are thrown away, so there is + // nothing to convert, and a title never fails here for asking without AUTOCONVERTPCM. + if (!valid_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT; + Lock l(lock_); + if (initialized_) return AUDCLNT_E_ALREADY_INITIALIZED; + rate_ = format->nSamplesPerSec; + channels_ = format->nChannels; + block_ = format->nBlockAlign; + period_hns_ = period_hns > 0 ? period_hns : kDefaultPeriodHns; + const REFERENCE_TIME hns = buffer_hns > 2 * period_hns_ ? buffer_hns : 2 * period_hns_; + buffer_frames_ = static_cast((hns * rate_ + 9999999) / 10000000); + scratch_.assign(static_cast(buffer_frames_) * block_, 0); + for (float& v : channel_volume_) v = 1.0f; + event_mode_ = (flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) != 0; + if (event_mode_) { + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + thread_ = stop_ ? CreateThread(nullptr, 64 * 1024, &AudioClient::clock_thread, this, 0, nullptr) : nullptr; + if (!thread_) return E_OUTOFMEMORY; + } + initialized_ = true; + if (InterlockedExchange(&g_stream_logged, 1) == 0) { + std::fprintf(stderr, "[rt] audio: silent stream: %u ch, %u Hz, %u-byte frames, %u-frame buffer, %s\n", + channels_, rate_, block_, buffer_frames_, event_mode_ ? "event-driven" : "polled"); + } + return S_OK; + } + + // Frames the device has consumed since Start, at the stream's rate, clamped to what was written. + void advance(int64_t now) { + if (!running_) return; + const int64_t f = qpc_frequency(); + const int64_t elapsed = now > anchor_qpc_ ? now - anchor_qpc_ : 0; + const uint64_t frames = static_cast((elapsed / f) * rate_ + (elapsed % f) * rate_ / f); + const uint64_t candidate = played_at_anchor_ + frames; + if (candidate >= written_) { + // Ran dry: the device plays silence until more is written. + played_ = written_; + anchor_qpc_ = now; + played_at_anchor_ = written_; + } else { + played_ = candidate; + } + } + + void tick() { + HANDLE signal = nullptr; + { + Lock l(lock_); + if (!running_) return; + advance(qpc_now()); + signal = event_; + } + if (signal) SetEvent(signal); + } + + static DWORD WINAPI clock_thread(void* self) { + auto* c = static_cast(self); + const DWORD period_ms = static_cast((c->period_hns_ + 9999) / 10000); + // A fixed schedule, so a late wake-up does not push the next ones back. + const int64_t f = qpc_frequency(); + const int64_t step = c->period_hns_ * f / 10000000; + int64_t next = qpc_now() + step; + for (;;) { + const int64_t now = qpc_now(); + DWORD wait = 0; + if (next > now) { + wait = static_cast((next - now) * 1000 / f); + if (wait > period_ms) wait = period_ms; + } + if (WaitForSingleObject(c->stop_, wait) != WAIT_TIMEOUT) break; + if (qpc_now() < next) continue; + next += step; + if (next < qpc_now()) next = qpc_now() + step; + c->tick(); + } + return 0; + } + + static inline LONG g_stream_logged = 0; + + SRWLOCK lock_ = SRWLOCK_INIT; + bool initialized_ = false; + bool event_mode_ = false; + bool running_ = false; + bool pending_ = false; + uint32_t pending_frames_ = 0; + uint32_t rate_ = kSampleRate; + uint32_t channels_ = kChannels; + uint32_t block_ = kChannels * 4; + uint32_t buffer_frames_ = 0; + REFERENCE_TIME period_hns_ = kDefaultPeriodHns; + std::vector scratch_; + HANDLE event_ = nullptr; // the title's; not owned + HANDLE stop_ = nullptr; + HANDLE thread_ = nullptr; + uint64_t written_ = 0; + uint64_t played_ = 0; + uint64_t played_at_anchor_ = 0; + int64_t anchor_qpc_ = 0; + float channel_volume_[kMaxChannels]{}; +}; + +// The services hold their client. +template +class Service : public Unknown { +public: + explicit Service(AudioClient* client) : client_(client) { client_->AddRef(); } + +protected: + ~Service() override { client_->Release(); } + AudioClient* client_; +}; + +class RenderClient final : public Service { +public: + using Service::Service; + HRESULT STDMETHODCALLTYPE GetBuffer(UINT32 frames, BYTE** data) override { return client_->get_buffer(frames, data); } + HRESULT STDMETHODCALLTYPE ReleaseBuffer(UINT32 frames, DWORD) override { return client_->release_buffer(frames); } +}; + +class Clock final : public Service { +public: + using Service::Service; + HRESULT STDMETHODCALLTYPE GetFrequency(UINT64* frequency) override { + if (!frequency) return E_POINTER; + *frequency = client_->rate(); // the position counts frames + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetPosition(UINT64* position, UINT64* qpc_hns) override { + if (!position) return E_POINTER; + client_->position(position, qpc_hns); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetCharacteristics(DWORD* characteristics) override { + if (!characteristics) return E_POINTER; + *characteristics = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ; + return S_OK; + } +}; + +class SimpleVolume final : public Service { +public: + using Service::Service; + HRESULT STDMETHODCALLTYPE SetMasterVolume(float level, LPCGUID) override { + if (level < 0.0f || level > 1.0f) return E_INVALIDARG; + client_->master_ = level; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetMasterVolume(float* level) override { + if (!level) return E_POINTER; + *level = client_->master_; + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetMute(BOOL mute, LPCGUID) override { + client_->mute_ = mute; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetMute(BOOL* mute) override { + if (!mute) return E_POINTER; + *mute = client_->mute_; + return S_OK; + } +}; + +class StreamVolume final : public Service { +public: + using Service::Service; + HRESULT STDMETHODCALLTYPE GetChannelCount(UINT32* count) override { + if (!count) return E_POINTER; + *count = client_->channels(); + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetChannelVolume(UINT32 index, const float level) override { + if (index >= client_->channels() || level < 0.0f || level > 1.0f) return E_INVALIDARG; + client_->set_volume(index, level); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetChannelVolume(UINT32 index, float* level) override { + if (!level) return E_POINTER; + if (index >= client_->channels()) return E_INVALIDARG; + *level = client_->volume(index); + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetAllVolumes(UINT32 count, const float* levels) override { + if (!levels) return E_POINTER; + if (count != client_->channels()) return E_INVALIDARG; + for (UINT32 i = 0; i < count; ++i) { + if (levels[i] < 0.0f || levels[i] > 1.0f) return E_INVALIDARG; + } + for (UINT32 i = 0; i < count; ++i) client_->set_volume(i, levels[i]); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetAllVolumes(UINT32 count, float* levels) override { + if (!levels) return E_POINTER; + if (count != client_->channels()) return E_INVALIDARG; + for (UINT32 i = 0; i < count; ++i) levels[i] = client_->volume(i); + return S_OK; + } +}; + +HRESULT AudioClient::GetService(REFIID riid, void** ppv) { + if (!ppv) return E_POINTER; + *ppv = nullptr; + { + Lock l(lock_); + if (!initialized_) return AUDCLNT_E_NOT_INITIALIZED; + } + IUnknown* made = nullptr; + if (IsEqualIID(riid, __uuidof(IAudioRenderClient))) made = new (std::nothrow) RenderClient(this); + else if (IsEqualIID(riid, __uuidof(IAudioClock))) made = new (std::nothrow) Clock(this); + else if (IsEqualIID(riid, __uuidof(ISimpleAudioVolume))) made = new (std::nothrow) SimpleVolume(this); + else if (IsEqualIID(riid, __uuidof(IAudioStreamVolume))) made = new (std::nothrow) StreamVolume(this); + else { + log_missing_iid_once("IAudioClient::GetService", riid); + return E_NOINTERFACE; + } + if (!made) return E_OUTOFMEMORY; + const HRESULT hr = made->QueryInterface(riid, ppv); + made->Release(); + return hr; +} + +// ---- IPropertyStore ------------------------------------------------------------------------------------------- + +class PropertyStore final : public Unknown { +public: + HRESULT STDMETHODCALLTYPE GetCount(DWORD* count) override { + if (!count) return E_POINTER; + *count = static_cast(sizeof kKeys / sizeof kKeys[0]); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetAt(DWORD index, PROPERTYKEY* key) override { + if (!key) return E_POINTER; + if (index >= sizeof kKeys / sizeof kKeys[0]) return E_INVALIDARG; + *key = kKeys[index]; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetValue(REFPROPERTYKEY key, PROPVARIANT* value) override { + if (!value) return E_POINTER; + PropVariantInit(value); + if (same_key(key, kKeyFriendlyName) || same_key(key, kKeyDeviceDesc) || same_key(key, kKeyInterfaceName) || + same_key(key, kKeyEndpointGuid)) { + value->pwszVal = co_task_string(same_key(key, kKeyEndpointGuid) ? kEndpointGuid : kFriendlyName); + if (!value->pwszVal) return E_OUTOFMEMORY; + value->vt = VT_LPWSTR; + } else if (same_key(key, kKeyDeviceFormat) || same_key(key, kKeyOemFormat)) { + value->blob.pBlobData = reinterpret_cast(alloc_mix_format()); + if (!value->blob.pBlobData) return E_OUTOFMEMORY; + value->blob.cbSize = sizeof(WAVEFORMATEXTENSIBLE); + value->vt = VT_BLOB; + } else if (same_key(key, kKeyFormFactor) || same_key(key, kKeyPhysicalSpeakers)) { + value->ulVal = same_key(key, kKeyFormFactor) ? kFormFactorSpeakers : kChannelMask; + value->vt = VT_UI4; + } + return S_OK; // any other key: VT_EMPTY, as a host store answers a key it does not hold + } + HRESULT STDMETHODCALLTYPE SetValue(REFPROPERTYKEY, REFPROPVARIANT) override { return STG_E_ACCESSDENIED; } + HRESULT STDMETHODCALLTYPE Commit() override { return STG_E_ACCESSDENIED; } +}; + +// ---- IMMDevice ------------------------------------------------------------------------------------------------ + +class Device final : public IMMDevice, public IMMEndpoint { +public: + ULONG STDMETHODCALLTYPE AddRef() override { return static_cast(InterlockedIncrement(&refs_)); } + ULONG STDMETHODCALLTYPE Release() override { + const LONG n = InterlockedDecrement(&refs_); + if (n == 0) delete this; + return static_cast(n); + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (IsEqualIID(riid, __uuidof(IUnknown)) || IsEqualIID(riid, __uuidof(IMMDevice))) { + *ppv = static_cast(this); + } else if (IsEqualIID(riid, __uuidof(IMMEndpoint))) { + *ppv = static_cast(this); + } else { + return E_NOINTERFACE; + } + AddRef(); + return S_OK; + } + + // IMMDevice + HRESULT STDMETHODCALLTYPE Activate(REFIID riid, DWORD, PROPVARIANT*, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!IsEqualIID(riid, __uuidof(IAudioClient)) && !IsEqualIID(riid, __uuidof(IAudioClient2)) && + !IsEqualIID(riid, __uuidof(IAudioClient3))) { + log_missing_iid_once("IMMDevice::Activate", riid); + return E_NOINTERFACE; + } + auto* client = new (std::nothrow) AudioClient(); + if (!client) return E_OUTOFMEMORY; + const HRESULT hr = client->QueryInterface(riid, ppv); + client->Release(); + return hr; + } + HRESULT STDMETHODCALLTYPE OpenPropertyStore(DWORD access, IPropertyStore** store) override { + if (!store) return E_POINTER; + *store = nullptr; + if (access != STGM_READ && access != STGM_WRITE && access != STGM_READWRITE) return E_INVALIDARG; + if (access != STGM_READ) return E_ACCESSDENIED; + *store = new (std::nothrow) PropertyStore(); + return *store ? S_OK : E_OUTOFMEMORY; + } + HRESULT STDMETHODCALLTYPE GetId(LPWSTR* id) override { + if (!id) return E_POINTER; + *id = co_task_string(kDeviceId); + return *id ? S_OK : E_OUTOFMEMORY; + } + HRESULT STDMETHODCALLTYPE GetState(DWORD* state) override { + if (!state) return E_POINTER; + *state = DEVICE_STATE_ACTIVE; + return S_OK; + } + + // IMMEndpoint + HRESULT STDMETHODCALLTYPE GetDataFlow(EDataFlow* flow) override { + if (!flow) return E_POINTER; + *flow = eRender; + return S_OK; + } + +private: + ~Device() = default; + LONG refs_ = 1; +}; + +IMMDevice* make_device(const char* reason) { + auto* d = new (std::nothrow) Device(); + if (d) note_served(reason); + return d; +} + +// ---- IMMDeviceCollection -------------------------------------------------------------------------------------- + +class Collection final : public Unknown { +public: + void add(IMMDevice* device) { devices_.push_back(device); } // takes the reference + HRESULT STDMETHODCALLTYPE GetCount(UINT* count) override { + if (!count) return E_POINTER; + *count = static_cast(devices_.size()); + return S_OK; + } + HRESULT STDMETHODCALLTYPE Item(UINT index, IMMDevice** device) override { + if (!device) return E_POINTER; + *device = nullptr; + if (index >= devices_.size()) return E_INVALIDARG; + *device = devices_[index]; + (*device)->AddRef(); + return S_OK; + } + +private: + ~Collection() override { + for (IMMDevice* d : devices_) d->Release(); + } + std::vector devices_; +}; + +// Appends the host's devices of one flow; returns the result of the host's call. +HRESULT append_host(IMMDeviceEnumerator* host, EDataFlow flow, DWORD mask, Collection* out) { + IMMDeviceCollection* c = nullptr; + const HRESULT hr = host->EnumAudioEndpoints(flow, mask, &c); + if (FAILED(hr) || !c) return hr; + UINT n = 0; + c->GetCount(&n); + for (UINT i = 0; i < n; ++i) { + IMMDevice* d = nullptr; + if (SUCCEEDED(c->Item(i, &d)) && d) out->add(d); + } + c->Release(); + return hr; +} + +// ---- IMMDeviceEnumerator -------------------------------------------------------------------------------------- + +class Enumerator final : public Unknown { +public: + Enumerator(IMMDeviceEnumerator* host, HRESULT host_hr, Mode mode, HostFactory factory) + : host_(host), host_hr_(host_hr), mode_(mode), factory_(factory) { + if (host_) host_->AddRef(); + } + + HRESULT STDMETHODCALLTYPE EnumAudioEndpoints(EDataFlow flow, DWORD mask, IMMDeviceCollection** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (flow != eRender && flow != eCapture && flow != eAll) return E_INVALIDARG; + if (mask & ~DEVICE_STATEMASK_ALL) return E_INVALIDARG; + auto* c = new (std::nothrow) Collection(); + if (!c) return E_OUTOFMEMORY; + if (flow == eRender || flow == eAll) { + char reason[96]; + if (!host_render(reason, sizeof reason)) { + if (mask & DEVICE_STATE_ACTIVE) { + if (IMMDevice* d = make_device(reason)) c->add(d); + } + } else { + append_host(host_, eRender, mask, c); + } + } + if (flow == eCapture || flow == eAll) { + if (IMMDeviceEnumerator* h = host()) append_host(h, eCapture, mask, c); + } + *out = c; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint(EDataFlow flow, ERole role, IMMDevice** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (role != eConsole && role != eMultimedia && role != eCommunications) return E_INVALIDARG; + if (flow == eCapture) { + IMMDeviceEnumerator* h = host(); + return h ? h->GetDefaultAudioEndpoint(flow, role, out) : kNotFound; + } + if (flow != eRender) return E_INVALIDARG; + char reason[96]; + if (mode_ == Mode::Auto && host_) { + const HRESULT hr = host_->GetDefaultAudioEndpoint(eRender, role, out); + if (SUCCEEDED(hr) && *out) return hr; + if (*out) (*out)->Release(); + *out = nullptr; + std::snprintf(reason, sizeof reason, "no host render endpoint: GetDefaultAudioEndpoint 0x%08lx", + static_cast(hr)); + } else { + why_silent(reason, sizeof reason); + } + *out = make_device(reason); + return *out ? S_OK : E_OUTOFMEMORY; + } + HRESULT STDMETHODCALLTYPE GetDevice(LPCWSTR id, IMMDevice** out) override { + if (!id || !out) return E_POINTER; + *out = nullptr; + if (std::wcscmp(id, kDeviceId) == 0) { + char reason[96]; + why_silent(reason, sizeof reason); + *out = make_device(reason); + return *out ? S_OK : E_OUTOFMEMORY; + } + IMMDeviceEnumerator* h = host(); + return h ? h->GetDevice(id, out) : kNotFound; + } + // Accepted and never called: the silent endpoint never changes, and no host notification is forwarded. + HRESULT STDMETHODCALLTYPE RegisterEndpointNotificationCallback(IMMNotificationClient* client) override { + return client ? S_OK : E_POINTER; + } + HRESULT STDMETHODCALLTYPE UnregisterEndpointNotificationCallback(IMMNotificationClient* client) override { + return client ? S_OK : E_POINTER; + } + +private: + ~Enumerator() override { + if (host_) host_->Release(); + } + + // The host's enumerator for capture questions: made on first use in Mode::Silent. + IMMDeviceEnumerator* host() { + AcquireSRWLockExclusive(&lock_); + if (!host_ && factory_ && !factory_tried_) { + factory_tried_ = true; + host_ = factory_(); + } + IMMDeviceEnumerator* h = host_; + ReleaseSRWLockExclusive(&lock_); + return h; + } + + void why_silent(char* reason, size_t size) const { + if (mode_ == Mode::Silent) std::snprintf(reason, size, "LEONIDA_AUDIO=silent"); + else if (!host_) std::snprintf(reason, size, "no host device enumerator: 0x%08lx", + static_cast(host_hr_)); + else std::snprintf(reason, size, "no host render endpoint"); + } + + // True when render questions go to the host: Mode::Auto and a host with a default render endpoint. + bool host_render(char* reason, size_t size) { + if (mode_ == Mode::Auto && host_) { + IMMDevice* d = nullptr; + const HRESULT hr = host_->GetDefaultAudioEndpoint(eRender, eConsole, &d); + if (d) d->Release(); + if (SUCCEEDED(hr) && d) return true; + std::snprintf(reason, size, "no host render endpoint: GetDefaultAudioEndpoint 0x%08lx", + static_cast(hr)); + return false; + } + why_silent(reason, size); + return false; + } + + SRWLOCK lock_ = SRWLOCK_INIT; + IMMDeviceEnumerator* host_; + HRESULT host_hr_; + Mode mode_; + HostFactory factory_; + bool factory_tried_ = false; +}; + +IMMDeviceEnumerator* make_host_enumerator() { + IMMDeviceEnumerator* e = nullptr; + if (FAILED(::CoCreateInstance(kClsidMMDeviceEnumerator, nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), + reinterpret_cast(&e)))) { + return nullptr; + } + return e; +} + +} // namespace + +Mode mode_from_env() { + char v[16]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_AUDIO", v, sizeof v); + if (n == 0 || n >= sizeof v) return Mode::Auto; + return _stricmp(v, "silent") == 0 ? Mode::Silent : Mode::Auto; +} + +HRESULT serve_enumerator(IMMDeviceEnumerator* host, HRESULT host_hr, Mode mode, HostFactory factory, REFIID riid, + void** ppv) { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (mode == Mode::Auto && host) { + IMMDevice* d = nullptr; + const HRESULT hr = host->GetDefaultAudioEndpoint(eRender, eConsole, &d); + if (d) d->Release(); + if (SUCCEEDED(hr) && d) return host->QueryInterface(riid, ppv); // the host has an output: unchanged + } + auto* e = new (std::nothrow) Enumerator(host, host ? S_OK : host_hr, mode, factory); + if (!e) return E_OUTOFMEMORY; + const HRESULT hr = e->QueryInterface(riid, ppv); + e->Release(); + return hr; +} + +HRESULT create_enumerator(DWORD cls_context, REFIID riid, void** ppv) { + if (!ppv) return E_POINTER; + *ppv = nullptr; + const Mode mode = mode_from_env(); + if (mode == Mode::Silent) return serve_enumerator(nullptr, S_OK, mode, &make_host_enumerator, riid, ppv); + IMMDeviceEnumerator* host = nullptr; + const HRESULT hr = ::CoCreateInstance(kClsidMMDeviceEnumerator, nullptr, cls_context, + __uuidof(IMMDeviceEnumerator), reinterpret_cast(&host)); + if (FAILED(hr)) host = nullptr; + const HRESULT served = serve_enumerator(host, hr, mode, nullptr, riid, ppv); + if (host) host->Release(); + return served; +} + +uint32_t devices_served() { return static_cast(InterlockedCompareExchange(&g_served, 0, 0)); } + +} // namespace rt::silent_audio diff --git a/runtime/shims/silent_audio.h b/runtime/shims/silent_audio.h new file mode 100644 index 000000000..db7fa3a7f --- /dev/null +++ b/runtime/shims/silent_audio.h @@ -0,0 +1,60 @@ +// The silent output endpoint: an in-process WASAPI render device that throws every sample away. +// +// The title creates its MMDeviceEnumerator through CoCreateInstance (com_shim.cpp). When the host has no render +// endpoint, GetDefaultAudioEndpoint(eRender, ...) fails with 0x80070490 (ERROR_NOT_FOUND); the title's device start +// then leaks its own output-device lock and its audio engine never mixes, so the boot stops. A console always has an +// output, so the title only meets that path off-console. The enumerator served here answers render questions with a +// device of its own when the host has none (or always, with LEONIDA_AUDIO=silent): an IAudioClient whose clock +// consumes frames in real time and signals the stream's event every period. It never opens a host audio device. +// Capture questions keep the host's answer. +#pragma once + +#include +#include +#include + +#include + +namespace rt::silent_audio { + +// {BCDE0395-E52F-467C-8E3D-C4579291692E} +inline constexpr CLSID kClsidMMDeviceEnumerator{ + 0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; + +// The endpoint ID GetId returns (the form of a host render endpoint ID). +inline constexpr wchar_t kDeviceId[] = L"{0.0.0.00000000}.{5a4c2a5e-1e0d-4c1b-9a51-6c656f6e6964}"; +inline constexpr wchar_t kFriendlyName[] = L"Leonida silent output"; + +// The mix format: 48 kHz, 32-bit float, 7.1 (eight channels, KSAUDIO_SPEAKER_7POINT1_SURROUND). +inline constexpr uint32_t kSampleRate = 48000; +inline constexpr uint16_t kChannels = 8; +inline constexpr uint32_t kChannelMask = 0x63F; +// The engine period: 10 ms (default), 3 ms (minimum), in 100 ns units. +inline constexpr int64_t kDefaultPeriodHns = 100000; +inline constexpr int64_t kMinimumPeriodHns = 30000; + +enum class Mode { + Auto, // the host's render endpoint when it has one, the silent one when it has none + Silent, // LEONIDA_AUDIO=silent: the silent endpoint even when the host has one +}; + +// LEONIDA_AUDIO, read on every call: "silent" (any case) is Mode::Silent, anything else Mode::Auto. +Mode mode_from_env(); + +// Makes the host's enumerator on demand (Mode::Silent creates none until a capture question needs one); may be null. +using HostFactory = IMMDeviceEnumerator* (*)(); + +// What CoCreateInstance(CLSID_MMDeviceEnumerator) returns. `host` is the host's enumerator or null, with `host_hr` +// the result of creating it; it is not consumed (what is kept is AddRef'd). In Mode::Auto, a host that answers +// GetDefaultAudioEndpoint(eRender, eConsole) is returned itself, unchanged; otherwise the wrapper answers. +HRESULT serve_enumerator(IMMDeviceEnumerator* host, HRESULT host_hr, Mode mode, HostFactory factory, REFIID riid, + void** ppv); + +// The CoCreateInstance hook: the mode from the environment, the host's enumerator (not made in Mode::Silent), then +// serve_enumerator. +HRESULT create_enumerator(DWORD cls_context, REFIID riid, void** ppv); + +// For tests: how many silent devices have been handed out. +uint32_t devices_served(); + +} // namespace rt::silent_audio diff --git a/runtime/test/silent_audio_test.cpp b/runtime/test/silent_audio_test.cpp new file mode 100644 index 000000000..cb9f9b860 --- /dev/null +++ b/runtime/test/silent_audio_test.cpp @@ -0,0 +1,585 @@ +// Tests for runtime/shims/silent_audio.cpp: the silent output endpoint behind CoCreateInstance(MMDeviceEnumerator). +// +// The host is a stand-in enumerator (with no endpoints, or with one), so no host audio device or sound server is ever +// touched. The last case goes through the com_shim CoCreateInstance with LEONIDA_AUDIO=silent, which makes no host +// enumerator for render questions. +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "shims.h" +#include "silent_audio.h" + +namespace { + +namespace sa = rt::silent_audio; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); +constexpr GUID kSubtypeFloat{0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; +constexpr PROPERTYKEY kKeyFriendlyName{{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, + 14}; +constexpr PROPERTYKEY kKeyDeviceFormat{{0xf19f064d, 0x082c, 0x4e27, {0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c}}, + 0}; + +// ---- stand-in host ------------------------------------------------------------------------------------------- + +class HostDevice final : public IMMDevice { +public: + ULONG STDMETHODCALLTYPE AddRef() override { return static_cast(InterlockedIncrement(&refs_)); } + ULONG STDMETHODCALLTYPE Release() override { + const LONG n = InterlockedDecrement(&refs_); + if (n == 0) delete this; + return static_cast(n); + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!IsEqualIID(riid, __uuidof(IUnknown)) && !IsEqualIID(riid, __uuidof(IMMDevice))) return E_NOINTERFACE; + *ppv = this; + AddRef(); + return S_OK; + } + HRESULT STDMETHODCALLTYPE Activate(REFIID, DWORD, PROPVARIANT*, void**) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE OpenPropertyStore(DWORD, IPropertyStore**) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE GetId(LPWSTR* id) override { + const wchar_t text[] = L"host-device"; + *id = static_cast(CoTaskMemAlloc(sizeof text)); + std::memcpy(*id, text, sizeof text); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetState(DWORD* state) override { + *state = DEVICE_STATE_ACTIVE; + return S_OK; + } + +private: + LONG refs_ = 1; +}; + +class HostCollection final : public IMMDeviceCollection { +public: + explicit HostCollection(bool one) : one_(one) {} + ULONG STDMETHODCALLTYPE AddRef() override { return static_cast(InterlockedIncrement(&refs_)); } + ULONG STDMETHODCALLTYPE Release() override { + const LONG n = InterlockedDecrement(&refs_); + if (n == 0) delete this; + return static_cast(n); + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; } + HRESULT STDMETHODCALLTYPE GetCount(UINT* n) override { + *n = one_ ? 1 : 0; + return S_OK; + } + HRESULT STDMETHODCALLTYPE Item(UINT i, IMMDevice** d) override { + *d = nullptr; + if (!one_ || i != 0) return E_INVALIDARG; + *d = new HostDevice(); + return S_OK; + } + +private: + LONG refs_ = 1; + bool one_; +}; + +// A host enumerator: with no endpoints at all (as a machine without an output), or with one render endpoint. It +// counts what it was asked, per flow. +class HostEnumerator final : public IMMDeviceEnumerator { +public: + explicit HostEnumerator(bool has_render) : has_render_(has_render) {} + ULONG STDMETHODCALLTYPE AddRef() override { return static_cast(InterlockedIncrement(&refs_)); } + ULONG STDMETHODCALLTYPE Release() override { + const LONG n = InterlockedDecrement(&refs_); + if (n == 0) delete this; + return static_cast(n); + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!IsEqualIID(riid, __uuidof(IUnknown)) && !IsEqualIID(riid, __uuidof(IMMDeviceEnumerator))) + return E_NOINTERFACE; + *ppv = this; + AddRef(); + return S_OK; + } + HRESULT STDMETHODCALLTYPE EnumAudioEndpoints(EDataFlow flow, DWORD, IMMDeviceCollection** out) override { + ++(flow == eCapture ? capture_calls : render_calls); + *out = new HostCollection(flow == eRender && has_render_); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint(EDataFlow flow, ERole, IMMDevice** out) override { + ++(flow == eCapture ? capture_calls : render_calls); + *out = nullptr; + if (flow != eRender || !has_render_) return kNotFound; + *out = new HostDevice(); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetDevice(LPCWSTR, IMMDevice** out) override { + ++other_calls; + *out = nullptr; + return kNotFound; + } + HRESULT STDMETHODCALLTYPE RegisterEndpointNotificationCallback(IMMNotificationClient*) override { + ++other_calls; + return S_OK; + } + HRESULT STDMETHODCALLTYPE UnregisterEndpointNotificationCallback(IMMNotificationClient*) override { + ++other_calls; + return S_OK; + } + LONG refs() const { return refs_; } + + int render_calls = 0; + int capture_calls = 0; + int other_calls = 0; + +private: + LONG refs_ = 1; + bool has_render_; +}; + +HostEnumerator* g_lazy_host = nullptr; +int g_lazy_made = 0; +IMMDeviceEnumerator* lazy_factory() { + ++g_lazy_made; + g_lazy_host->AddRef(); + return g_lazy_host; +} + +class Notifications final : public IMMNotificationClient { +public: + ULONG STDMETHODCALLTYPE AddRef() override { return 2; } + ULONG STDMETHODCALLTYPE Release() override { return 1; } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; } + HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR, DWORD) override { return ++calls, S_OK; } + HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR) override { return ++calls, S_OK; } + HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR) override { return ++calls, S_OK; } + HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow, ERole, LPCWSTR) override { return ++calls, S_OK; } + HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY) override { return ++calls, S_OK; } + int calls = 0; +}; + +// ---- helpers -------------------------------------------------------------------------------------------------- + +bool is_silent_device(IMMDevice* d) { + if (!d) return false; + LPWSTR id = nullptr; + const bool ok = SUCCEEDED(d->GetId(&id)) && id && std::wcscmp(id, sa::kDeviceId) == 0; + CoTaskMemFree(id); + return ok; +} + +IMMDeviceEnumerator* serve(IMMDeviceEnumerator* host, HRESULT host_hr, sa::Mode mode, sa::HostFactory factory) { + IMMDeviceEnumerator* e = nullptr; + const HRESULT hr = + sa::serve_enumerator(host, host_hr, mode, factory, __uuidof(IMMDeviceEnumerator), reinterpret_cast(&e)); + return SUCCEEDED(hr) ? e : nullptr; +} + +UINT collection_count(IMMDeviceEnumerator* e, EDataFlow flow, DWORD mask, bool* silent_first = nullptr) { + IMMDeviceCollection* c = nullptr; + if (FAILED(e->EnumAudioEndpoints(flow, mask, &c)) || !c) return 0xFFFFFFFF; + UINT n = 0; + c->GetCount(&n); + if (silent_first) { + IMMDevice* d = nullptr; + *silent_first = n > 0 && SUCCEEDED(c->Item(0, &d)) && is_silent_device(d); + if (d) d->Release(); + } + c->Release(); + return n; +} + +// ---- the enumerator ------------------------------------------------------------------------------------------- + +void test_host_without_endpoints() { + auto* host = new HostEnumerator(false); + IMMDeviceEnumerator* e = serve(host, S_OK, sa::Mode::Auto, nullptr); + check(e != nullptr && e != host, "no host render endpoint: the wrapper answers, not the host"); + if (!e) return; + const uint32_t served_before = sa::devices_served(); + + IMMDevice* d = nullptr; + check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d), + "GetDefaultAudioEndpoint(eRender, eConsole) is the silent device"); + check(host->render_calls >= 1, "the host was asked first"); + check(sa::devices_served() == served_before + 1, "one silent device handed out"); + if (d) { + DWORD state = 0; + check(d->GetState(&state) == S_OK && state == DEVICE_STATE_ACTIVE, "the silent device is active"); + IMMEndpoint* ep = nullptr; + EDataFlow flow = eCapture; + check(SUCCEEDED(d->QueryInterface(__uuidof(IMMEndpoint), reinterpret_cast(&ep))) && + ep->GetDataFlow(&flow) == S_OK && flow == eRender, + "IMMEndpoint says eRender"); + if (ep) ep->Release(); + + IPropertyStore* store = nullptr; + check(d->OpenPropertyStore(STGM_READWRITE, &store) == E_ACCESSDENIED && !store, + "the property store is read-only"); + check(d->OpenPropertyStore(STGM_READ, &store) == S_OK && store, "OpenPropertyStore(STGM_READ)"); + if (store) { + PROPVARIANT v; + PropVariantInit(&v); + check(store->GetValue(kKeyFriendlyName, &v) == S_OK && v.vt == VT_LPWSTR && + std::wcscmp(v.pwszVal, sa::kFriendlyName) == 0, + "PKEY_Device_FriendlyName"); + PropVariantClear(&v); + check(store->GetValue(kKeyDeviceFormat, &v) == S_OK && v.vt == VT_BLOB && + v.blob.cbSize == sizeof(WAVEFORMATEXTENSIBLE), + "PKEY_AudioEngine_DeviceFormat is a WAVEFORMATEXTENSIBLE blob"); + if (v.vt == VT_BLOB) { + const auto* f = reinterpret_cast(v.blob.pBlobData); + check(f->Format.nChannels == 8 && f->Format.nSamplesPerSec == 48000 && f->Format.wBitsPerSample == 32 && + f->dwChannelMask == 0x63F && IsEqualGUID(f->SubFormat, kSubtypeFloat), + "device format: 48 kHz float 7.1"); + } + PropVariantClear(&v); + DWORD n = 0; + check(store->GetCount(&n) == S_OK && n >= 2, "the store lists its keys"); + store->Release(); + } + d->Release(); + } + + bool silent_first = false; + check(collection_count(e, eRender, DEVICE_STATE_ACTIVE, &silent_first) == 1 && silent_first, + "EnumAudioEndpoints(eRender, ACTIVE) lists the silent device"); + check(collection_count(e, eRender, DEVICE_STATE_DISABLED) == 0, + "EnumAudioEndpoints(eRender, DISABLED) lists nothing"); + const int capture_before = host->capture_calls; + check(collection_count(e, eCapture, DEVICE_STATEMASK_ALL) == 0 && host->capture_calls == capture_before + 1, + "EnumAudioEndpoints(eCapture) is the host's answer"); + check(collection_count(e, eAll, DEVICE_STATE_ACTIVE) == 1, "EnumAudioEndpoints(eAll) has the silent device"); + check(e->GetDefaultAudioEndpoint(eCapture, eConsole, &d) == kNotFound && !d, + "GetDefaultAudioEndpoint(eCapture) is the host's answer"); + check(e->GetDefaultAudioEndpoint(eAll, eConsole, &d) == E_INVALIDARG, "GetDefaultAudioEndpoint(eAll) is refused"); + check(e->GetDevice(sa::kDeviceId, &d) == S_OK && is_silent_device(d), "GetDevice(silent id)"); + if (d) d->Release(); + d = nullptr; + check(e->GetDevice(L"host-device", &d) == kNotFound && host->other_calls == 1, "GetDevice(other id) goes to the host"); + + Notifications n; + check(e->RegisterEndpointNotificationCallback(&n) == S_OK, "RegisterEndpointNotificationCallback accepted"); + check(e->UnregisterEndpointNotificationCallback(&n) == S_OK && n.calls == 0, + "UnregisterEndpointNotificationCallback; the callback never fired"); + check(e->RegisterEndpointNotificationCallback(nullptr) == E_POINTER, "a null callback is E_POINTER"); + + e->Release(); + check(host->refs() == 1, "the wrapper released the host"); + host->Release(); +} + +void test_host_with_endpoint() { + auto* host = new HostEnumerator(true); + IMMDeviceEnumerator* e = serve(host, S_OK, sa::Mode::Auto, nullptr); + check(e == host, "a host with a render endpoint is returned unchanged"); + if (e) e->Release(); + + const int render_before = host->render_calls; + e = serve(host, S_OK, sa::Mode::Silent, nullptr); + check(e != nullptr && e != host && host->render_calls == render_before, + "LEONIDA_AUDIO=silent: the wrapper answers without asking the host"); + if (e) { + IMMDevice* d = nullptr; + check(e->GetDefaultAudioEndpoint(eRender, eMultimedia, &d) == S_OK && is_silent_device(d) && + host->render_calls == render_before, + "forced: GetDefaultAudioEndpoint(eRender) is silent, the host's endpoint is not used"); + if (d) d->Release(); + bool silent_first = false; + check(collection_count(e, eRender, DEVICE_STATE_ACTIVE, &silent_first) == 1 && silent_first && + host->render_calls == render_before, + "forced: EnumAudioEndpoints(eRender) lists only the silent device"); + e->Release(); + } + host->Release(); +} + +void test_no_host_enumerator() { + IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr); + check(e != nullptr, "no host enumerator: the wrapper still serves"); + if (!e) return; + IMMDevice* d = nullptr; + check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d), + "no host enumerator: render is the silent device"); + if (d) d->Release(); + d = nullptr; + check(e->GetDefaultAudioEndpoint(eCapture, eConsole, &d) == kNotFound && !d, + "no host enumerator: capture is ERROR_NOT_FOUND"); + check(collection_count(e, eCapture, DEVICE_STATE_ACTIVE) == 0, "no host enumerator: no capture devices"); + e->Release(); + + // Forced, the host is made only when a capture question comes. + g_lazy_host = new HostEnumerator(true); + e = serve(nullptr, S_OK, sa::Mode::Silent, &lazy_factory); + if (e) { + check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d) && g_lazy_made == 0, + "forced: render makes no host enumerator"); + if (d) d->Release(); + d = nullptr; + e->GetDefaultAudioEndpoint(eCapture, eConsole, &d); + check(g_lazy_made == 1 && g_lazy_host->capture_calls == 1, "forced: a capture question makes the host's"); + if (d) d->Release(); + e->Release(); + } + check(g_lazy_host->refs() == 1, "forced: the lazily made host is released"); + g_lazy_host->Release(); +} + +// ---- the stream ----------------------------------------------------------------------------------------------- + +IAudioClient* activate(IMMDevice* d, REFIID riid) { + void* out = nullptr; + return SUCCEEDED(d->Activate(riid, CLSCTX_ALL, nullptr, &out)) ? static_cast(out) : nullptr; +} + +void test_render_stream() { + IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr); + IMMDevice* d = nullptr; + if (!e || FAILED(e->GetDefaultAudioEndpoint(eRender, eConsole, &d)) || !d) { + check(false, "silent device for the stream tests"); + return; + } + e->Release(); + + for (const IID& iid : {__uuidof(IAudioClient), __uuidof(IAudioClient2), __uuidof(IAudioClient3)}) { + IAudioClient* c = activate(d, iid); + check(c != nullptr, "Activate(IAudioClient / 2 / 3)"); + if (c) c->Release(); + } + void* other = reinterpret_cast(1); + check(d->Activate(__uuidof(IMMDeviceEnumerator), CLSCTX_ALL, nullptr, &other) == E_NOINTERFACE && !other, + "Activate(another interface) is E_NOINTERFACE"); + + IAudioClient3* c = nullptr; + d->Activate(__uuidof(IAudioClient3), CLSCTX_ALL, nullptr, reinterpret_cast(&c)); + d->Release(); + if (!c) return; + + UINT32 frames = 0; + check(c->GetBufferSize(&frames) == AUDCLNT_E_NOT_INITIALIZED, "GetBufferSize before Initialize"); + check(c->Start() == AUDCLNT_E_NOT_INITIALIZED, "Start before Initialize"); + + WAVEFORMATEX* mix = nullptr; + check(c->GetMixFormat(&mix) == S_OK && mix && mix->wFormatTag == WAVE_FORMAT_EXTENSIBLE && mix->nChannels == 8 && + mix->nSamplesPerSec == 48000 && mix->wBitsPerSample == 32 && mix->nBlockAlign == 32, + "GetMixFormat: 48 kHz float, 8 channels"); + if (!mix) return; + WAVEFORMATEX* closest = reinterpret_cast(1); + check(c->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, mix, &closest) == S_OK && !closest, + "IsFormatSupported(mix format) is S_OK"); + WAVEFORMATEX stereo{WAVE_FORMAT_PCM, 2, 44100, 44100 * 4, 4, 16, 0}; + check(c->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &stereo, &closest) == S_FALSE && closest && + closest->nChannels == 8, + "IsFormatSupported(stereo 44.1 kHz) is S_FALSE with the mix format"); + CoTaskMemFree(closest); + check(c->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mix, nullptr) == AUDCLNT_E_UNSUPPORTED_FORMAT, + "no exclusive mode"); + REFERENCE_TIME def = 0, minimum = 0; + check(c->GetDevicePeriod(&def, &minimum) == S_OK && def == 100000 && minimum > 0 && minimum <= def, + "GetDevicePeriod: 10 ms"); + + check(c->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, mix, nullptr) == S_OK, + "Initialize(shared, event callback, mix format)"); + check(c->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 0, 0, mix, nullptr) == AUDCLNT_E_ALREADY_INITIALIZED, + "a second Initialize is refused"); + CoTaskMemFree(mix); + check(c->GetBufferSize(&frames) == S_OK && frames >= 960, "GetBufferSize: at least two periods"); + REFERENCE_TIME latency = 0; + check(c->GetStreamLatency(&latency) == S_OK && latency > 0, "GetStreamLatency"); + check(c->Start() == AUDCLNT_E_EVENTHANDLE_NOT_SET, "Start without an event handle is refused"); + + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + check(c->SetEventHandle(event) == S_OK, "SetEventHandle"); + + IAudioRenderClient* render = nullptr; + IAudioClock* clock = nullptr; + ISimpleAudioVolume* simple = nullptr; + IAudioStreamVolume* stream = nullptr; + check(c->GetService(__uuidof(IAudioRenderClient), reinterpret_cast(&render)) == S_OK && render, + "GetService(IAudioRenderClient)"); + check(c->GetService(__uuidof(IAudioClock), reinterpret_cast(&clock)) == S_OK && clock, + "GetService(IAudioClock)"); + check(c->GetService(__uuidof(ISimpleAudioVolume), reinterpret_cast(&simple)) == S_OK && simple, + "GetService(ISimpleAudioVolume)"); + check(c->GetService(__uuidof(IAudioStreamVolume), reinterpret_cast(&stream)) == S_OK && stream, + "GetService(IAudioStreamVolume)"); + if (!render || !clock || !simple || !stream) return; + UINT32 channels = 0; + float level = 0.0f; + check(stream->GetChannelCount(&channels) == S_OK && channels == 8 && stream->SetChannelVolume(7, 0.5f) == S_OK && + stream->GetChannelVolume(7, &level) == S_OK && level == 0.5f, + "IAudioStreamVolume keeps a channel volume"); + check(simple->SetMasterVolume(0.25f, nullptr) == S_OK && simple->GetMasterVolume(&level) == S_OK && level == 0.25f, + "ISimpleAudioVolume keeps the master volume"); + UINT64 freq = 0; + check(clock->GetFrequency(&freq) == S_OK && freq == 48000, "IAudioClock counts frames at 48 kHz"); + + // Fill the whole buffer before Start, as a title primes its stream. + BYTE* data = nullptr; + check(render->ReleaseBuffer(1, 0) == AUDCLNT_E_OUT_OF_ORDER, "ReleaseBuffer without GetBuffer"); + check(render->GetBuffer(frames + 1, &data) == AUDCLNT_E_BUFFER_TOO_LARGE, "GetBuffer larger than the buffer"); + check(render->GetBuffer(frames, &data) == S_OK && data, "GetBuffer(whole buffer)"); + if (data) std::memset(data, 0x7f, static_cast(frames) * 32); + check(render->GetBuffer(1, &data) == AUDCLNT_E_OUT_OF_ORDER, "a second GetBuffer before ReleaseBuffer"); + check(render->ReleaseBuffer(frames + 1, 0) == AUDCLNT_E_INVALID_SIZE, "ReleaseBuffer of more than was got"); + check(render->ReleaseBuffer(frames, 0) == S_OK, "ReleaseBuffer(whole buffer)"); + UINT32 padding = 0; + check(c->GetCurrentPadding(&padding) == S_OK && padding == frames, "padding is the whole buffer before Start"); + Sleep(30); + check(c->GetCurrentPadding(&padding) == S_OK && padding == frames, "nothing drains before Start"); + check(render->GetBuffer(1, &data) == AUDCLNT_E_BUFFER_TOO_LARGE, "a full buffer takes no more"); + + // Run for a few periods, refilling on every event, as an event-driven title does. + LARGE_INTEGER f, t0, t1; + QueryPerformanceFrequency(&f); + check(c->Start() == S_OK, "Start"); + check(c->Start() == AUDCLNT_E_NOT_STOPPED, "a second Start is refused"); + QueryPerformanceCounter(&t0); + int signals = 0; + UINT32 lowest = frames; + UINT64 written = frames; + for (int i = 0; i < 12; ++i) { + if (WaitForSingleObject(event, 500) != WAIT_OBJECT_0) break; + ++signals; + if (FAILED(c->GetCurrentPadding(&padding))) break; + if (padding < lowest) lowest = padding; + const UINT32 room = frames - padding; + if (room && SUCCEEDED(render->GetBuffer(room, &data))) { + std::memset(data, 0, static_cast(room) * 32); + if (SUCCEEDED(render->ReleaseBuffer(room, 0))) written += room; + } + } + QueryPerformanceCounter(&t1); + const double seconds = static_cast(t1.QuadPart - t0.QuadPart) / static_cast(f.QuadPart); + std::printf(" 12 waits: %d signals in %.1f ms, lowest padding %u of %u, %llu frames written\n", signals, + seconds * 1000.0, lowest, frames, static_cast(written)); + check(signals == 12, "the event is signalled every period while running"); + check(seconds > 0.05 && seconds < 2.0, "the periods come at about real time (12 waits in 50 ms .. 2 s)"); + check(lowest < frames, "the padding drains while running"); + check(written > frames, "the drained room was refilled"); + UINT64 pos = 0, qpc = 0; + check(clock->GetPosition(&pos, &qpc) == S_OK && pos > 0 && pos <= written && qpc > 0, + "IAudioClock position advances, never past what was written"); + // The clock runs at the stream's rate: frames played track the time since Start (within the buffer). + const double expected = seconds * 48000.0; + check(static_cast(pos) > expected * 0.5 && static_cast(pos) <= expected * 1.5 + frames, + "the position follows real time at 48 kHz"); + + check(c->Stop() == S_OK, "Stop"); + UINT32 stopped = 0, later = 0; + c->GetCurrentPadding(&stopped); + Sleep(30); + c->GetCurrentPadding(&later); + check(stopped == later, "nothing drains after Stop"); + while (WaitForSingleObject(event, 0) == WAIT_OBJECT_0) { + } + check(WaitForSingleObject(event, 60) == WAIT_TIMEOUT, "no event after Stop"); + check(c->Stop() == S_FALSE, "a second Stop is S_FALSE"); + check(c->Reset() == S_OK && c->GetCurrentPadding(&padding) == S_OK && padding == 0, "Reset empties the buffer"); + check(clock->GetPosition(&pos, nullptr) == S_OK && pos == 0, "Reset rewinds the clock"); + + stream->Release(); + simple->Release(); + clock->Release(); + render->Release(); + check(c->Release() == 0, "the client is released last"); + CloseHandle(event); +} + +void test_polled_stream_drains() { + IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr); + IMMDevice* d = nullptr; + if (!e || FAILED(e->GetDefaultAudioEndpoint(eRender, eConsole, &d)) || !d) return; + e->Release(); + IAudioClient* c = activate(d, __uuidof(IAudioClient)); + d->Release(); + if (!c) return; + WAVEFORMATEX stereo{WAVE_FORMAT_IEEE_FLOAT, 2, 48000, 48000 * 8, 8, 32, 0}; + check(c->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 1000000, 0, &stereo, nullptr) == S_OK, + "Initialize(shared, polled, stereo float, 100 ms)"); + HANDLE unexpected = CreateEventW(nullptr, FALSE, FALSE, nullptr); + check(c->SetEventHandle(unexpected) == AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED, + "SetEventHandle on a polled stream is refused"); + CloseHandle(unexpected); + UINT32 frames = 0; + c->GetBufferSize(&frames); + check(frames >= 4800, "a 100 ms buffer holds 4800 frames"); + IAudioRenderClient* render = nullptr; + c->GetService(__uuidof(IAudioRenderClient), reinterpret_cast(&render)); + BYTE* data = nullptr; + if (render && SUCCEEDED(render->GetBuffer(frames, &data))) render->ReleaseBuffer(frames, AUDCLNT_BUFFERFLAGS_SILENT); + c->Start(); + Sleep(50); + UINT32 padding = frames; + c->GetCurrentPadding(&padding); + check(padding < frames, "a polled stream drains on its clock"); + Sleep(150); + c->GetCurrentPadding(&padding); + check(padding == 0, "a polled stream runs dry when nothing more is written"); + c->Stop(); + if (render) render->Release(); + c->Release(); +} + +// ---- through CoCreateInstance --------------------------------------------------------------------------------- + +using CoCreateInstFn = HRESULT(WINAPI*)(REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID*); + +void test_co_create_instance_forced() { + auto create = reinterpret_cast(rt::shims::find("api-ms-win-core-com-l1-1-0.dll", "CoCreateInstance")); + check(create != nullptr, "CoCreateInstance resolves"); + if (!create) return; + const HRESULT init = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + // Forced: no host enumerator is made for a render question, so this touches no host audio at all. + SetEnvironmentVariableA("LEONIDA_AUDIO", "Silent"); + check(sa::mode_from_env() == sa::Mode::Silent, "LEONIDA_AUDIO=Silent is the silent mode (any case)"); + IMMDeviceEnumerator* e = nullptr; + const HRESULT hr = create(sa::kClsidMMDeviceEnumerator, nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), + reinterpret_cast(&e)); + check(SUCCEEDED(hr) && e, "CoCreateInstance(MMDeviceEnumerator) with LEONIDA_AUDIO=silent"); + if (e) { + IMMDevice* d = nullptr; + check(e->GetDefaultAudioEndpoint(eRender, eConsole, &d) == S_OK && is_silent_device(d), + "LEONIDA_AUDIO=silent: the default render endpoint is the silent one"); + IAudioClient* c = d ? activate(d, __uuidof(IAudioClient)) : nullptr; + check(c != nullptr, "and it activates an IAudioClient"); + if (c) c->Release(); + if (d) d->Release(); + e->Release(); + } + SetEnvironmentVariableA("LEONIDA_AUDIO", "host"); + check(sa::mode_from_env() == sa::Mode::Auto, "any other LEONIDA_AUDIO value is the default"); + SetEnvironmentVariableA("LEONIDA_AUDIO", nullptr); + check(sa::mode_from_env() == sa::Mode::Auto, "unset LEONIDA_AUDIO is the default"); + if (SUCCEEDED(init)) CoUninitialize(); +} + +} // namespace + +int main() { + test_host_without_endpoints(); + test_host_with_endpoint(); + test_no_host_enumerator(); + test_render_stream(); + test_polled_stream_drains(); + test_co_create_instance_forced(); + std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 733d2c041..8d01873b2 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -86,7 +86,7 @@ $build || exit /b 1 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" From 018145b3388e739d879ff5a002bafae31e49e232 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 00:16:16 -0500 Subject: [PATCH 2/2] runtime: serve the spatial stream on the silent output endpoint The title activates ISpatialAudioClient on the render device, not IAudioClient (the first game run with the silent endpoint logged that IID and stopped as before). The silent device now answers ISpatialAudioClient and ISpatialAudioClient2: a 7.1 static bed, no dynamic objects, mono 48 kHz float objects, 480 frames a pass. Its ISpatialAudioObjectRenderStream signals the stream's event every 10 ms while it runs, and its objects write into a scratch buffer. The periodic event thread is shared with IAudioClient. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 14 +- runtime/shims/silent_audio.cpp | 455 ++++++++++++++++++++++++++--- runtime/shims/silent_audio.h | 5 +- runtime/test/silent_audio_test.cpp | 143 +++++++++ 4 files changed, 567 insertions(+), 50 deletions(-) diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index c1366c1b5..b55bb1021 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -232,7 +232,8 @@ The table under [The retail executable](#the-retail-executable-rt-5) was measure Off the console the title's sound goes out through WASAPI, not through the `AcpHal` path above: it creates an `MMDeviceEnumerator` with `CoCreateInstance` (one call, `CLSCTX_ALL`, `IID_IMMDeviceEnumerator`), asks it for the -default render endpoint and activates an `IAudioClient` on it. A console always has an output. A host with none +default render endpoint and activates `ISpatialAudioClient` on it (measured: the first interface the title asks the +device for). A console always has an output. A host with none answers `GetDefaultAudioEndpoint(eRender, ...)` with `0x80070490` (`ERROR_NOT_FOUND`), and the title's device start then takes an error path that leaves its own output-device lock held by a job worker: the audio engine never mixes, a main-thread command buffer fills up, and the title stops on an `int3` about 47 s into the boot (measured under Wine with @@ -242,8 +243,12 @@ So `CoCreateInstance` of that class goes to `runtime/shims/silent_audio.cpp` (ho the host's enumerator has a default render endpoint it is returned unchanged. When it has none, or cannot be made, or `LEONIDA_AUDIO=silent` is set, the title gets an enumerator whose render answers are a **silent output endpoint** of the runtime's own: `GetDefaultAudioEndpoint(eRender)`, `EnumAudioEndpoints(eRender)` (active devices) and `GetDevice` with -its ID give an active `IMMDevice` whose property store has a friendly name and the device format; `Activate` gives an -`IAudioClient`, `IAudioClient2` or `IAudioClient3` (any other interface is `E_NOINTERFACE`, logged once). The client +its ID give an active `IMMDevice` whose property store has a friendly name and the device format; `Activate` gives +`ISpatialAudioClient`, `ISpatialAudioClient2`, `IAudioClient`, `IAudioClient2` or `IAudioClient3` (any other interface +is `E_NOINTERFACE`, logged once). The spatial client has a 7.1 bed of static objects and no dynamic objects, as an +endpoint with no spatial sound format turned on; its objects are mono 48 kHz float, and its +`ISpatialAudioObjectRenderStream` signals the stream's event every 10 ms pass (480 frames) while it runs and hands +each object a scratch buffer between `BeginUpdatingAudioObjects` and `EndUpdatingAudioObjects`. The client takes any PCM or float format in shared mode (event-driven or polled), and `GetService` gives `IAudioRenderClient` (a scratch buffer), `IAudioClock`, `ISimpleAudioVolume` and `IAudioStreamVolume`. A clock consumes the written frames in real time, so `GetCurrentPadding` drains, and an event-driven stream's event is signalled every 10 ms period @@ -259,7 +264,8 @@ here: the console's system mixer takes a 7.1 bed whatever output is plugged in a console title is built for eight channels, where stereo would be the usual answer of a PC with headphones. The stream itself takes any channel count, so a title that asks for fewer is not refused. `silent_audio_test` covers the enumerator over stand-in hosts with and without an endpoint and with none, a render stream run for a -few periods with its event and padding checked, and the `CoCreateInstance` hook with `LEONIDA_AUDIO=silent`. +few periods with its event and padding checked, a spatial stream run for ten passes, and the `CoCreateInstance` hook +with `LEONIDA_AUDIO=silent`. ## Console paths and the write overlay diff --git a/runtime/shims/silent_audio.cpp b/runtime/shims/silent_audio.cpp index d6b650d27..0e02186bb 100644 --- a/runtime/shims/silent_audio.cpp +++ b/runtime/shims/silent_audio.cpp @@ -1,5 +1,5 @@ // The silent output endpoint (silent_audio.h): IMMDeviceEnumerator, IMMDevice, IPropertyStore, IAudioClient3 and its -// services, all in-process. Nothing here opens a host audio device; the samples a title writes go to a scratch buffer. +// services, and ISpatialAudioClient2 with its object render stream, all in-process. Nothing here opens a host audio device; the samples a title writes go to a scratch buffer. // // No function-local statics or thread_local here: like com_shim.cpp, this runs on threads the title made. #include "silent_audio.h" @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -169,6 +170,62 @@ class Unknown : public Iface { LONG refs_ = 1; }; +// Calls `tick(context)` every period on its own thread, on a fixed schedule so a late wake-up does not push the +// next ones back, until stop() (or destruction). +class PeriodicThread { +public: + using Tick = void (*)(void*); + ~PeriodicThread() { stop(); } + bool start(int64_t period_hns, Tick tick, void* context) { + if (thread_) return true; + period_hns_ = period_hns; + tick_ = tick; + context_ = context; + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + thread_ = stop_ ? CreateThread(nullptr, 64 * 1024, &PeriodicThread::run, this, 0, nullptr) : nullptr; + return thread_ != nullptr; + } + void stop() { + if (thread_) { + SetEvent(stop_); + WaitForSingleObject(thread_, INFINITE); + CloseHandle(thread_); + thread_ = nullptr; + } + if (stop_) CloseHandle(stop_); + stop_ = nullptr; + } + +private: + static DWORD WINAPI run(void* self) { + auto* t = static_cast(self); + const DWORD period_ms = static_cast((t->period_hns_ + 9999) / 10000); + const int64_t f = qpc_frequency(); + const int64_t step = t->period_hns_ * f / 10000000; + int64_t next = qpc_now() + step; + for (;;) { + const int64_t now = qpc_now(); + DWORD wait = 0; + if (next > now) { + wait = static_cast((next - now) * 1000 / f); + if (wait > period_ms) wait = period_ms; + } + if (WaitForSingleObject(t->stop_, wait) != WAIT_TIMEOUT) break; + if (qpc_now() < next) continue; + next += step; + if (next < qpc_now()) next = qpc_now() + step; + t->tick_(t->context_); + } + return 0; + } + + int64_t period_hns_ = kDefaultPeriodHns; + Tick tick_ = nullptr; + void* context_ = nullptr; + HANDLE stop_ = nullptr; + HANDLE thread_ = nullptr; +}; + // ---- IAudioClient3 -------------------------------------------------------------------------------------------- class AudioClient final : public Unknown { @@ -368,14 +425,7 @@ class AudioClient final : public Unknown { SRWLOCK& s_; }; - ~AudioClient() override { - if (thread_) { - SetEvent(stop_); - WaitForSingleObject(thread_, INFINITE); - CloseHandle(thread_); - } - if (stop_) CloseHandle(stop_); - } + ~AudioClient() override { clock_.stop(); } bool answers(REFIID riid) const override { return IsEqualIID(riid, __uuidof(IAudioClient)) || IsEqualIID(riid, __uuidof(IAudioClient2)) || @@ -402,11 +452,7 @@ class AudioClient final : public Unknown { scratch_.assign(static_cast(buffer_frames_) * block_, 0); for (float& v : channel_volume_) v = 1.0f; event_mode_ = (flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) != 0; - if (event_mode_) { - stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); - thread_ = stop_ ? CreateThread(nullptr, 64 * 1024, &AudioClient::clock_thread, this, 0, nullptr) : nullptr; - if (!thread_) return E_OUTOFMEMORY; - } + if (event_mode_ && !clock_.start(period_hns_, &AudioClient::tick, this)) return E_OUTOFMEMORY; initialized_ = true; if (InterlockedExchange(&g_stream_logged, 1) == 0) { std::fprintf(stderr, "[rt] audio: silent stream: %u ch, %u Hz, %u-byte frames, %u-frame buffer, %s\n", @@ -432,40 +478,18 @@ class AudioClient final : public Unknown { } } - void tick() { + static void tick(void* self) { + auto* c = static_cast(self); HANDLE signal = nullptr; { - Lock l(lock_); - if (!running_) return; - advance(qpc_now()); - signal = event_; + Lock l(c->lock_); + if (!c->running_) return; + c->advance(qpc_now()); + signal = c->event_; } if (signal) SetEvent(signal); } - static DWORD WINAPI clock_thread(void* self) { - auto* c = static_cast(self); - const DWORD period_ms = static_cast((c->period_hns_ + 9999) / 10000); - // A fixed schedule, so a late wake-up does not push the next ones back. - const int64_t f = qpc_frequency(); - const int64_t step = c->period_hns_ * f / 10000000; - int64_t next = qpc_now() + step; - for (;;) { - const int64_t now = qpc_now(); - DWORD wait = 0; - if (next > now) { - wait = static_cast((next - now) * 1000 / f); - if (wait > period_ms) wait = period_ms; - } - if (WaitForSingleObject(c->stop_, wait) != WAIT_TIMEOUT) break; - if (qpc_now() < next) continue; - next += step; - if (next < qpc_now()) next = qpc_now() + step; - c->tick(); - } - return 0; - } - static inline LONG g_stream_logged = 0; SRWLOCK lock_ = SRWLOCK_INIT; @@ -481,8 +505,7 @@ class AudioClient final : public Unknown { REFERENCE_TIME period_hns_ = kDefaultPeriodHns; std::vector scratch_; HANDLE event_ = nullptr; // the title's; not owned - HANDLE stop_ = nullptr; - HANDLE thread_ = nullptr; + PeriodicThread clock_; uint64_t written_ = 0; uint64_t played_ = 0; uint64_t played_at_anchor_ = 0; @@ -610,6 +633,343 @@ HRESULT AudioClient::GetService(REFIID riid, void** ppv) { return hr; } +// ---- ISpatialAudioClient2 ------------------------------------------------------------------------------------- +// +// A spatial endpoint with a 7.1 bed (the static objects of the mix format) and no dynamic objects, as an endpoint +// with no spatial sound format (Windows Sonic, Dolby Atmos) turned on. Objects are mono 48 kHz float; one pass is +// 10 ms (480 frames), and the stream's event is signalled every pass while it runs. + +constexpr uint32_t kBedMask = AudioObjectType_FrontLeft | AudioObjectType_FrontRight | AudioObjectType_FrontCenter | + AudioObjectType_LowFrequency | AudioObjectType_SideLeft | AudioObjectType_SideRight | + AudioObjectType_BackLeft | AudioObjectType_BackRight; +constexpr uint32_t kStaticTypes = 0xFFFFE; // FrontLeft .. StereoRight +constexpr uint32_t kObjectFrames = kSampleRate / 100; + +void object_format(WAVEFORMATEX* f) { + *f = WAVEFORMATEX{WAVE_FORMAT_IEEE_FLOAT, 1, kSampleRate, kSampleRate * 4, 4, 32, 0}; +} + +bool is_object_format(const WAVEFORMATEX* f) { + return f && f->nChannels == 1 && f->nSamplesPerSec == kSampleRate && f->wBitsPerSample == 32 && + f->nBlockAlign == 4 && is_float(f); +} + +bool one_type(uint32_t t) { return t != 0 && (t & (t - 1)) == 0; } + +class FormatEnumerator final : public Unknown { +public: + FormatEnumerator() { object_format(&format_); } + HRESULT STDMETHODCALLTYPE GetCount(UINT32* count) override { + if (!count) return E_POINTER; + *count = 1; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetFormat(UINT32 index, WAVEFORMATEX** format) override { + if (!format) return E_POINTER; + *format = nullptr; + if (index != 0) return E_INVALIDARG; + *format = &format_; // owned by the enumerator, as the system's is + return S_OK; + } + +private: + WAVEFORMATEX format_{}; +}; + +class SpatialStream; + +class SpatialObject final : public Unknown { +public: + SpatialObject(SpatialStream* stream, uint32_t type); + HRESULT STDMETHODCALLTYPE GetBuffer(BYTE** buffer, UINT32* length) override; + HRESULT STDMETHODCALLTYPE SetEndOfStream(UINT32 frames) override; + HRESULT STDMETHODCALLTYPE IsActive(BOOL* active) override { + if (!active) return E_POINTER; + *active = InterlockedCompareExchange(&active_, 0, 0) ? TRUE : FALSE; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetAudioObjectType(AudioObjectType* type) override { + if (!type) return E_POINTER; + *type = static_cast(type_); + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetPosition(float, float, float) override { return S_OK; } // nothing is rendered + HRESULT STDMETHODCALLTYPE SetVolume(float volume) override { + return volume >= 0.0f && volume <= 1.0f ? S_OK : E_INVALIDARG; + } + // The stream ends the object at the end of the pass it called SetEndOfStream in. + void make_inactive() { InterlockedExchange(&active_, 0); } + // True once: whoever takes the type frees it in the stream. + bool take_type() { return InterlockedExchange(&type_held_, 0) != 0; } + uint32_t type() const { return type_; } + +private: + ~SpatialObject() override; + SpatialStream* stream_; + uint32_t type_; + LONG active_ = 1; + LONG type_held_ = 1; + LONG ending_ = 0; +}; + +class SpatialStream final : public Unknown { +public: + SpatialStream(HANDLE event, uint32_t mask) : event_(event), mask_(mask) { + scratch_.assign(static_cast(kObjectFrames) * 4, 0); + } + bool start_clock() { return clock_.start(kDefaultPeriodHns, &SpatialStream::tick, this); } + + HRESULT STDMETHODCALLTYPE GetAvailableDynamicObjectCount(UINT32* value) override { + if (!value) return E_POINTER; + *value = 0; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetService(REFIID riid, void** service) override { + if (!service) return E_POINTER; + *service = nullptr; + log_missing_iid_once("ISpatialAudioObjectRenderStream::GetService", riid); + return E_NOINTERFACE; + } + HRESULT STDMETHODCALLTYPE Start() override { + { + Lock l(lock_); + if (running_) return S_OK; + running_ = true; + } + SetEvent(event_); + return S_OK; + } + HRESULT STDMETHODCALLTYPE Stop() override { + Lock l(lock_); + running_ = false; + return S_OK; + } + HRESULT STDMETHODCALLTYPE Reset() override { + Lock l(lock_); + return running_ ? SPTLAUDCLNT_E_STREAM_NOT_STOPPED : S_OK; + } + HRESULT STDMETHODCALLTYPE BeginUpdatingAudioObjects(UINT32* available, UINT32* frames) override { + if (!available || !frames) return E_POINTER; + Lock l(lock_); + if (updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER; + updating_ = true; + *available = 0; + *frames = kObjectFrames; + return S_OK; + } + HRESULT STDMETHODCALLTYPE EndUpdatingAudioObjects() override { + std::vector ended; + { + Lock l(lock_); + if (!updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER; + updating_ = false; + ended.swap(ending_); + for (SpatialObject* o : ended) { + o->make_inactive(); + if (o->take_type()) active_types_ &= ~o->type(); + } + } + for (SpatialObject* o : ended) o->Release(); + return S_OK; + } + HRESULT STDMETHODCALLTYPE ActivateSpatialAudioObject(AudioObjectType type, ISpatialAudioObject** object) override { + if (!object) return E_POINTER; + *object = nullptr; + const uint32_t t = static_cast(type); + if (t == AudioObjectType_Dynamic) return SPTLAUDCLNT_E_NO_MORE_OBJECTS; + if (!one_type(t) || (t & ~kStaticTypes)) return E_INVALIDARG; + { + Lock l(lock_); + if (!(mask_ & t)) return SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE; + if (active_types_ & t) return SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE; + active_types_ |= t; + } + auto* o = new (std::nothrow) SpatialObject(this, t); + if (!o) { + release_type(t); + return E_OUTOFMEMORY; + } + *object = o; + return S_OK; + } + + // For the objects. + HRESULT buffer(BYTE** data, UINT32* length) { + Lock l(lock_); + if (!updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER; + *data = scratch_.data(); + *length = static_cast(scratch_.size()); + return S_OK; + } + HRESULT end_of_stream(SpatialObject* o) { + Lock l(lock_); + if (!updating_) return SPTLAUDCLNT_E_OUT_OF_ORDER; + o->AddRef(); + ending_.push_back(o); + return S_OK; + } + void release_type(uint32_t t) { + Lock l(lock_); + active_types_ &= ~t; + } + +private: + struct Lock { + explicit Lock(SRWLOCK& s) : s_(s) { AcquireSRWLockExclusive(&s_); } + ~Lock() { ReleaseSRWLockExclusive(&s_); } + SRWLOCK& s_; + }; + ~SpatialStream() override { clock_.stop(); } // ending_ is empty: each entry holds the stream + static void tick(void* self) { + auto* s = static_cast(self); + bool running = false; + { + Lock l(s->lock_); + running = s->running_; + } + if (running) SetEvent(s->event_); + } + + SRWLOCK lock_ = SRWLOCK_INIT; + HANDLE event_; // the title's; not owned + uint32_t mask_; + uint32_t active_types_ = 0; + bool running_ = false; + bool updating_ = false; + std::vector scratch_; + std::vector ending_; + PeriodicThread clock_; +}; + +SpatialObject::SpatialObject(SpatialStream* stream, uint32_t type) : stream_(stream), type_(type) { + stream_->AddRef(); +} +SpatialObject::~SpatialObject() { + if (take_type()) stream_->release_type(type_); + stream_->Release(); +} +HRESULT SpatialObject::GetBuffer(BYTE** buffer, UINT32* length) { + if (!buffer || !length) return E_POINTER; + *buffer = nullptr; + *length = 0; + if (!InterlockedCompareExchange(&active_, 0, 0)) return SPTLAUDCLNT_E_RESOURCES_INVALIDATED; + return stream_->buffer(buffer, length); +} +HRESULT SpatialObject::SetEndOfStream(UINT32) { + if (!InterlockedCompareExchange(&active_, 0, 0)) return SPTLAUDCLNT_E_RESOURCES_INVALIDATED; + if (InterlockedCompareExchange(&ending_, 1, 0) != 0) return S_OK; + const HRESULT hr = stream_->end_of_stream(this); + if (FAILED(hr)) InterlockedExchange(&ending_, 0); + return hr; +} + +class SpatialClient final : public Unknown { +public: + HRESULT STDMETHODCALLTYPE GetStaticObjectPosition(AudioObjectType type, float* x, float* y, float* z) override { + if (!x || !y || !z) return E_POINTER; + // Unit directions: x right, y up, z back (the listener faces -z). + const float d = 0.70710678f; + float p[3]{}; + switch (static_cast(type)) { + case AudioObjectType_FrontLeft: p[0] = -d, p[2] = -d; break; + case AudioObjectType_FrontRight: p[0] = d, p[2] = -d; break; + case AudioObjectType_FrontCenter: p[2] = -1; break; + case AudioObjectType_LowFrequency: break; + case AudioObjectType_SideLeft: p[0] = -1; break; + case AudioObjectType_SideRight: p[0] = 1; break; + case AudioObjectType_BackLeft: p[0] = -d, p[2] = d; break; + case AudioObjectType_BackRight: p[0] = d, p[2] = d; break; + default: return E_INVALIDARG; + } + *x = p[0]; + *y = p[1]; + *z = p[2]; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetNativeStaticObjectTypeMask(AudioObjectType* mask) override { + if (!mask) return E_POINTER; + *mask = static_cast(kBedMask); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetMaxDynamicObjectCount(UINT32* value) override { + if (!value) return E_POINTER; + *value = 0; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetSupportedAudioObjectFormatEnumerator(IAudioFormatEnumerator** e) override { + if (!e) return E_POINTER; + *e = new (std::nothrow) FormatEnumerator(); + return *e ? S_OK : E_OUTOFMEMORY; + } + HRESULT STDMETHODCALLTYPE GetMaxFrameCount(const WAVEFORMATEX* format, UINT32* frames) override { + if (!format || !frames) return E_POINTER; + if (!is_object_format(format)) return AUDCLNT_E_UNSUPPORTED_FORMAT; + *frames = kObjectFrames; + return S_OK; + } + HRESULT STDMETHODCALLTYPE IsAudioObjectFormatSupported(const WAVEFORMATEX* format) override { + if (!format) return E_POINTER; + return is_object_format(format) ? S_OK : AUDCLNT_E_UNSUPPORTED_FORMAT; + } + HRESULT STDMETHODCALLTYPE IsSpatialAudioStreamAvailable(REFIID stream, const PROPVARIANT*) override { + return IsEqualIID(stream, __uuidof(ISpatialAudioObjectRenderStream)) ? S_OK + : SPTLAUDCLNT_E_STREAM_NOT_AVAILABLE; + } + HRESULT STDMETHODCALLTYPE ActivateSpatialAudioStream(const PROPVARIANT* params, REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!params) return E_INVALIDARG; + if (!IsEqualIID(riid, __uuidof(ISpatialAudioObjectRenderStream))) { + log_missing_iid_once("ISpatialAudioClient::ActivateSpatialAudioStream", riid); + return E_NOINTERFACE; + } + if (params->vt != VT_BLOB || !params->blob.pBlobData || + params->blob.cbSize < sizeof(SpatialAudioObjectRenderStreamActivationParams)) { + return E_INVALIDARG; + } + SpatialAudioObjectRenderStreamActivationParams p{}; + std::memcpy(&p, params->blob.pBlobData, sizeof p); + if (!p.ObjectFormat || !p.EventHandle) return E_INVALIDARG; + if (!is_object_format(p.ObjectFormat)) return AUDCLNT_E_UNSUPPORTED_FORMAT; + const uint32_t mask = static_cast(p.StaticObjectTypeMask); + if (mask & ~kStaticTypes) return E_INVALIDARG; // AudioObjectType_Dynamic is not a static type + if (p.MinDynamicObjectCount > p.MaxDynamicObjectCount) return E_INVALIDARG; + // Dynamic objects asked for are granted as none available (GetAvailableDynamicObjectCount is 0), so a + // minimum above 0 is accepted rather than refused. + auto* s = new (std::nothrow) SpatialStream(p.EventHandle, mask); + if (!s) return E_OUTOFMEMORY; + if (!s->start_clock()) { + s->Release(); + return E_OUTOFMEMORY; + } + if (InterlockedExchange(&g_spatial_logged, 1) == 0) { + std::fprintf(stderr, + "[rt] audio: silent spatial stream: static objects 0x%x, dynamic objects %u..%u asked " + "(0 available), %u frames a pass\n", + mask, p.MinDynamicObjectCount, p.MaxDynamicObjectCount, kObjectFrames); + } + const HRESULT hr = s->QueryInterface(riid, out); + s->Release(); + return hr; + } + // ISpatialAudioClient2 + HRESULT STDMETHODCALLTYPE IsOffloadCapable(AUDIO_STREAM_CATEGORY, BOOL* capable) override { + if (!capable) return E_POINTER; + *capable = FALSE; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetMaxFrameCountForCategory(AUDIO_STREAM_CATEGORY, BOOL, const WAVEFORMATEX* format, + UINT32* frames) override { + return GetMaxFrameCount(format, frames); + } + +private: + bool answers(REFIID riid) const override { + return IsEqualIID(riid, __uuidof(ISpatialAudioClient)) || IsEqualIID(riid, __uuidof(ISpatialAudioClient2)); + } + static inline LONG g_spatial_logged = 0; +}; + // ---- IPropertyStore ------------------------------------------------------------------------------------------- class PropertyStore final : public Unknown { @@ -676,6 +1036,13 @@ class Device final : public IMMDevice, public IMMEndpoint { HRESULT STDMETHODCALLTYPE Activate(REFIID riid, DWORD, PROPVARIANT*, void** ppv) override { if (!ppv) return E_POINTER; *ppv = nullptr; + if (IsEqualIID(riid, __uuidof(ISpatialAudioClient)) || IsEqualIID(riid, __uuidof(ISpatialAudioClient2))) { + auto* spatial = new (std::nothrow) SpatialClient(); + if (!spatial) return E_OUTOFMEMORY; + const HRESULT hr = spatial->QueryInterface(riid, ppv); + spatial->Release(); + return hr; + } if (!IsEqualIID(riid, __uuidof(IAudioClient)) && !IsEqualIID(riid, __uuidof(IAudioClient2)) && !IsEqualIID(riid, __uuidof(IAudioClient3))) { log_missing_iid_once("IMMDevice::Activate", riid); diff --git a/runtime/shims/silent_audio.h b/runtime/shims/silent_audio.h index db7fa3a7f..779aa5011 100644 --- a/runtime/shims/silent_audio.h +++ b/runtime/shims/silent_audio.h @@ -4,8 +4,9 @@ // endpoint, GetDefaultAudioEndpoint(eRender, ...) fails with 0x80070490 (ERROR_NOT_FOUND); the title's device start // then leaks its own output-device lock and its audio engine never mixes, so the boot stops. A console always has an // output, so the title only meets that path off-console. The enumerator served here answers render questions with a -// device of its own when the host has none (or always, with LEONIDA_AUDIO=silent): an IAudioClient whose clock -// consumes frames in real time and signals the stream's event every period. It never opens a host audio device. +// device of its own when the host has none (or always, with LEONIDA_AUDIO=silent): an ISpatialAudioClient (what the +// title activates) and an IAudioClient, whose streams consume frames in real time and signal their event every +// period. It never opens a host audio device. // Capture questions keep the host's answer. #pragma once diff --git a/runtime/test/silent_audio_test.cpp b/runtime/test/silent_audio_test.cpp index cb9f9b860..eac3121b9 100644 --- a/runtime/test/silent_audio_test.cpp +++ b/runtime/test/silent_audio_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -538,6 +539,147 @@ void test_polled_stream_drains() { c->Release(); } +// ---- the spatial stream --------------------------------------------------------------------------------------- + +void test_spatial_stream() { + IMMDeviceEnumerator* e = serve(nullptr, REGDB_E_CLASSNOTREG, sa::Mode::Auto, nullptr); + IMMDevice* d = nullptr; + if (!e || FAILED(e->GetDefaultAudioEndpoint(eRender, eConsole, &d)) || !d) { + check(false, "silent device for the spatial tests"); + return; + } + e->Release(); + ISpatialAudioClient2* c2 = nullptr; + check(d->Activate(__uuidof(ISpatialAudioClient2), CLSCTX_ALL, nullptr, reinterpret_cast(&c2)) == S_OK && c2, + "Activate(ISpatialAudioClient2)"); + if (c2) c2->Release(); + ISpatialAudioClient* c = nullptr; + check(d->Activate(__uuidof(ISpatialAudioClient), CLSCTX_ALL, nullptr, reinterpret_cast(&c)) == S_OK && c, + "Activate(ISpatialAudioClient)"); + d->Release(); + if (!c) return; + + AudioObjectType mask = AudioObjectType_None; + UINT32 dynamic = 99; + check(c->GetNativeStaticObjectTypeMask(&mask) == S_OK && static_cast(mask) == 0x1FE, + "the native static objects are the 7.1 bed"); + check(c->GetMaxDynamicObjectCount(&dynamic) == S_OK && dynamic == 0, "no dynamic objects"); + float x = 0, y = 0, z = 0; + check(c->GetStaticObjectPosition(AudioObjectType_FrontLeft, &x, &y, &z) == S_OK && x < 0 && z < 0, + "front left is to the left and in front"); + IAudioFormatEnumerator* formats = nullptr; + WAVEFORMATEX* format = nullptr; + UINT32 count = 0; + check(c->GetSupportedAudioObjectFormatEnumerator(&formats) == S_OK && formats && + formats->GetCount(&count) == S_OK && count == 1 && formats->GetFormat(0, &format) == S_OK && format && + format->nChannels == 1 && format->nSamplesPerSec == 48000 && format->wBitsPerSample == 32 && + format->wFormatTag == WAVE_FORMAT_IEEE_FLOAT, + "one object format: mono 48 kHz float"); + if (!format) return; + check(c->IsAudioObjectFormatSupported(format) == S_OK, "IsAudioObjectFormatSupported(its format)"); + WAVEFORMATEX stereo{WAVE_FORMAT_IEEE_FLOAT, 2, 48000, 48000 * 8, 8, 32, 0}; + check(c->IsAudioObjectFormatSupported(&stereo) == AUDCLNT_E_UNSUPPORTED_FORMAT, "a stereo object is refused"); + UINT32 frames = 0; + check(c->GetMaxFrameCount(format, &frames) == S_OK && frames == 480, "GetMaxFrameCount: 480 (10 ms)"); + check(c->IsSpatialAudioStreamAvailable(__uuidof(ISpatialAudioObjectRenderStream), nullptr) == S_OK, + "the object render stream is available"); + + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + SpatialAudioObjectRenderStreamActivationParams params{}; + params.ObjectFormat = format; + params.StaticObjectTypeMask = + static_cast(AudioObjectType_FrontLeft | AudioObjectType_FrontRight | AudioObjectType_LowFrequency); + params.Category = AudioCategory_GameEffects; + params.EventHandle = event; + PROPVARIANT pv; + PropVariantInit(&pv); + pv.vt = VT_BLOB; + pv.blob.cbSize = sizeof params; + pv.blob.pBlobData = reinterpret_cast(¶ms); + ISpatialAudioObjectRenderStream* stream = nullptr; + params.EventHandle = nullptr; + check(c->ActivateSpatialAudioStream(&pv, __uuidof(ISpatialAudioObjectRenderStream), + reinterpret_cast(&stream)) == E_INVALIDARG && !stream, + "a stream without an event handle is refused"); + params.EventHandle = event; + check(c->ActivateSpatialAudioStream(&pv, __uuidof(ISpatialAudioObjectRenderStream), + reinterpret_cast(&stream)) == S_OK && stream, + "ActivateSpatialAudioStream(FL | FR | LFE, event)"); + formats->Release(); + c->Release(); + if (!stream) return; + + UINT32 available = 99; + check(stream->BeginUpdatingAudioObjects(&available, &frames) == S_OK && available == 0 && frames == 480, + "BeginUpdatingAudioObjects: 480 frames, no dynamic objects"); + check(stream->BeginUpdatingAudioObjects(&available, &frames) == SPTLAUDCLNT_E_OUT_OF_ORDER, + "a second Begin is out of order"); + ISpatialAudioObject* fl = nullptr; + ISpatialAudioObject* fr = nullptr; + ISpatialAudioObject* other = nullptr; + check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontLeft, &fl) == S_OK && fl, "activate front left"); + check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontRight, &fr) == S_OK && fr, "activate front right"); + check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontLeft, &other) == SPTLAUDCLNT_E_OBJECT_ALREADY_ACTIVE, + "front left twice is refused"); + check(stream->ActivateSpatialAudioObject(AudioObjectType_BackLeft, &other) == + SPTLAUDCLNT_E_STATIC_OBJECT_NOT_AVAILABLE, + "a type outside the stream's mask is refused"); + check(stream->ActivateSpatialAudioObject(AudioObjectType_Dynamic, &other) == SPTLAUDCLNT_E_NO_MORE_OBJECTS, + "no dynamic object"); + check(stream->EndUpdatingAudioObjects() == S_OK, "EndUpdatingAudioObjects"); + check(stream->EndUpdatingAudioObjects() == SPTLAUDCLNT_E_OUT_OF_ORDER, "a second End is out of order"); + if (!fl || !fr) return; + BYTE* buffer = nullptr; + UINT32 length = 0; + check(fl->GetBuffer(&buffer, &length) == SPTLAUDCLNT_E_OUT_OF_ORDER, "GetBuffer outside an update"); + + check(stream->Start() == S_OK, "Start"); + LARGE_INTEGER f, t0, t1; + QueryPerformanceFrequency(&f); + QueryPerformanceCounter(&t0); + int passes = 0; + bool buffers_ok = true; + for (int i = 0; i < 10; ++i) { + if (WaitForSingleObject(event, 500) != WAIT_OBJECT_0) break; + if (FAILED(stream->BeginUpdatingAudioObjects(&available, &frames))) break; + for (ISpatialAudioObject* o : {fl, fr}) { + buffer = nullptr; + length = 0; + if (FAILED(o->GetBuffer(&buffer, &length)) || !buffer || length != frames * 4) buffers_ok = false; + else std::memset(buffer, 0, length); + o->SetVolume(0.5f); + o->SetPosition(0.0f, 0.0f, -1.0f); + } + if (i == 9) fr->SetEndOfStream(0); + if (SUCCEEDED(stream->EndUpdatingAudioObjects())) ++passes; + } + QueryPerformanceCounter(&t1); + const double seconds = static_cast(t1.QuadPart - t0.QuadPart) / static_cast(f.QuadPart); + std::printf(" spatial: %d passes in %.1f ms\n", passes, seconds * 1000.0); + check(passes == 10, "the spatial event is signalled every pass while running"); + check(seconds > 0.04 && seconds < 2.0, "the passes come at about real time (10 in 40 ms .. 2 s)"); + check(buffers_ok, "every object gets a 480-frame mono float buffer in each pass"); + BOOL active = TRUE; + check(fr->IsActive(&active) == S_OK && !active, "an object is inactive after the pass it ended in"); + check(fl->IsActive(&active) == S_OK && active, "the other object stays active"); + check(stream->Reset() == SPTLAUDCLNT_E_STREAM_NOT_STOPPED, "Reset while running is refused"); + check(stream->Stop() == S_OK, "Stop"); + while (WaitForSingleObject(event, 0) == WAIT_OBJECT_0) { + } + check(WaitForSingleObject(event, 60) == WAIT_TIMEOUT, "no spatial event after Stop"); + check(stream->Reset() == S_OK, "Reset"); + fr->Release(); + if (SUCCEEDED(stream->BeginUpdatingAudioObjects(&available, &frames))) { + check(stream->ActivateSpatialAudioObject(AudioObjectType_FrontRight, &other) == S_OK && other, + "an ended type can be activated again"); + if (other) other->Release(); + stream->EndUpdatingAudioObjects(); + } + fl->Release(); + check(stream->Release() == 0, "the stream is released last"); + CloseHandle(event); +} + // ---- through CoCreateInstance --------------------------------------------------------------------------------- using CoCreateInstFn = HRESULT(WINAPI*)(REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID*); @@ -579,6 +721,7 @@ int main() { test_no_host_enumerator(); test_render_stream(); test_polled_stream_drains(); + test_spatial_stream(); test_co_create_instance_forced(); std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); return g_failures ? 1 : 0;