startup: add a WASAPI render sink and the startup_audio_output fixture #1243

Merged
tedin7 merged 2 commits from upstream-pr/1250 into main 2026-11-24 05:58:38 +00:00
tedin7 commented 2026-11-24 05:28:14 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:28:14Z.


What

  • src/startup_stubs/audio_sink.{h,cpp}: desktop WASAPI shared-mode render sink. Default endpoint via IMMDeviceEnumerator, mix format from GetMixFormat (32-bit float or 16-bit PCM only, anything else is a skip), IAudioRenderClient to write, GetCurrentPadding and IAudioClock::GetPosition to observe consumption. One call, submit(format, frames, bytes), converts the block to the mix format. It records the first accepted block, submitted format, per-block frame counts and peaks, consumed frames, drained interval, recovery, and a glitch count kept separate (the render API exposes no discontinuity flag, so it reports "not available").
  • tests/startup_audio_output.cpp (CTest startup_audio_output, exit 77 = capability skip): (a) no submission, (b) eight generated 40 ms tone blocks with distinct amplitudes including one all-zero block that must be accepted and counted, (c) producer starvation: drain to padding 0, hold 300 ms, resume, consumption recovers. All waits are bounded; CTest TIMEOUT 60.
  • docs/startup-runtime.md: short "Audio output" section.

Why

First slice of #1145: a real desktop buffer submission and consumption record that separates absent output, valid silent samples and producer starvation. Fixtures are generated tones only.

Tested

Commands on Windows:

ctest --preset release --no-tests=error -R '^startup_audio_output$' -V
ctest --preset dev --no-tests=error -R '^startup_audio_output$' -V

Run here (Linux host): the pure helpers (conversion, silence detection, drained/recovery arithmetic) built with g++ -std=c++17 and -std=c++20 and ran clean; python3 -B tests/docs_links_check.py and tests/bidi_controls_check.py passed.

NOT run: nothing that touches Windows. audio_sink.cpp, tests/startup_audio_output.cpp and the CMake registration were never compiled with MSVC and the fixture was never run against an endpoint. Please treat the Windows results (endpoint, format, build, per-case counters) as still to be reported.

Not included: no capture-path verification of the generated tone, and no decoding of the console audio command queue (xapu.cpp is unchanged; its payload layout is still unknown).

Refs #1145

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6575313657 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:28:14Z. --- ## What - `src/startup_stubs/audio_sink.{h,cpp}`: desktop WASAPI shared-mode render sink. Default endpoint via `IMMDeviceEnumerator`, mix format from `GetMixFormat` (32-bit float or 16-bit PCM only, anything else is a skip), `IAudioRenderClient` to write, `GetCurrentPadding` and `IAudioClock::GetPosition` to observe consumption. One call, `submit(format, frames, bytes)`, converts the block to the mix format. It records the first accepted block, submitted format, per-block frame counts and peaks, consumed frames, drained interval, recovery, and a glitch count kept separate (the render API exposes no discontinuity flag, so it reports "not available"). - `tests/startup_audio_output.cpp` (CTest `startup_audio_output`, exit 77 = capability skip): (a) no submission, (b) eight generated 40 ms tone blocks with distinct amplitudes including one all-zero block that must be accepted and counted, (c) producer starvation: drain to padding 0, hold 300 ms, resume, consumption recovers. All waits are bounded; CTest TIMEOUT 60. - `docs/startup-runtime.md`: short "Audio output" section. ## Why First slice of #1145: a real desktop buffer submission and consumption record that separates absent output, valid silent samples and producer starvation. Fixtures are generated tones only. ## Tested Commands on Windows: ```powershell ctest --preset release --no-tests=error -R '^startup_audio_output$' -V ctest --preset dev --no-tests=error -R '^startup_audio_output$' -V ``` Run here (Linux host): the pure helpers (conversion, silence detection, drained/recovery arithmetic) built with `g++ -std=c++17` and `-std=c++20` and ran clean; `python3 -B tests/docs_links_check.py` and `tests/bidi_controls_check.py` passed. NOT run: nothing that touches Windows. `audio_sink.cpp`, `tests/startup_audio_output.cpp` and the CMake registration were never compiled with MSVC and the fixture was never run against an endpoint. Please treat the Windows results (endpoint, format, build, per-case counters) as still to be reported. Not included: no capture-path verification of the generated tone, and no decoding of the console audio command queue (`xapu.cpp` is unchanged; its payload layout is still unknown). Refs #1145
upstream-sync closed this pull request 2026-11-24 06:47:18 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 06:47:18 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:38:40Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 89d860cfeb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034240257 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#pullrequestreview-6034240257). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:38:40Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `89d860cfeb` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
tedin7 commented 2026-11-24 06:47:18 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:39:56Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034249743 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#pullrequestreview-6034249743). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:39:56Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:47:18 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:39:58Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034249955 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#pullrequestreview-6034249955). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:39:58Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:47:19 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:40:00Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6034250159 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#pullrequestreview-6034250159). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:40:00Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:50:27 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:30:52Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207, AMD Ryzen 5 PRO 5650U) at HEAD 89d860cfeb8097a285d01107e4367b5476e96438:

  • Debug (--preset dev):
    • cmake --build --preset dev --target startup_audio_output -- -j 6: built cleanly ([3/3] Linking CXX executable startup_audio_output.exe).
    • ctest --preset dev --no-tests=error -R "^startup_audio_output$" -V:
      • pure checks: conversion, silence detection and drained/recovery arithmetic ok
      • SKIP (capability): no default render endpoint, hr=-2147023728 (0x80070490, headless VM has no audio render endpoint)
      • windows: 10.0 build 26100
      • Result: 1/1 Test #53: startup_audio_output .............***Skipped 0.05 sec (exit code 0, clean capability skip 77).
  • Release (--preset release):
    • cmake --build --preset release --target startup_audio_output -- -j 6: built cleanly ([3/3] Linking CXX executable startup_audio_output.exe).
    • ctest --preset release --no-tests=error -R "^startup_audio_output$" -V:
      • pure checks: conversion, silence detection and drained/recovery arithmetic ok
      • SKIP (capability): no default render endpoint, hr=-2147023728
      • windows: 10.0 build 26100
      • Result: 1/1 Test #53: startup_audio_output .............***Skipped 0.02 sec (exit code 0, clean capability skip 77).
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7123018347 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#issuecomment-7123018347). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:30:52Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207, AMD Ryzen 5 PRO 5650U) at HEAD `89d860cfeb8097a285d01107e4367b5476e96438`: - **Debug (`--preset dev`)**: - `cmake --build --preset dev --target startup_audio_output -- -j 6`: built cleanly (`[3/3] Linking CXX executable startup_audio_output.exe`). - `ctest --preset dev --no-tests=error -R "^startup_audio_output$" -V`: - `pure checks: conversion, silence detection and drained/recovery arithmetic ok` - `SKIP (capability): no default render endpoint, hr=-2147023728` (`0x80070490`, headless VM has no audio render endpoint) - `windows: 10.0 build 26100` - Result: `1/1 Test #53: startup_audio_output .............***Skipped 0.05 sec` (exit code 0, clean capability skip 77). - **Release (`--preset release`)**: - `cmake --build --preset release --target startup_audio_output -- -j 6`: built cleanly (`[3/3] Linking CXX executable startup_audio_output.exe`). - `ctest --preset release --no-tests=error -R "^startup_audio_output$" -V`: - `pure checks: conversion, silence detection and drained/recovery arithmetic ok` - `SKIP (capability): no default render endpoint, hr=-2147023728` - `windows: 10.0 build 26100` - Result: `1/1 Test #53: startup_audio_output .............***Skipped 0.02 sec` (exit code 0, clean capability skip 77).
chatgpt-codex-connector[bot commented 2026-11-24 06:50:27 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:32:39Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T05:38:43.593955Z 89d860c Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7123046536 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#issuecomment-7123046536). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:32:39Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"89d860cfeb8097a285d01107e4367b5476e96438","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-24T05:38:43.593955Z">2026-11-24T05:38:43.593955Z</relative-time> | `89d860c` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
tedin7 commented 2026-11-24 06:50:28 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:43:34Z.


Verified on Windows Server 2025 (build 26100, MSVC 14.44, sccache) at commit 16a5a077872411f3ccd7418456b9ed72960de78e.

Commands:

  • cmake --preset dev + cmake --build --preset dev --target startup_audio_output (4.3s build, 5.97s dev total)
  • ctest --preset dev -R "^startup_audio_output$" -V
  • cmake --preset release + cmake --build --preset release --target startup_audio_output (1.88s build, 3.44s release total)
  • ctest --preset release -R "^startup_audio_output$" -V

Result (dev and release):

  • pure checks: conversion, silence detection and drained/recovery arithmetic ok
  • SKIP (capability): no default render endpoint, hr=-2147023728
  • CTest exited 0 (100% tests passed out of 1, 1 skipped due to no default render endpoint on this headless Server 2025 VM).
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7123215096 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#issuecomment-7123215096). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:43:34Z. --- Verified on Windows Server 2025 (build 26100, MSVC 14.44, `sccache`) at commit `16a5a077872411f3ccd7418456b9ed72960de78e`. Commands: - `cmake --preset dev` + `cmake --build --preset dev --target startup_audio_output` (4.3s build, 5.97s dev total) - `ctest --preset dev -R "^startup_audio_output$" -V` - `cmake --preset release` + `cmake --build --preset release --target startup_audio_output` (1.88s build, 3.44s release total) - `ctest --preset release -R "^startup_audio_output$" -V` Result (`dev` and `release`): - `pure checks: conversion, silence detection and drained/recovery arithmetic ok` - `SKIP (capability): no default render endpoint, hr=-2147023728` - CTest exited 0 (`100% tests passed out of 1`, 1 skipped due to no default render endpoint on this headless Server 2025 VM).
chatgpt-codex-connector[bot commented 2026-11-24 06:50:43 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:38:40Z.

Code review location: docs/startup-runtime.md; line 182

@@ -162,7 +162,34 @@ These are measured on one executable; treat them as hypotheses for others.
   support, MIN/MAX with factors other than ONE). Its draws match a CPU model of the register fields
   (`ctest --preset release --no-tests=error -R "^startup_cb_blend"`). Where those registers sit in the
   state block is not measured yet, so the draw path doesn't call it.
-- Audio produces no output.
+- Audio produces no output from the console audio path. A separate desktop render sink exists
+  (see "Audio output"); nothing connects the console path to it yet.
+
+## Audio output
+
+`src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the
+default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only),
+converts each submitted block (format, frame count, bytes) to it, and writes it through
+`IAudioRenderClient`. Consumed frames are the submitted frames minus `GetCurrentPadding`; the
+`IAudioClock` position is reported next to them. It records the first accepted block, the
+submitted format, per-block frame counts and peak amplitude, the drained interval (queue empty
+while the producer withholds data) and the recovery (resume until consumption advances). The
+render API reports no discontinuity flag, so the glitch count is "not available" and is kept
+apart from both intervals.
+
+```powershell
+cmake --build --preset release --target startup_audio_output
+ctest --preset release --no-tests=error -R '^startup_audio_output$' -V

P1 Badge Register the audio fixture in the required experiment docs

This introduces a public render capability and reproduction commands, but the commit updates neither the README experiment table nor docs/experiments.md. AGENTS.md requires updating those entry points when public capabilities or reproduction commands change, and CONTRIBUTING.md specifically requires the README entry and experiment reproduction details. Add the fixture, capability-skip behavior, and limitations there so contributors following the prescribed experiment index can discover and reproduce it.

AGENTS.md reference: AGENTS.md:L176-L177

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675958167 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#discussion_r4675958167). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:38:40Z. **Code review location:** `docs/startup-runtime.md`; line 182 ~~~~diff @@ -162,7 +162,34 @@ These are measured on one executable; treat them as hypotheses for others. support, MIN/MAX with factors other than ONE). Its draws match a CPU model of the register fields (`ctest --preset release --no-tests=error -R "^startup_cb_blend"`). Where those registers sit in the state block is not measured yet, so the draw path doesn't call it. -- Audio produces no output. +- Audio produces no output from the console audio path. A separate desktop render sink exists + (see "Audio output"); nothing connects the console path to it yet. + +## Audio output + +`src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the +default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), +converts each submitted block (format, frame count, bytes) to it, and writes it through +`IAudioRenderClient`. Consumed frames are the submitted frames minus `GetCurrentPadding`; the +`IAudioClock` position is reported next to them. It records the first accepted block, the +submitted format, per-block frame counts and peak amplitude, the drained interval (queue empty +while the producer withholds data) and the recovery (resume until consumption advances). The +render API reports no discontinuity flag, so the glitch count is "not available" and is kept +apart from both intervals. + +```powershell +cmake --build --preset release --target startup_audio_output +ctest --preset release --no-tests=error -R '^startup_audio_output$' -V ~~~~ --- **<sub><sub>![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)</sub></sub> Register the audio fixture in the required experiment docs** This introduces a public render capability and reproduction commands, but the commit updates neither the README experiment table nor `docs/experiments.md`. `AGENTS.md` requires updating those entry points when public capabilities or reproduction commands change, and `CONTRIBUTING.md` specifically requires the README entry and experiment reproduction details. Add the fixture, capability-skip behavior, and limitations there so contributors following the prescribed experiment index can discover and reproduce it. AGENTS.md reference: [AGENTS.md:L176-L177](https://github.com/R0Y00/Xbox2Windows/blob/89d860cfeb8097a285d01107e4367b5476e96438/AGENTS.md#L176-L177) Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:43 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:38:40Z.

Code review location: src/startup_stubs/audio_sink.cpp; line 101

@@ -0,0 +1,157 @@
+#include "startup_stubs/audio_sink.h"
+
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <objbase.h>
+#include <mmreg.h>
+#include <audioclient.h>
+#include <mmdeviceapi.h>
+#include <wrl/client.h>
+
+namespace x2w_audio {
+
+using Microsoft::WRL::ComPtr;
+
+struct AudioSink::Impl {
+    ComPtr<IAudioClient> client;
+    ComPtr<IAudioRenderClient> render;
+    ComPtr<IAudioClock> clock;
+    UINT64 clock_freq = 1;
+};
+
+AudioSink::AudioSink() = default;
+
+AudioSink::~AudioSink()
+{
+    if (p_ && p_->client) p_->client->Stop();
+}
+
+static std::string friendly_name(IMMDevice* dev)
+{
+    // PKEY_Device_FriendlyName, spelled out to avoid the property-key header link requirements.
+    const PROPERTYKEY key = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14};
+    ComPtr<IPropertyStore> props;
+    PROPVARIANT v;
+    PropVariantInit(&v);
+    std::string out = "(unnamed endpoint)";
+    if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &props)) && SUCCEEDED(props->GetValue(key, &v)) &&
+        v.vt == VT_LPWSTR && v.pwszVal) {
+        char buf[256] = {};
+        if (WideCharToMultiByte(CP_UTF8, 0, v.pwszVal, -1, buf, sizeof(buf) - 1, nullptr, nullptr) > 0) out = buf;
+    }
+    PropVariantClear(&v);
+    return out;
+}
+
+// Accepts 32-bit float and 16-bit PCM mix formats (extensible or plain).
+static bool mix_kind(const WAVEFORMATEX* wf, SampleKind& kind)
+{
+    WORD tag = wf->wFormatTag;
+    if (tag == WAVE_FORMAT_EXTENSIBLE && wf->cbSize >= 22)
+        tag = static_cast<WORD>(reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(wf)->SubFormat.Data1);
+    if (tag == WAVE_FORMAT_IEEE_FLOAT && wf->wBitsPerSample == 32) kind = SampleKind::Float32;
+    else if (tag == WAVE_FORMAT_PCM && wf->wBitsPerSample == 16) kind = SampleKind::Pcm16;
+    else return false;
+    return true;
+}
+
+std::string AudioSink::open()
+{
+    auto impl = std::make_unique<Impl>();
+    ComPtr<IMMDeviceEnumerator> en;
+    ComPtr<IMMDevice> dev;
+    HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en));
+    if (FAILED(hr)) return "no device enumerator, hr=" + std::to_string(static_cast<long>(hr));
+    hr = en->GetDefaultAudioEndpoint(eRender, eConsole, &dev);
+    if (FAILED(hr)) return "no default render endpoint, hr=" + std::to_string(static_cast<long>(hr));
+    endpoint_ = friendly_name(dev.Get());
+    hr = dev->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(impl->client.GetAddressOf()));
+    if (FAILED(hr)) return "endpoint activation failed, hr=" + std::to_string(static_cast<long>(hr));
+    WAVEFORMATEX* wf = nullptr;
+    hr = impl->client->GetMixFormat(&wf);
+    if (FAILED(hr) || !wf) return "GetMixFormat failed, hr=" + std::to_string(static_cast<long>(hr));
+    SampleKind kind = SampleKind::Float32;
+    const bool ok = mix_kind(wf, kind);
+    if (!ok) {
+        const std::string s = "unsupported mix format tag=" + std::to_string(wf->wFormatTag) +
+                              " bits=" + std::to_string(wf->wBitsPerSample);
+        CoTaskMemFree(wf);
+        return s;
+    }
+    mix_ = {kind, wf->nChannels, wf->nSamplesPerSec};
+    constexpr REFERENCE_TIME buffer_100ns = 5000000;  // 500 ms
+    hr = impl->client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, buffer_100ns, 0, wf, nullptr);
+    CoTaskMemFree(wf);
+    if (FAILED(hr)) return "IAudioClient::Initialize failed, hr=" + std::to_string(static_cast<long>(hr));
+    UINT32 frames = 0;
+    if (FAILED(impl->client->GetBufferSize(&frames)) || FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->render))) ||
+        FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->clock))) || FAILED(impl->clock->GetFrequency(&impl->clock_freq)))
+        return "endpoint services unavailable";
+    buffer_frames_ = frames;
+    p_ = std::move(impl);
+    return {};
+}
+
+uint32_t AudioSink::padding()
+{
+    UINT32 pad = 0;
+    if (p_) p_->client->GetCurrentPadding(&pad);
+    return pad;

P2 Badge Distinguish padding-query failures from an empty queue

If the Windows endpoint is invalidated while audio remains queued, GetCurrentPadding can fail with AUDCLNT_E_DEVICE_INVALIDATED, but its HRESULT is discarded and pad can remain zero. observe() then counts every submitted frame as consumed and can mark recovery complete; an invalidation immediately after case (c)'s resume submission can therefore satisfy its assertions without consuming that block. Propagate the query failure and make the fixture reject the observation instead of advancing consumption and starvation measurements.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675958173 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#discussion_r4675958173). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:38:40Z. **Code review location:** `src/startup_stubs/audio_sink.cpp`; line 101 ~~~~diff @@ -0,0 +1,157 @@ +#include "startup_stubs/audio_sink.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <objbase.h> +#include <mmreg.h> +#include <audioclient.h> +#include <mmdeviceapi.h> +#include <wrl/client.h> + +namespace x2w_audio { + +using Microsoft::WRL::ComPtr; + +struct AudioSink::Impl { + ComPtr<IAudioClient> client; + ComPtr<IAudioRenderClient> render; + ComPtr<IAudioClock> clock; + UINT64 clock_freq = 1; +}; + +AudioSink::AudioSink() = default; + +AudioSink::~AudioSink() +{ + if (p_ && p_->client) p_->client->Stop(); +} + +static std::string friendly_name(IMMDevice* dev) +{ + // PKEY_Device_FriendlyName, spelled out to avoid the property-key header link requirements. + const PROPERTYKEY key = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14}; + ComPtr<IPropertyStore> props; + PROPVARIANT v; + PropVariantInit(&v); + std::string out = "(unnamed endpoint)"; + if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &props)) && SUCCEEDED(props->GetValue(key, &v)) && + v.vt == VT_LPWSTR && v.pwszVal) { + char buf[256] = {}; + if (WideCharToMultiByte(CP_UTF8, 0, v.pwszVal, -1, buf, sizeof(buf) - 1, nullptr, nullptr) > 0) out = buf; + } + PropVariantClear(&v); + return out; +} + +// Accepts 32-bit float and 16-bit PCM mix formats (extensible or plain). +static bool mix_kind(const WAVEFORMATEX* wf, SampleKind& kind) +{ + WORD tag = wf->wFormatTag; + if (tag == WAVE_FORMAT_EXTENSIBLE && wf->cbSize >= 22) + tag = static_cast<WORD>(reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(wf)->SubFormat.Data1); + if (tag == WAVE_FORMAT_IEEE_FLOAT && wf->wBitsPerSample == 32) kind = SampleKind::Float32; + else if (tag == WAVE_FORMAT_PCM && wf->wBitsPerSample == 16) kind = SampleKind::Pcm16; + else return false; + return true; +} + +std::string AudioSink::open() +{ + auto impl = std::make_unique<Impl>(); + ComPtr<IMMDeviceEnumerator> en; + ComPtr<IMMDevice> dev; + HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en)); + if (FAILED(hr)) return "no device enumerator, hr=" + std::to_string(static_cast<long>(hr)); + hr = en->GetDefaultAudioEndpoint(eRender, eConsole, &dev); + if (FAILED(hr)) return "no default render endpoint, hr=" + std::to_string(static_cast<long>(hr)); + endpoint_ = friendly_name(dev.Get()); + hr = dev->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(impl->client.GetAddressOf())); + if (FAILED(hr)) return "endpoint activation failed, hr=" + std::to_string(static_cast<long>(hr)); + WAVEFORMATEX* wf = nullptr; + hr = impl->client->GetMixFormat(&wf); + if (FAILED(hr) || !wf) return "GetMixFormat failed, hr=" + std::to_string(static_cast<long>(hr)); + SampleKind kind = SampleKind::Float32; + const bool ok = mix_kind(wf, kind); + if (!ok) { + const std::string s = "unsupported mix format tag=" + std::to_string(wf->wFormatTag) + + " bits=" + std::to_string(wf->wBitsPerSample); + CoTaskMemFree(wf); + return s; + } + mix_ = {kind, wf->nChannels, wf->nSamplesPerSec}; + constexpr REFERENCE_TIME buffer_100ns = 5000000; // 500 ms + hr = impl->client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, buffer_100ns, 0, wf, nullptr); + CoTaskMemFree(wf); + if (FAILED(hr)) return "IAudioClient::Initialize failed, hr=" + std::to_string(static_cast<long>(hr)); + UINT32 frames = 0; + if (FAILED(impl->client->GetBufferSize(&frames)) || FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->render))) || + FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->clock))) || FAILED(impl->clock->GetFrequency(&impl->clock_freq))) + return "endpoint services unavailable"; + buffer_frames_ = frames; + p_ = std::move(impl); + return {}; +} + +uint32_t AudioSink::padding() +{ + UINT32 pad = 0; + if (p_) p_->client->GetCurrentPadding(&pad); + return pad; ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Distinguish padding-query failures from an empty queue** If the Windows endpoint is invalidated while audio remains queued, `GetCurrentPadding` can fail with `AUDCLNT_E_DEVICE_INVALIDATED`, but its HRESULT is discarded and `pad` can remain zero. `observe()` then counts every submitted frame as consumed and can mark recovery complete; an invalidation immediately after case (c)'s resume submission can therefore satisfy its assertions without consuming that block. Propagate the query failure and make the fixture reject the observation instead of advancing consumption and starvation measurements. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:43 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:38:40Z.

Code review location: tests/startup_audio_output.cpp; line 138

@@ -0,0 +1,140 @@
+// Source-built WASAPI render fixture (Refs #1145). Three cases against the default endpoint:
+// (a) no submission, (b) a continuous stream with one silent block, (c) producer starvation.
+// Exit 77 when there is no usable render endpoint. Capture-path verification is not included.
+#include "startup_audio_pure_check.h"
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <objbase.h>
+
+using namespace x2w_audio;
+
+namespace {
+
+int fail(const char* what, int code)
+{
+    std::printf("FAIL: %s\n", what);
+    return code;
+}
+
+void print_report(const char* name, const Report& r)
+{
+    std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu "
+                "unsupported=%u rejected_full=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n",
+                name, static_cast<long long>(r.first_block), r.frames.size(), static_cast<unsigned long long>(r.submitted_frames),
+                static_cast<unsigned long long>(r.consumed_frames), static_cast<unsigned long long>(r.clock_frames),
+                r.unsupported, r.rejected_full, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available");
+}
+
+// Polls until done() holds or ms elapse; every wait in this fixture goes through here.
+template <class F>
+bool wait_for(AudioSink& s, double ms, F done)
+{
+    const double end = now_ms() + ms;
+    for (;;) {
+        s.observe(false);
+        if (done()) return true;
+        if (now_ms() > end) return false;
+        Sleep(2);
+    }
+}
+
+// Retries a block while the endpoint buffer is full, for at most two seconds.
+Submit send(AudioSink& s, const std::vector<int16_t>& pcm, const BlockFormat& fmt)
+{
+    const double end = now_ms() + 2000;
+    for (;;) {
+        const Submit r = s.submit(fmt, static_cast<uint32_t>(pcm.size()), pcm.data());
+        if (r != Submit::Full || now_ms() > end) return r;
+        Sleep(2);
+        s.observe(false);
+    }
+}
+
+void print_windows_build()
+{
+    using Fn = LONG(WINAPI*)(OSVERSIONINFOW*);
+    OSVERSIONINFOW v{sizeof(v)};
+    const auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion")));
+    if (fn && fn(&v) == 0) std::printf("windows: %lu.%lu build %lu\n", v.dwMajorVersion, v.dwMinorVersion, v.dwBuildNumber);
+    else std::puts("windows: build unknown");
+}
+
+int skip(const std::string& why)
+{
+    std::printf("SKIP (capability): %s\n", why.c_str());
+    print_windows_build();
+    return 77;
+}
+
+}  // namespace
+
+int main()
+{
+    if (const int rc = check_pure()) return fail("pure helper checks", rc);
+    if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return skip("COM initialisation failed");
+
+    AudioSink a;
+    if (const std::string why = a.open(); !why.empty()) return skip(why);
+    print_windows_build();
+    const BlockFormat mix = a.mix_format();
+    std::printf("endpoint: %s, mix %s %u ch %u Hz, buffer %u frames\n", a.endpoint().c_str(),
+                mix.kind == SampleKind::Float32 ? "float32" : "pcm16", mix.channels, mix.rate, a.buffer_frames());
+
+    // (a) No submission: nothing accepted, nothing consumed.
+    wait_for(a, 300, [] { return false; });
+    const Report ra = a.report();
+    print_report("case a (no submission)", ra);
+    if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0)
+        return fail("case a reported accepted or consumed frames without a submission", 1);
+
+    // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros.
+    const BlockFormat src{SampleKind::Pcm16, 1, mix.rate};
+    const uint32_t block = mix.rate / 25;
+    AudioSink b;
+    if (const std::string why = b.open(); !why.empty()) return skip(why);
+    for (int i = 0; i < 8; ++i) {
+        const auto pcm = make_tone(mix.rate, block, 220.0 * (i + 1), i == 3 ? 0.0 : 0.1 + 0.07 * i);
+        const Submit r = send(b, pcm, src);
+        if (r == Submit::Unsupported) return skip("block format cannot be converted to the endpoint format");
+        if (r != Submit::Accepted) return fail("case b block not accepted", 2);
+    }
+    wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; });
+    const Report rb = b.report();
+    print_report("case b (continuous with silence)", rb);
+    if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3);
+    for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3);
+    if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4);
+    if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5);
+    for (int i = 0; i < 8; ++i)
+        for (int j = i + 1; j < 8; ++j)
+            if (rb.peaks[i] == rb.peaks[j]) return fail("case b blocks are not distinguishable", 5);
+
+    // (c) Starvation: let the queue drain, hold, resume.
+    AudioSink c;
+    if (const std::string why = c.open(); !why.empty()) return skip(why);
+    for (int i = 0; i < 2; ++i)
+        if (send(c, make_tone(mix.rate, block, 330.0 + 110 * i, 0.4), src) != Submit::Accepted) return fail("case c first blocks", 6);
+    if (!wait_for(c, 3000, [&] { return c.padding() == 0 && c.report().consumed_frames == 2ull * block; }))
+        return fail("case c queue did not drain", 7);
+    for (const double hold_end = now_ms() + 300; now_ms() < hold_end;) {
+        c.observe(true);
+        Sleep(2);
+    }
+    if (c.padding() != 0) return fail("case c queue refilled while withheld", 7);
+    if (send(c, make_tone(mix.rate, block, 550.0, 0.4), src) != Submit::Accepted) return fail("case c resume block", 8);
+    wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; });
+    const Report rc = c.report();
+    print_report("case c (starvation)", rc);
+    if (rc.drained_ms < 250) return fail("case c drained interval too short", 9);
+    if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10);
+    if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10);
+    std::puts("startup_audio_output: PASS (no capture-path verification; glitch count not available from the render API)");
+    CoUninitialize();

P2 Badge Destroy the audio sinks before uninitializing COM

On the successful Windows path, a, b, and c are still alive when this call uninitializes COM. They are destroyed only as main returns, and AudioSink::~AudioSink() still calls IAudioClient::Stop() before its ComPtr members release the interfaces. Those operations therefore occur after COM teardown and can fail or crash during shutdown despite the fixture having printed PASS. Put the sinks in an inner scope, or use a COM lifetime guard declared before them, so all interfaces are stopped and released before CoUninitialize().

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675958176 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#discussion_r4675958176). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:38:40Z. **Code review location:** `tests/startup_audio_output.cpp`; line 138 ~~~~diff @@ -0,0 +1,140 @@ +// Source-built WASAPI render fixture (Refs #1145). Three cases against the default endpoint: +// (a) no submission, (b) a continuous stream with one silent block, (c) producer starvation. +// Exit 77 when there is no usable render endpoint. Capture-path verification is not included. +#include "startup_audio_pure_check.h" + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <objbase.h> + +using namespace x2w_audio; + +namespace { + +int fail(const char* what, int code) +{ + std::printf("FAIL: %s\n", what); + return code; +} + +void print_report(const char* name, const Report& r) +{ + std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " + "unsupported=%u rejected_full=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", + name, static_cast<long long>(r.first_block), r.frames.size(), static_cast<unsigned long long>(r.submitted_frames), + static_cast<unsigned long long>(r.consumed_frames), static_cast<unsigned long long>(r.clock_frames), + r.unsupported, r.rejected_full, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); +} + +// Polls until done() holds or ms elapse; every wait in this fixture goes through here. +template <class F> +bool wait_for(AudioSink& s, double ms, F done) +{ + const double end = now_ms() + ms; + for (;;) { + s.observe(false); + if (done()) return true; + if (now_ms() > end) return false; + Sleep(2); + } +} + +// Retries a block while the endpoint buffer is full, for at most two seconds. +Submit send(AudioSink& s, const std::vector<int16_t>& pcm, const BlockFormat& fmt) +{ + const double end = now_ms() + 2000; + for (;;) { + const Submit r = s.submit(fmt, static_cast<uint32_t>(pcm.size()), pcm.data()); + if (r != Submit::Full || now_ms() > end) return r; + Sleep(2); + s.observe(false); + } +} + +void print_windows_build() +{ + using Fn = LONG(WINAPI*)(OSVERSIONINFOW*); + OSVERSIONINFOW v{sizeof(v)}; + const auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion"))); + if (fn && fn(&v) == 0) std::printf("windows: %lu.%lu build %lu\n", v.dwMajorVersion, v.dwMinorVersion, v.dwBuildNumber); + else std::puts("windows: build unknown"); +} + +int skip(const std::string& why) +{ + std::printf("SKIP (capability): %s\n", why.c_str()); + print_windows_build(); + return 77; +} + +} // namespace + +int main() +{ + if (const int rc = check_pure()) return fail("pure helper checks", rc); + if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return skip("COM initialisation failed"); + + AudioSink a; + if (const std::string why = a.open(); !why.empty()) return skip(why); + print_windows_build(); + const BlockFormat mix = a.mix_format(); + std::printf("endpoint: %s, mix %s %u ch %u Hz, buffer %u frames\n", a.endpoint().c_str(), + mix.kind == SampleKind::Float32 ? "float32" : "pcm16", mix.channels, mix.rate, a.buffer_frames()); + + // (a) No submission: nothing accepted, nothing consumed. + wait_for(a, 300, [] { return false; }); + const Report ra = a.report(); + print_report("case a (no submission)", ra); + if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0) + return fail("case a reported accepted or consumed frames without a submission", 1); + + // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros. + const BlockFormat src{SampleKind::Pcm16, 1, mix.rate}; + const uint32_t block = mix.rate / 25; + AudioSink b; + if (const std::string why = b.open(); !why.empty()) return skip(why); + for (int i = 0; i < 8; ++i) { + const auto pcm = make_tone(mix.rate, block, 220.0 * (i + 1), i == 3 ? 0.0 : 0.1 + 0.07 * i); + const Submit r = send(b, pcm, src); + if (r == Submit::Unsupported) return skip("block format cannot be converted to the endpoint format"); + if (r != Submit::Accepted) return fail("case b block not accepted", 2); + } + wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; }); + const Report rb = b.report(); + print_report("case b (continuous with silence)", rb); + if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); + for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3); + if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4); + if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5); + for (int i = 0; i < 8; ++i) + for (int j = i + 1; j < 8; ++j) + if (rb.peaks[i] == rb.peaks[j]) return fail("case b blocks are not distinguishable", 5); + + // (c) Starvation: let the queue drain, hold, resume. + AudioSink c; + if (const std::string why = c.open(); !why.empty()) return skip(why); + for (int i = 0; i < 2; ++i) + if (send(c, make_tone(mix.rate, block, 330.0 + 110 * i, 0.4), src) != Submit::Accepted) return fail("case c first blocks", 6); + if (!wait_for(c, 3000, [&] { return c.padding() == 0 && c.report().consumed_frames == 2ull * block; })) + return fail("case c queue did not drain", 7); + for (const double hold_end = now_ms() + 300; now_ms() < hold_end;) { + c.observe(true); + Sleep(2); + } + if (c.padding() != 0) return fail("case c queue refilled while withheld", 7); + if (send(c, make_tone(mix.rate, block, 550.0, 0.4), src) != Submit::Accepted) return fail("case c resume block", 8); + wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; }); + const Report rc = c.report(); + print_report("case c (starvation)", rc); + if (rc.drained_ms < 250) return fail("case c drained interval too short", 9); + if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10); + if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10); + std::puts("startup_audio_output: PASS (no capture-path verification; glitch count not available from the render API)"); + CoUninitialize(); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Destroy the audio sinks before uninitializing COM** On the successful Windows path, `a`, `b`, and `c` are still alive when this call uninitializes COM. They are destroyed only as `main` returns, and `AudioSink::~AudioSink()` still calls `IAudioClient::Stop()` before its `ComPtr` members release the interfaces. Those operations therefore occur after COM teardown and can fail or crash during shutdown despite the fixture having printed PASS. Put the sinks in an inner scope, or use a COM lifetime guard declared before them, so all interfaces are stopped and released before `CoUninitialize()`. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 06:50:44 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:39:56Z.

Code review location: docs/startup-runtime.md; line 182

@@ -162,7 +162,34 @@ These are measured on one executable; treat them as hypotheses for others.
   support, MIN/MAX with factors other than ONE). Its draws match a CPU model of the register fields
   (`ctest --preset release --no-tests=error -R "^startup_cb_blend"`). Where those registers sit in the
   state block is not measured yet, so the draw path doesn't call it.
-- Audio produces no output.
+- Audio produces no output from the console audio path. A separate desktop render sink exists
+  (see "Audio output"); nothing connects the console path to it yet.
+
+## Audio output
+
+`src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the
+default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only),
+converts each submitted block (format, frame count, bytes) to it, and writes it through
+`IAudioRenderClient`. Consumed frames are the submitted frames minus `GetCurrentPadding`; the
+`IAudioClock` position is reported next to them. It records the first accepted block, the
+submitted format, per-block frame counts and peak amplitude, the drained interval (queue empty
+while the producer withholds data) and the recovery (resume until consumption advances). The
+render API reports no discontinuity flag, so the glitch count is "not available" and is kept
+apart from both intervals.
+
+```powershell
+cmake --build --preset release --target startup_audio_output
+ctest --preset release --no-tests=error -R '^startup_audio_output$' -V

Fixed in 16a5a077: README experiment table row added, and a "Desktop audio render sink" section in docs/experiments.md (fixture, command, capability-skip meaning, what is not covered; no endpoint run is recorded there yet).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675966205 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#discussion_r4675966205). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:39:56Z. **Code review location:** `docs/startup-runtime.md`; line 182 ~~~~diff @@ -162,7 +162,34 @@ These are measured on one executable; treat them as hypotheses for others. support, MIN/MAX with factors other than ONE). Its draws match a CPU model of the register fields (`ctest --preset release --no-tests=error -R "^startup_cb_blend"`). Where those registers sit in the state block is not measured yet, so the draw path doesn't call it. -- Audio produces no output. +- Audio produces no output from the console audio path. A separate desktop render sink exists + (see "Audio output"); nothing connects the console path to it yet. + +## Audio output + +`src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the +default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), +converts each submitted block (format, frame count, bytes) to it, and writes it through +`IAudioRenderClient`. Consumed frames are the submitted frames minus `GetCurrentPadding`; the +`IAudioClock` position is reported next to them. It records the first accepted block, the +submitted format, per-block frame counts and peak amplitude, the drained interval (queue empty +while the producer withholds data) and the recovery (resume until consumption advances). The +render API reports no discontinuity flag, so the glitch count is "not available" and is kept +apart from both intervals. + +```powershell +cmake --build --preset release --target startup_audio_output +ctest --preset release --no-tests=error -R '^startup_audio_output$' -V ~~~~ --- Fixed in 16a5a077: README experiment table row added, and a "Desktop audio render sink" section in docs/experiments.md (fixture, command, capability-skip meaning, what is not covered; no endpoint run is recorded there yet).
tedin7 commented 2026-11-24 06:50:44 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:39:58Z.

Code review location: src/startup_stubs/audio_sink.cpp; line 101

@@ -0,0 +1,157 @@
+#include "startup_stubs/audio_sink.h"
+
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <objbase.h>
+#include <mmreg.h>
+#include <audioclient.h>
+#include <mmdeviceapi.h>
+#include <wrl/client.h>
+
+namespace x2w_audio {
+
+using Microsoft::WRL::ComPtr;
+
+struct AudioSink::Impl {
+    ComPtr<IAudioClient> client;
+    ComPtr<IAudioRenderClient> render;
+    ComPtr<IAudioClock> clock;
+    UINT64 clock_freq = 1;
+};
+
+AudioSink::AudioSink() = default;
+
+AudioSink::~AudioSink()
+{
+    if (p_ && p_->client) p_->client->Stop();
+}
+
+static std::string friendly_name(IMMDevice* dev)
+{
+    // PKEY_Device_FriendlyName, spelled out to avoid the property-key header link requirements.
+    const PROPERTYKEY key = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14};
+    ComPtr<IPropertyStore> props;
+    PROPVARIANT v;
+    PropVariantInit(&v);
+    std::string out = "(unnamed endpoint)";
+    if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &props)) && SUCCEEDED(props->GetValue(key, &v)) &&
+        v.vt == VT_LPWSTR && v.pwszVal) {
+        char buf[256] = {};
+        if (WideCharToMultiByte(CP_UTF8, 0, v.pwszVal, -1, buf, sizeof(buf) - 1, nullptr, nullptr) > 0) out = buf;
+    }
+    PropVariantClear(&v);
+    return out;
+}
+
+// Accepts 32-bit float and 16-bit PCM mix formats (extensible or plain).
+static bool mix_kind(const WAVEFORMATEX* wf, SampleKind& kind)
+{
+    WORD tag = wf->wFormatTag;
+    if (tag == WAVE_FORMAT_EXTENSIBLE && wf->cbSize >= 22)
+        tag = static_cast<WORD>(reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(wf)->SubFormat.Data1);
+    if (tag == WAVE_FORMAT_IEEE_FLOAT && wf->wBitsPerSample == 32) kind = SampleKind::Float32;
+    else if (tag == WAVE_FORMAT_PCM && wf->wBitsPerSample == 16) kind = SampleKind::Pcm16;
+    else return false;
+    return true;
+}
+
+std::string AudioSink::open()
+{
+    auto impl = std::make_unique<Impl>();
+    ComPtr<IMMDeviceEnumerator> en;
+    ComPtr<IMMDevice> dev;
+    HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en));
+    if (FAILED(hr)) return "no device enumerator, hr=" + std::to_string(static_cast<long>(hr));
+    hr = en->GetDefaultAudioEndpoint(eRender, eConsole, &dev);
+    if (FAILED(hr)) return "no default render endpoint, hr=" + std::to_string(static_cast<long>(hr));
+    endpoint_ = friendly_name(dev.Get());
+    hr = dev->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(impl->client.GetAddressOf()));
+    if (FAILED(hr)) return "endpoint activation failed, hr=" + std::to_string(static_cast<long>(hr));
+    WAVEFORMATEX* wf = nullptr;
+    hr = impl->client->GetMixFormat(&wf);
+    if (FAILED(hr) || !wf) return "GetMixFormat failed, hr=" + std::to_string(static_cast<long>(hr));
+    SampleKind kind = SampleKind::Float32;
+    const bool ok = mix_kind(wf, kind);
+    if (!ok) {
+        const std::string s = "unsupported mix format tag=" + std::to_string(wf->wFormatTag) +
+                              " bits=" + std::to_string(wf->wBitsPerSample);
+        CoTaskMemFree(wf);
+        return s;
+    }
+    mix_ = {kind, wf->nChannels, wf->nSamplesPerSec};
+    constexpr REFERENCE_TIME buffer_100ns = 5000000;  // 500 ms
+    hr = impl->client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, buffer_100ns, 0, wf, nullptr);
+    CoTaskMemFree(wf);
+    if (FAILED(hr)) return "IAudioClient::Initialize failed, hr=" + std::to_string(static_cast<long>(hr));
+    UINT32 frames = 0;
+    if (FAILED(impl->client->GetBufferSize(&frames)) || FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->render))) ||
+        FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->clock))) || FAILED(impl->clock->GetFrequency(&impl->clock_freq)))
+        return "endpoint services unavailable";
+    buffer_frames_ = frames;
+    p_ = std::move(impl);
+    return {};
+}
+
+uint32_t AudioSink::padding()
+{
+    UINT32 pad = 0;
+    if (p_) p_->client->GetCurrentPadding(&pad);
+    return pad;

Fixed in 16a5a077: padding() now returns padding_failed and counts padding_errors when GetCurrentPadding fails. observe() makes no observation in that case (consumption and the queue timers do not move), submit() refuses the block, and the fixture fails the run if any case has padding_errors. Not compiled or run on Windows by me.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675966376 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#discussion_r4675966376). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:39:58Z. **Code review location:** `src/startup_stubs/audio_sink.cpp`; line 101 ~~~~diff @@ -0,0 +1,157 @@ +#include "startup_stubs/audio_sink.h" + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <objbase.h> +#include <mmreg.h> +#include <audioclient.h> +#include <mmdeviceapi.h> +#include <wrl/client.h> + +namespace x2w_audio { + +using Microsoft::WRL::ComPtr; + +struct AudioSink::Impl { + ComPtr<IAudioClient> client; + ComPtr<IAudioRenderClient> render; + ComPtr<IAudioClock> clock; + UINT64 clock_freq = 1; +}; + +AudioSink::AudioSink() = default; + +AudioSink::~AudioSink() +{ + if (p_ && p_->client) p_->client->Stop(); +} + +static std::string friendly_name(IMMDevice* dev) +{ + // PKEY_Device_FriendlyName, spelled out to avoid the property-key header link requirements. + const PROPERTYKEY key = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14}; + ComPtr<IPropertyStore> props; + PROPVARIANT v; + PropVariantInit(&v); + std::string out = "(unnamed endpoint)"; + if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &props)) && SUCCEEDED(props->GetValue(key, &v)) && + v.vt == VT_LPWSTR && v.pwszVal) { + char buf[256] = {}; + if (WideCharToMultiByte(CP_UTF8, 0, v.pwszVal, -1, buf, sizeof(buf) - 1, nullptr, nullptr) > 0) out = buf; + } + PropVariantClear(&v); + return out; +} + +// Accepts 32-bit float and 16-bit PCM mix formats (extensible or plain). +static bool mix_kind(const WAVEFORMATEX* wf, SampleKind& kind) +{ + WORD tag = wf->wFormatTag; + if (tag == WAVE_FORMAT_EXTENSIBLE && wf->cbSize >= 22) + tag = static_cast<WORD>(reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(wf)->SubFormat.Data1); + if (tag == WAVE_FORMAT_IEEE_FLOAT && wf->wBitsPerSample == 32) kind = SampleKind::Float32; + else if (tag == WAVE_FORMAT_PCM && wf->wBitsPerSample == 16) kind = SampleKind::Pcm16; + else return false; + return true; +} + +std::string AudioSink::open() +{ + auto impl = std::make_unique<Impl>(); + ComPtr<IMMDeviceEnumerator> en; + ComPtr<IMMDevice> dev; + HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en)); + if (FAILED(hr)) return "no device enumerator, hr=" + std::to_string(static_cast<long>(hr)); + hr = en->GetDefaultAudioEndpoint(eRender, eConsole, &dev); + if (FAILED(hr)) return "no default render endpoint, hr=" + std::to_string(static_cast<long>(hr)); + endpoint_ = friendly_name(dev.Get()); + hr = dev->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, reinterpret_cast<void**>(impl->client.GetAddressOf())); + if (FAILED(hr)) return "endpoint activation failed, hr=" + std::to_string(static_cast<long>(hr)); + WAVEFORMATEX* wf = nullptr; + hr = impl->client->GetMixFormat(&wf); + if (FAILED(hr) || !wf) return "GetMixFormat failed, hr=" + std::to_string(static_cast<long>(hr)); + SampleKind kind = SampleKind::Float32; + const bool ok = mix_kind(wf, kind); + if (!ok) { + const std::string s = "unsupported mix format tag=" + std::to_string(wf->wFormatTag) + + " bits=" + std::to_string(wf->wBitsPerSample); + CoTaskMemFree(wf); + return s; + } + mix_ = {kind, wf->nChannels, wf->nSamplesPerSec}; + constexpr REFERENCE_TIME buffer_100ns = 5000000; // 500 ms + hr = impl->client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, buffer_100ns, 0, wf, nullptr); + CoTaskMemFree(wf); + if (FAILED(hr)) return "IAudioClient::Initialize failed, hr=" + std::to_string(static_cast<long>(hr)); + UINT32 frames = 0; + if (FAILED(impl->client->GetBufferSize(&frames)) || FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->render))) || + FAILED(impl->client->GetService(IID_PPV_ARGS(&impl->clock))) || FAILED(impl->clock->GetFrequency(&impl->clock_freq))) + return "endpoint services unavailable"; + buffer_frames_ = frames; + p_ = std::move(impl); + return {}; +} + +uint32_t AudioSink::padding() +{ + UINT32 pad = 0; + if (p_) p_->client->GetCurrentPadding(&pad); + return pad; ~~~~ --- Fixed in 16a5a077: `padding()` now returns `padding_failed` and counts `padding_errors` when `GetCurrentPadding` fails. `observe()` makes no observation in that case (consumption and the queue timers do not move), `submit()` refuses the block, and the fixture fails the run if any case has `padding_errors`. Not compiled or run on Windows by me.
tedin7 commented 2026-11-24 06:50:44 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:40:00Z.

Code review location: tests/startup_audio_output.cpp; line 138

@@ -0,0 +1,140 @@
+// Source-built WASAPI render fixture (Refs #1145). Three cases against the default endpoint:
+// (a) no submission, (b) a continuous stream with one silent block, (c) producer starvation.
+// Exit 77 when there is no usable render endpoint. Capture-path verification is not included.
+#include "startup_audio_pure_check.h"
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#include <objbase.h>
+
+using namespace x2w_audio;
+
+namespace {
+
+int fail(const char* what, int code)
+{
+    std::printf("FAIL: %s\n", what);
+    return code;
+}
+
+void print_report(const char* name, const Report& r)
+{
+    std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu "
+                "unsupported=%u rejected_full=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n",
+                name, static_cast<long long>(r.first_block), r.frames.size(), static_cast<unsigned long long>(r.submitted_frames),
+                static_cast<unsigned long long>(r.consumed_frames), static_cast<unsigned long long>(r.clock_frames),
+                r.unsupported, r.rejected_full, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available");
+}
+
+// Polls until done() holds or ms elapse; every wait in this fixture goes through here.
+template <class F>
+bool wait_for(AudioSink& s, double ms, F done)
+{
+    const double end = now_ms() + ms;
+    for (;;) {
+        s.observe(false);
+        if (done()) return true;
+        if (now_ms() > end) return false;
+        Sleep(2);
+    }
+}
+
+// Retries a block while the endpoint buffer is full, for at most two seconds.
+Submit send(AudioSink& s, const std::vector<int16_t>& pcm, const BlockFormat& fmt)
+{
+    const double end = now_ms() + 2000;
+    for (;;) {
+        const Submit r = s.submit(fmt, static_cast<uint32_t>(pcm.size()), pcm.data());
+        if (r != Submit::Full || now_ms() > end) return r;
+        Sleep(2);
+        s.observe(false);
+    }
+}
+
+void print_windows_build()
+{
+    using Fn = LONG(WINAPI*)(OSVERSIONINFOW*);
+    OSVERSIONINFOW v{sizeof(v)};
+    const auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion")));
+    if (fn && fn(&v) == 0) std::printf("windows: %lu.%lu build %lu\n", v.dwMajorVersion, v.dwMinorVersion, v.dwBuildNumber);
+    else std::puts("windows: build unknown");
+}
+
+int skip(const std::string& why)
+{
+    std::printf("SKIP (capability): %s\n", why.c_str());
+    print_windows_build();
+    return 77;
+}
+
+}  // namespace
+
+int main()
+{
+    if (const int rc = check_pure()) return fail("pure helper checks", rc);
+    if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return skip("COM initialisation failed");
+
+    AudioSink a;
+    if (const std::string why = a.open(); !why.empty()) return skip(why);
+    print_windows_build();
+    const BlockFormat mix = a.mix_format();
+    std::printf("endpoint: %s, mix %s %u ch %u Hz, buffer %u frames\n", a.endpoint().c_str(),
+                mix.kind == SampleKind::Float32 ? "float32" : "pcm16", mix.channels, mix.rate, a.buffer_frames());
+
+    // (a) No submission: nothing accepted, nothing consumed.
+    wait_for(a, 300, [] { return false; });
+    const Report ra = a.report();
+    print_report("case a (no submission)", ra);
+    if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0)
+        return fail("case a reported accepted or consumed frames without a submission", 1);
+
+    // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros.
+    const BlockFormat src{SampleKind::Pcm16, 1, mix.rate};
+    const uint32_t block = mix.rate / 25;
+    AudioSink b;
+    if (const std::string why = b.open(); !why.empty()) return skip(why);
+    for (int i = 0; i < 8; ++i) {
+        const auto pcm = make_tone(mix.rate, block, 220.0 * (i + 1), i == 3 ? 0.0 : 0.1 + 0.07 * i);
+        const Submit r = send(b, pcm, src);
+        if (r == Submit::Unsupported) return skip("block format cannot be converted to the endpoint format");
+        if (r != Submit::Accepted) return fail("case b block not accepted", 2);
+    }
+    wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; });
+    const Report rb = b.report();
+    print_report("case b (continuous with silence)", rb);
+    if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3);
+    for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3);
+    if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4);
+    if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5);
+    for (int i = 0; i < 8; ++i)
+        for (int j = i + 1; j < 8; ++j)
+            if (rb.peaks[i] == rb.peaks[j]) return fail("case b blocks are not distinguishable", 5);
+
+    // (c) Starvation: let the queue drain, hold, resume.
+    AudioSink c;
+    if (const std::string why = c.open(); !why.empty()) return skip(why);
+    for (int i = 0; i < 2; ++i)
+        if (send(c, make_tone(mix.rate, block, 330.0 + 110 * i, 0.4), src) != Submit::Accepted) return fail("case c first blocks", 6);
+    if (!wait_for(c, 3000, [&] { return c.padding() == 0 && c.report().consumed_frames == 2ull * block; }))
+        return fail("case c queue did not drain", 7);
+    for (const double hold_end = now_ms() + 300; now_ms() < hold_end;) {
+        c.observe(true);
+        Sleep(2);
+    }
+    if (c.padding() != 0) return fail("case c queue refilled while withheld", 7);
+    if (send(c, make_tone(mix.rate, block, 550.0, 0.4), src) != Submit::Accepted) return fail("case c resume block", 8);
+    wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; });
+    const Report rc = c.report();
+    print_report("case c (starvation)", rc);
+    if (rc.drained_ms < 250) return fail("case c drained interval too short", 9);
+    if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10);
+    if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10);
+    std::puts("startup_audio_output: PASS (no capture-path verification; glitch count not available from the render API)");
+    CoUninitialize();

Fixed in 16a5a077: the three sinks now live in run(), and main() calls CoUninitialize() only after run() has returned, so they stop and release their interfaces first. Not compiled or run on Windows by me.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675966538 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1250#discussion_r4675966538). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:40:00Z. **Code review location:** `tests/startup_audio_output.cpp`; line 138 ~~~~diff @@ -0,0 +1,140 @@ +// Source-built WASAPI render fixture (Refs #1145). Three cases against the default endpoint: +// (a) no submission, (b) a continuous stream with one silent block, (c) producer starvation. +// Exit 77 when there is no usable render endpoint. Capture-path verification is not included. +#include "startup_audio_pure_check.h" + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <objbase.h> + +using namespace x2w_audio; + +namespace { + +int fail(const char* what, int code) +{ + std::printf("FAIL: %s\n", what); + return code; +} + +void print_report(const char* name, const Report& r) +{ + std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " + "unsupported=%u rejected_full=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", + name, static_cast<long long>(r.first_block), r.frames.size(), static_cast<unsigned long long>(r.submitted_frames), + static_cast<unsigned long long>(r.consumed_frames), static_cast<unsigned long long>(r.clock_frames), + r.unsupported, r.rejected_full, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); +} + +// Polls until done() holds or ms elapse; every wait in this fixture goes through here. +template <class F> +bool wait_for(AudioSink& s, double ms, F done) +{ + const double end = now_ms() + ms; + for (;;) { + s.observe(false); + if (done()) return true; + if (now_ms() > end) return false; + Sleep(2); + } +} + +// Retries a block while the endpoint buffer is full, for at most two seconds. +Submit send(AudioSink& s, const std::vector<int16_t>& pcm, const BlockFormat& fmt) +{ + const double end = now_ms() + 2000; + for (;;) { + const Submit r = s.submit(fmt, static_cast<uint32_t>(pcm.size()), pcm.data()); + if (r != Submit::Full || now_ms() > end) return r; + Sleep(2); + s.observe(false); + } +} + +void print_windows_build() +{ + using Fn = LONG(WINAPI*)(OSVERSIONINFOW*); + OSVERSIONINFOW v{sizeof(v)}; + const auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion"))); + if (fn && fn(&v) == 0) std::printf("windows: %lu.%lu build %lu\n", v.dwMajorVersion, v.dwMinorVersion, v.dwBuildNumber); + else std::puts("windows: build unknown"); +} + +int skip(const std::string& why) +{ + std::printf("SKIP (capability): %s\n", why.c_str()); + print_windows_build(); + return 77; +} + +} // namespace + +int main() +{ + if (const int rc = check_pure()) return fail("pure helper checks", rc); + if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return skip("COM initialisation failed"); + + AudioSink a; + if (const std::string why = a.open(); !why.empty()) return skip(why); + print_windows_build(); + const BlockFormat mix = a.mix_format(); + std::printf("endpoint: %s, mix %s %u ch %u Hz, buffer %u frames\n", a.endpoint().c_str(), + mix.kind == SampleKind::Float32 ? "float32" : "pcm16", mix.channels, mix.rate, a.buffer_frames()); + + // (a) No submission: nothing accepted, nothing consumed. + wait_for(a, 300, [] { return false; }); + const Report ra = a.report(); + print_report("case a (no submission)", ra); + if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0) + return fail("case a reported accepted or consumed frames without a submission", 1); + + // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros. + const BlockFormat src{SampleKind::Pcm16, 1, mix.rate}; + const uint32_t block = mix.rate / 25; + AudioSink b; + if (const std::string why = b.open(); !why.empty()) return skip(why); + for (int i = 0; i < 8; ++i) { + const auto pcm = make_tone(mix.rate, block, 220.0 * (i + 1), i == 3 ? 0.0 : 0.1 + 0.07 * i); + const Submit r = send(b, pcm, src); + if (r == Submit::Unsupported) return skip("block format cannot be converted to the endpoint format"); + if (r != Submit::Accepted) return fail("case b block not accepted", 2); + } + wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; }); + const Report rb = b.report(); + print_report("case b (continuous with silence)", rb); + if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); + for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3); + if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4); + if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5); + for (int i = 0; i < 8; ++i) + for (int j = i + 1; j < 8; ++j) + if (rb.peaks[i] == rb.peaks[j]) return fail("case b blocks are not distinguishable", 5); + + // (c) Starvation: let the queue drain, hold, resume. + AudioSink c; + if (const std::string why = c.open(); !why.empty()) return skip(why); + for (int i = 0; i < 2; ++i) + if (send(c, make_tone(mix.rate, block, 330.0 + 110 * i, 0.4), src) != Submit::Accepted) return fail("case c first blocks", 6); + if (!wait_for(c, 3000, [&] { return c.padding() == 0 && c.report().consumed_frames == 2ull * block; })) + return fail("case c queue did not drain", 7); + for (const double hold_end = now_ms() + 300; now_ms() < hold_end;) { + c.observe(true); + Sleep(2); + } + if (c.padding() != 0) return fail("case c queue refilled while withheld", 7); + if (send(c, make_tone(mix.rate, block, 550.0, 0.4), src) != Submit::Accepted) return fail("case c resume block", 8); + wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; }); + const Report rc = c.report(); + print_report("case c (starvation)", rc); + if (rc.drained_ms < 250) return fail("case c drained interval too short", 9); + if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10); + if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10); + std::puts("startup_audio_output: PASS (no capture-path verification; glitch count not available from the render API)"); + CoUninitialize(); ~~~~ --- Fixed in 16a5a077: the three sinks now live in `run()`, and `main()` calls `CoUninitialize()` only after `run()` has returned, so they stop and release their interfaces first. Not compiled or run on Windows by me.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!1243
No description provided.