startup: add a voice-lifecycle control with explicit diagnostic and system providers #1392

Merged
triggered02 merged 2 commits from upstream-pr/1399 into main 2026-11-24 10:45:59 +00:00
triggered02 commented 2026-11-24 10:30:50 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by triggered02 on 2026-11-24T10:30:50Z.


Second slice of #1145, following the direction on the issue: a source-built client with an explicit
diagnostic XAudio2 provider rather than an intercepting tap.

One client drives a steady and a bursty submission plan through a small provider interface with two
implementations:

  • diagnostic: records the voice lifecycle, buffer arguments and callbacks, and advances a virtual
    clock as the plan waits; it touches no device and stores no audio;
  • system: calls XAudio2Create and the real IXAudio2 directly. There is no import patching and no
    hooking anywhere, so the diagnostics-disabled arm visibly calls the system provider.

The precondition the slice starts from is that the diagnostic window is faithful, so the fixture checks
that both arms observe the same lifecycle and the same buffer arguments for the same plan, and fails on
divergence with the first differing event. Only after that does it report timing.

Recorded per arm: timestamps, frame counts, buffer counts, callbacks, drops, queue depth and clock
progress. Audio bytes and user data are never recorded or stored — the system arm submits silence.

Measured here (shared-mode endpoint, XAudio2_9, 48 kHz stereo 16-bit, 120 blocks of 10 ms):

steady: faithful=yes
  diagnostic: events=243 frames=57600 callbacks=120 drops=0 depth_max=480  clock=57600 elapsed=1907ms
  system    : events=243 frames=57600 callbacks=120 drops=0 depth_max=480  clock=57600 elapsed=1875ms
bursty: faithful=yes
  diagnostic: events=243 frames=57600 callbacks=120 drops=0 depth_max=2880 clock=57600 elapsed=4704ms
  system    : events=243 frames=57600 callbacks=120 drops=0 depth_max=2880 clock=57600 elapsed=4719ms

Two defects this control found in its own diagnostic arm while it was being built, both fixed: the arm
did not advance its clock during withholding gaps (so the bursty arm was unfaithful by construction and
diverged at event 3), and it reported queue depth in frames for one arm and buffers for the other.

Skips (77) when no shared-mode endpoint is available.

What this slice does not establish, restating the limit on the issue: a steady submission stream
would narrow the fault to after submission, and would still leave voice state, queued playback and
endpoint scheduling to verify. This fixture measures the client/provider boundary; it does not locate
the title's stutter.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6579780842 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399). Originally posted by [triggered02](https://github.com/triggered02) on 2026-11-24T10:30:50Z. --- Second slice of #1145, following the direction on the issue: a source-built client with an explicit diagnostic XAudio2 provider rather than an intercepting tap. One client drives a steady and a bursty submission plan through a small provider interface with two implementations: - **diagnostic**: records the voice lifecycle, buffer arguments and callbacks, and advances a virtual clock as the plan waits; it touches no device and stores no audio; - **system**: calls `XAudio2Create` and the real `IXAudio2` directly. There is no import patching and no hooking anywhere, so the diagnostics-disabled arm visibly calls the system provider. The precondition the slice starts from is that the diagnostic window is faithful, so the fixture checks that both arms observe the same lifecycle and the same buffer arguments for the same plan, and fails on divergence with the first differing event. Only after that does it report timing. Recorded per arm: timestamps, frame counts, buffer counts, callbacks, drops, queue depth and clock progress. **Audio bytes and user data are never recorded or stored** — the system arm submits silence. Measured here (shared-mode endpoint, XAudio2_9, 48 kHz stereo 16-bit, 120 blocks of 10 ms): ``` steady: faithful=yes diagnostic: events=243 frames=57600 callbacks=120 drops=0 depth_max=480 clock=57600 elapsed=1907ms system : events=243 frames=57600 callbacks=120 drops=0 depth_max=480 clock=57600 elapsed=1875ms bursty: faithful=yes diagnostic: events=243 frames=57600 callbacks=120 drops=0 depth_max=2880 clock=57600 elapsed=4704ms system : events=243 frames=57600 callbacks=120 drops=0 depth_max=2880 clock=57600 elapsed=4719ms ``` Two defects this control found in its own diagnostic arm while it was being built, both fixed: the arm did not advance its clock during withholding gaps (so the bursty arm was unfaithful by construction and diverged at event 3), and it reported queue depth in frames for one arm and buffers for the other. Skips (77) when no shared-mode endpoint is available. **What this slice does not establish**, restating the limit on the issue: a steady submission stream would narrow the fault to *after* submission, and would still leave voice state, queued playback and endpoint scheduling to verify. This fixture measures the client/provider boundary; it does not locate the title's stutter.
upstream-sync closed this pull request 2026-11-24 11:02:50 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 11:02:51 +00:00 (Migrated from github.com)

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

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e60714288a

ℹ️ 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:6037619479 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399#pullrequestreview-6037619479). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T10:33:32Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `e60714288a` <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 11:02:51 +00:00 (Migrated from github.com)

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

Review: COMMENTED


Dual-platform peer review of #1399 (e6071428):

Checks

  • git diff --check origin/main...HEAD: clean.
  • Linux: tests/bidi_controls_check.py passed (Checked 1148 tracked source, script and build/CI files: no bidirectional controls.).
  • Win2025 (x2w_pipe.py win2025 1399 --targets startup_audio_provider --regex '^startup_audio_provider$'):
    • Debug (--preset dev): builds cleanly (4.11s); startup_audio_provider skipped (exit 77) (1.96s) — no audio endpoint on the Windows Server 2025 VM.
    • Release (/O2, --preset release): builds cleanly (1.61s); startup_audio_provider skipped (exit 77) (1.88s).

Code audit (tests/startup_audio_provider.cpp)

  1. Buffer size mismatch in SystemVoice::prepare() / submit() (out-of-bounds read):
    • prepare() allocates pcm_.assign(block_frames * format_.channels, 0); (960 bytes for 480 frames * 2 channels), whereas submit() sets buffer.AudioBytes = frames * (format_.bits / 8) * format_.channels; (1920 bytes for 16-bit stereo). prepare() is missing * (format_.bits / 8).
  2. Data race between XAudio2 callback thread and main thread:
    • SystemVoice::OnBufferEnd() executes on XAudio2's audio thread and mutates trace_.callbacks and trace_.events.push_back({"callback", 0}) without synchronization, while run_plan() reads voice->trace().callbacks in a loop and submit()/start()/stop() push to trace_.events on the main thread.
  3. Minor cleanup / consistency notes:
    • SystemProvider::open() leaks engine_ if CreateMasteringVoice() fails, and main() exits early without calling diagnostic.close() when system.open() skips.
    • SystemVoice::state() overwrites trace_.clock_frames = out.played_frames, whereas DiagnosticVoice::advance() accumulates trace_.clock_frames += consumed.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6037712142 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399#pullrequestreview-6037712142). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T10:40:05Z. **Review:** COMMENTED --- Dual-platform peer review of #1399 (`e6071428`): ### Checks - `git diff --check origin/main...HEAD`: clean. - Linux: `tests/bidi_controls_check.py` passed (`Checked 1148 tracked source, script and build/CI files: no bidirectional controls.`). - Win2025 (`x2w_pipe.py win2025 1399 --targets startup_audio_provider --regex '^startup_audio_provider$'`): - **Debug (`--preset dev`)**: builds cleanly (`4.11s`); `startup_audio_provider` **skipped (exit 77)** (`1.96s`) — no audio endpoint on the Windows Server 2025 VM. - **Release (`/O2`, `--preset release`)**: builds cleanly (`1.61s`); `startup_audio_provider` **skipped (exit 77)** (`1.88s`). ### Code audit (`tests/startup_audio_provider.cpp`) 1. **Buffer size mismatch in `SystemVoice::prepare()` / `submit()` (out-of-bounds read):** - `prepare()` allocates `pcm_.assign(block_frames * format_.channels, 0);` (960 bytes for 480 frames * 2 channels), whereas `submit()` sets `buffer.AudioBytes = frames * (format_.bits / 8) * format_.channels;` (1920 bytes for 16-bit stereo). `prepare()` is missing `* (format_.bits / 8)`. 2. **Data race between XAudio2 callback thread and main thread:** - `SystemVoice::OnBufferEnd()` executes on XAudio2's audio thread and mutates `trace_.callbacks` and `trace_.events.push_back({"callback", 0})` without synchronization, while `run_plan()` reads `voice->trace().callbacks` in a loop and `submit()`/`start()`/`stop()` push to `trace_.events` on the main thread. 3. **Minor cleanup / consistency notes:** - `SystemProvider::open()` leaks `engine_` if `CreateMasteringVoice()` fails, and `main()` exits early without calling `diagnostic.close()` when `system.open()` skips. - `SystemVoice::state()` overwrites `trace_.clock_frames = out.played_frames`, whereas `DiagnosticVoice::advance()` accumulates `trace_.clock_frames += consumed`.
chatgpt-codex-connector[bot commented 2026-11-24 11:03:00 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T10:31:07Z.


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-24T10:33:35.602947Z e607142 PR opened
ℹ️ 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:7128886924 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399#issuecomment-7128886924). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T10:31:07Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"e60714288a1ba2e6142a9672053726d9a247c72c","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-24T10:33:35.602947Z">2026-11-24T10:33:35.602947Z</relative-time> | `e607142` | PR opened | <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>
R0Y00 commented 2026-11-24 11:03:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T10:41:13Z.


I fixed the two review findings in 04bc596e. The silence buffer is sized in bytes and checked before submission. The callback only updates atomic completion state, and the test checks completion order and count separately from caller-side events, which can interleave differently on the system clock. A rejected submission or missing completion now fails the test. Windows Release ran both providers and passed startup_audio_provider on this revision. This is still a source-built voice control for #1145.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7129110107 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399#issuecomment-7129110107). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T10:41:13Z. --- I fixed the two review findings in 04bc596e. The silence buffer is sized in bytes and checked before submission. The callback only updates atomic completion state, and the test checks completion order and count separately from caller-side events, which can interleave differently on the system clock. A rejected submission or missing completion now fails the test. Windows Release ran both providers and passed startup_audio_provider on this revision. This is still a source-built voice control for #1145.
chatgpt-codex-connector[bot commented 2026-11-24 11:03:03 +00:00 (Migrated from github.com)

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

Code review location: tests/startup_audio_provider.cpp; line 247

@@ -0,0 +1,445 @@
+// Voice-lifecycle control for the playback-timing slice of #1145 (slice 2).
+//
+// The client here is deliberately not the title: it drives one small provider interface through a
+// steady and a bursty submission plan, and it is given either of two explicit providers:
+//
+//   diagnostic - records the voice lifecycle, buffer arguments and callbacks, and advances a virtual
+//                clock as the plan is pumped; it plays no audio and touches no device;
+//   system     - calls XAudio2Create and the real IXAudio2 directly. No import patching, no hooking:
+//                the "diagnostics disabled" arm visibly calls the system provider.
+//
+// The precondition the slice starts from is that the diagnostic arm is a faithful window, so the
+// fixture first checks that both arms observe the same lifecycle and the same buffer arguments for
+// the same plan. If they diverge it fails there and prints the first divergence, because a timing
+// number from an unfaithful window would be worthless.
+//
+// What is recorded (and nothing else): timestamps, frame counts, queue depth, drop counts, clock
+// progress, callbacks observed, and buffer arguments. Audio bytes are never recorded or stored.
+#include <xaudio2.h>
+
+#define NOMINMAX
+#include <windows.h>
+#include <objbase.h>
+
+#include <algorithm>
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include <vector>
+
+namespace {
+
+constexpr int skip_no_device = 77;
+
+struct Format {
+    unsigned rate = 48000, channels = 2, bits = 16;
+};
+
+struct VoiceState {
+    unsigned long long queued_frames = 0;
+    unsigned long long played_frames = 0;
+};
+
+// One entry per lifecycle or submission event, in order. Kept independent of wall-clock time so two
+// arms running on different clocks can be compared event for event.
+struct Event {
+    const char* kind;  // "create", "submit", "start", "stop", "callback", "destroy"
+    unsigned long long arg = 0;
+    bool operator==(const Event& other) const { return std::strcmp(kind, other.kind) == 0 && arg == other.arg; }
+};
+
+struct Trace {
+    std::vector<Event> events;
+    unsigned long long submitted_frames = 0;
+    unsigned long long submitted_buffers = 0;
+    unsigned long long callbacks = 0;
+    unsigned long long drops = 0;
+    unsigned long long queue_depth_max = 0;
+    unsigned long long clock_frames = 0;
+    bool started = false, stopped = false;
+};
+
+class Voice {
+public:
+    virtual ~Voice() = default;
+    // frames of quiet PCM; the plan owns the bytes so the provider never has to store audio content.
+    virtual bool submit(unsigned frames) = 0;
+    virtual void start() = 0;
+    virtual void stop() = 0;
+    virtual VoiceState state() = 0;
+    virtual Trace& trace() = 0;
+};
+
+class Provider {
+public:
+    virtual ~Provider() = default;
+    virtual const char* name() const = 0;
+    virtual std::string open() = 0;  // empty on success
+    virtual Voice* create_voice(const Format&) = 0;
+    virtual void close() = 0;
+};
+
+// ---------------------------------------------------------------------------------------------------
+// Diagnostic provider: no device, virtual clock, records the lifecycle the client drives.
+class DiagnosticVoice final : public Voice {
+public:
+    explicit DiagnosticVoice(Format format) : format_(format) {}
+    bool submit(unsigned frames) override
+    {
+        if (queue_ + frames > capacity_frames) {
+            ++trace_.drops;
+            return false;
+        }
+        queue_ += frames;
+        ++in_flight_;
+        trace_.submitted_frames += frames;
+        ++trace_.submitted_buffers;
+        trace_.events.push_back({"submit", frames});
+        drain();
+        return true;
+    }
+    void start() override
+    {
+        trace_.started = true;
+        trace_.events.push_back({"start", 0});
+    }
+    void stop() override
+    {
+        trace_.stopped = true;
+        trace_.events.push_back({"stop", 0});
+        // Stopping discards whatever is queued, which is what the system voice does on Stop().
+        queue_ = 0;
+        in_flight_ = 0;
+    }
+    VoiceState state() override
+    {
+        VoiceState s;
+        s.queued_frames = queue_;
+        s.played_frames = played_;
+        return s;
+    }
+    Trace& trace() override { return trace_; }
+
+    // The plan calls this once per submission period, so the virtual clock advances in the same steps
+    // as the real one would and the callbacks line up with the same submissions.
+    void advance(unsigned frames)
+    {
+        const unsigned consumed = (std::min)(frames, static_cast<unsigned>(queue_));
+        queue_ -= consumed;
+        played_ += consumed;
+        trace_.clock_frames += consumed;
+        while (in_flight_ > 0 && played_ >= next_callback_at_) {
+            --in_flight_;
+            ++trace_.callbacks;
+            trace_.events.push_back({"callback", 0});
+            next_callback_at_ += block_frames_;
+        }
+        trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_);
+    }
+
+private:
+    void drain() { trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_); }
+    Format format_;
+    unsigned capacity_frames = 4800;  // 100 ms
+    unsigned block_frames_ = 480;     // 10 ms
+    unsigned long long queue_ = 0, played_ = 0, next_callback_at_ = 480;
+    int in_flight_ = 0;
+    Trace trace_;
+};
+
+class DiagnosticProvider final : public Provider {
+public:
+    const char* name() const override { return "diagnostic"; }
+    std::string open() override { return {}; }
+    Voice* create_voice(const Format& format) override
+    {
+        auto* voice = new DiagnosticVoice(format);
+        voice->trace().events.push_back({"create", format.rate});
+        voices_.push_back(voice);
+        return voice;
+    }
+    void close() override
+    {
+        for (Voice* voice : voices_) delete voice;
+        voices_.clear();
+    }
+    void advance(unsigned frames)
+    {
+        for (Voice* voice : voices_)
+            if (auto* diagnostic = dynamic_cast<DiagnosticVoice*>(voice)) diagnostic->advance(frames);
+    }
+
+private:
+    std::vector<Voice*> voices_;
+};
+
+// ---------------------------------------------------------------------------------------------------
+// System provider: the real thing, called directly.
+class SystemVoice final : public Voice, public IXAudio2VoiceCallback {
+public:
+    SystemVoice(IXAudio2* engine, Format format) : engine_(engine), format_(format) {}
+    ~SystemVoice() override
+    {
+        if (voice_) voice_->DestroyVoice();
+        if (buffers_) delete[] buffers_;
+    }
+    std::string create()
+    {
+        WAVEFORMATEX wf{};
+        wf.wFormatTag = WAVE_FORMAT_PCM;
+        wf.nChannels = static_cast<WORD>(format_.channels);
+        wf.nSamplesPerSec = format_.rate;
+        wf.wBitsPerSample = static_cast<WORD>(format_.bits);
+        wf.nBlockAlign = static_cast<WORD>(wf.nChannels * wf.wBitsPerSample / 8);
+        wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
+        const HRESULT hr = engine_->CreateSourceVoice(&voice_, &wf, 0, 1.0f, this);
+        if (FAILED(hr)) return "CreateSourceVoice failed";
+        trace_.events.push_back({"create", format_.rate});
+        return {};
+    }
+    bool submit(unsigned frames) override
+    {
+        if (submit_index_ >= max_blocks) return false;
+        XAUDIO2_BUFFER& buffer = buffers_[submit_index_];
+        buffer = {};
+        buffer.AudioBytes = frames * (format_.bits / 8) * format_.channels;
+        buffer.pAudioData = pcm_.data();  // one shared quiet block; content is never recorded
+        buffer.Flags = XAUDIO2_END_OF_STREAM * 0;
+        const HRESULT hr = voice_->SubmitSourceBuffer(&buffer);
+        if (FAILED(hr)) {
+            ++trace_.drops;
+            return false;
+        }
+        ++submit_index_;
+        trace_.submitted_frames += frames;
+        ++trace_.submitted_buffers;
+        trace_.events.push_back({"submit", frames});
+        return true;
+    }
+    void start() override
+    {
+        if (SUCCEEDED(voice_->Start(0))) {
+            trace_.started = true;
+            trace_.events.push_back({"start", 0});
+        }
+    }
+    void stop() override
+    {
+        voice_->Stop(0);
+        trace_.stopped = true;
+        trace_.events.push_back({"stop", 0});
+    }
+    VoiceState state() override
+    {
+        XAUDIO2_VOICE_STATE s{};
+        voice_->GetState(&s, 0);
+        VoiceState out;
+        out.queued_frames = s.BuffersQueued * block_frames_;
+        out.played_frames = s.SamplesPlayed;
+        trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, out.queued_frames);
+        trace_.clock_frames = out.played_frames;
+        return out;
+    }
+    Trace& trace() override { return trace_; }
+    void prepare(unsigned block_frames)
+    {
+        block_frames_ = block_frames;
+        pcm_.assign(block_frames * format_.channels, 0);

P2 Badge Size the PCM storage in bytes

On any run that reaches the XAudio2 system arm, the 48 kHz stereo 16-bit plan allocates 960 bytes for a 480-frame block, while submit() advertises 1,920 bytes via AudioBytes. XAudio2 can therefore read beyond pcm_ for every queued buffer, so the system arm is not submitting silence and may play unrelated heap contents or fault; allocate bits / 8 bytes per sample as well.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4678682816 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399#discussion_r4678682816). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T10:33:32Z. **Code review location:** `tests/startup_audio_provider.cpp`; line 247 ~~~~diff @@ -0,0 +1,445 @@ +// Voice-lifecycle control for the playback-timing slice of #1145 (slice 2). +// +// The client here is deliberately not the title: it drives one small provider interface through a +// steady and a bursty submission plan, and it is given either of two explicit providers: +// +// diagnostic - records the voice lifecycle, buffer arguments and callbacks, and advances a virtual +// clock as the plan is pumped; it plays no audio and touches no device; +// system - calls XAudio2Create and the real IXAudio2 directly. No import patching, no hooking: +// the "diagnostics disabled" arm visibly calls the system provider. +// +// The precondition the slice starts from is that the diagnostic arm is a faithful window, so the +// fixture first checks that both arms observe the same lifecycle and the same buffer arguments for +// the same plan. If they diverge it fails there and prints the first divergence, because a timing +// number from an unfaithful window would be worthless. +// +// What is recorded (and nothing else): timestamps, frame counts, queue depth, drop counts, clock +// progress, callbacks observed, and buffer arguments. Audio bytes are never recorded or stored. +#include <xaudio2.h> + +#define NOMINMAX +#include <windows.h> +#include <objbase.h> + +#include <algorithm> +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +namespace { + +constexpr int skip_no_device = 77; + +struct Format { + unsigned rate = 48000, channels = 2, bits = 16; +}; + +struct VoiceState { + unsigned long long queued_frames = 0; + unsigned long long played_frames = 0; +}; + +// One entry per lifecycle or submission event, in order. Kept independent of wall-clock time so two +// arms running on different clocks can be compared event for event. +struct Event { + const char* kind; // "create", "submit", "start", "stop", "callback", "destroy" + unsigned long long arg = 0; + bool operator==(const Event& other) const { return std::strcmp(kind, other.kind) == 0 && arg == other.arg; } +}; + +struct Trace { + std::vector<Event> events; + unsigned long long submitted_frames = 0; + unsigned long long submitted_buffers = 0; + unsigned long long callbacks = 0; + unsigned long long drops = 0; + unsigned long long queue_depth_max = 0; + unsigned long long clock_frames = 0; + bool started = false, stopped = false; +}; + +class Voice { +public: + virtual ~Voice() = default; + // frames of quiet PCM; the plan owns the bytes so the provider never has to store audio content. + virtual bool submit(unsigned frames) = 0; + virtual void start() = 0; + virtual void stop() = 0; + virtual VoiceState state() = 0; + virtual Trace& trace() = 0; +}; + +class Provider { +public: + virtual ~Provider() = default; + virtual const char* name() const = 0; + virtual std::string open() = 0; // empty on success + virtual Voice* create_voice(const Format&) = 0; + virtual void close() = 0; +}; + +// --------------------------------------------------------------------------------------------------- +// Diagnostic provider: no device, virtual clock, records the lifecycle the client drives. +class DiagnosticVoice final : public Voice { +public: + explicit DiagnosticVoice(Format format) : format_(format) {} + bool submit(unsigned frames) override + { + if (queue_ + frames > capacity_frames) { + ++trace_.drops; + return false; + } + queue_ += frames; + ++in_flight_; + trace_.submitted_frames += frames; + ++trace_.submitted_buffers; + trace_.events.push_back({"submit", frames}); + drain(); + return true; + } + void start() override + { + trace_.started = true; + trace_.events.push_back({"start", 0}); + } + void stop() override + { + trace_.stopped = true; + trace_.events.push_back({"stop", 0}); + // Stopping discards whatever is queued, which is what the system voice does on Stop(). + queue_ = 0; + in_flight_ = 0; + } + VoiceState state() override + { + VoiceState s; + s.queued_frames = queue_; + s.played_frames = played_; + return s; + } + Trace& trace() override { return trace_; } + + // The plan calls this once per submission period, so the virtual clock advances in the same steps + // as the real one would and the callbacks line up with the same submissions. + void advance(unsigned frames) + { + const unsigned consumed = (std::min)(frames, static_cast<unsigned>(queue_)); + queue_ -= consumed; + played_ += consumed; + trace_.clock_frames += consumed; + while (in_flight_ > 0 && played_ >= next_callback_at_) { + --in_flight_; + ++trace_.callbacks; + trace_.events.push_back({"callback", 0}); + next_callback_at_ += block_frames_; + } + trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_); + } + +private: + void drain() { trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_); } + Format format_; + unsigned capacity_frames = 4800; // 100 ms + unsigned block_frames_ = 480; // 10 ms + unsigned long long queue_ = 0, played_ = 0, next_callback_at_ = 480; + int in_flight_ = 0; + Trace trace_; +}; + +class DiagnosticProvider final : public Provider { +public: + const char* name() const override { return "diagnostic"; } + std::string open() override { return {}; } + Voice* create_voice(const Format& format) override + { + auto* voice = new DiagnosticVoice(format); + voice->trace().events.push_back({"create", format.rate}); + voices_.push_back(voice); + return voice; + } + void close() override + { + for (Voice* voice : voices_) delete voice; + voices_.clear(); + } + void advance(unsigned frames) + { + for (Voice* voice : voices_) + if (auto* diagnostic = dynamic_cast<DiagnosticVoice*>(voice)) diagnostic->advance(frames); + } + +private: + std::vector<Voice*> voices_; +}; + +// --------------------------------------------------------------------------------------------------- +// System provider: the real thing, called directly. +class SystemVoice final : public Voice, public IXAudio2VoiceCallback { +public: + SystemVoice(IXAudio2* engine, Format format) : engine_(engine), format_(format) {} + ~SystemVoice() override + { + if (voice_) voice_->DestroyVoice(); + if (buffers_) delete[] buffers_; + } + std::string create() + { + WAVEFORMATEX wf{}; + wf.wFormatTag = WAVE_FORMAT_PCM; + wf.nChannels = static_cast<WORD>(format_.channels); + wf.nSamplesPerSec = format_.rate; + wf.wBitsPerSample = static_cast<WORD>(format_.bits); + wf.nBlockAlign = static_cast<WORD>(wf.nChannels * wf.wBitsPerSample / 8); + wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; + const HRESULT hr = engine_->CreateSourceVoice(&voice_, &wf, 0, 1.0f, this); + if (FAILED(hr)) return "CreateSourceVoice failed"; + trace_.events.push_back({"create", format_.rate}); + return {}; + } + bool submit(unsigned frames) override + { + if (submit_index_ >= max_blocks) return false; + XAUDIO2_BUFFER& buffer = buffers_[submit_index_]; + buffer = {}; + buffer.AudioBytes = frames * (format_.bits / 8) * format_.channels; + buffer.pAudioData = pcm_.data(); // one shared quiet block; content is never recorded + buffer.Flags = XAUDIO2_END_OF_STREAM * 0; + const HRESULT hr = voice_->SubmitSourceBuffer(&buffer); + if (FAILED(hr)) { + ++trace_.drops; + return false; + } + ++submit_index_; + trace_.submitted_frames += frames; + ++trace_.submitted_buffers; + trace_.events.push_back({"submit", frames}); + return true; + } + void start() override + { + if (SUCCEEDED(voice_->Start(0))) { + trace_.started = true; + trace_.events.push_back({"start", 0}); + } + } + void stop() override + { + voice_->Stop(0); + trace_.stopped = true; + trace_.events.push_back({"stop", 0}); + } + VoiceState state() override + { + XAUDIO2_VOICE_STATE s{}; + voice_->GetState(&s, 0); + VoiceState out; + out.queued_frames = s.BuffersQueued * block_frames_; + out.played_frames = s.SamplesPlayed; + trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, out.queued_frames); + trace_.clock_frames = out.played_frames; + return out; + } + Trace& trace() override { return trace_; } + void prepare(unsigned block_frames) + { + block_frames_ = block_frames; + pcm_.assign(block_frames * format_.channels, 0); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Size the PCM storage in bytes** On any run that reaches the XAudio2 system arm, the 48 kHz stereo 16-bit plan allocates 960 bytes for a 480-frame block, while `submit()` advertises 1,920 bytes via `AudioBytes`. XAudio2 can therefore read beyond `pcm_` for every queued buffer, so the system arm is not submitting silence and may play unrelated heap contents or fault; allocate `bits / 8` bytes per sample as well. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 11:03:03 +00:00 (Migrated from github.com)

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

Code review location: tests/startup_audio_provider.cpp; line 261

@@ -0,0 +1,445 @@
+// Voice-lifecycle control for the playback-timing slice of #1145 (slice 2).
+//
+// The client here is deliberately not the title: it drives one small provider interface through a
+// steady and a bursty submission plan, and it is given either of two explicit providers:
+//
+//   diagnostic - records the voice lifecycle, buffer arguments and callbacks, and advances a virtual
+//                clock as the plan is pumped; it plays no audio and touches no device;
+//   system     - calls XAudio2Create and the real IXAudio2 directly. No import patching, no hooking:
+//                the "diagnostics disabled" arm visibly calls the system provider.
+//
+// The precondition the slice starts from is that the diagnostic arm is a faithful window, so the
+// fixture first checks that both arms observe the same lifecycle and the same buffer arguments for
+// the same plan. If they diverge it fails there and prints the first divergence, because a timing
+// number from an unfaithful window would be worthless.
+//
+// What is recorded (and nothing else): timestamps, frame counts, queue depth, drop counts, clock
+// progress, callbacks observed, and buffer arguments. Audio bytes are never recorded or stored.
+#include <xaudio2.h>
+
+#define NOMINMAX
+#include <windows.h>
+#include <objbase.h>
+
+#include <algorithm>
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include <vector>
+
+namespace {
+
+constexpr int skip_no_device = 77;
+
+struct Format {
+    unsigned rate = 48000, channels = 2, bits = 16;
+};
+
+struct VoiceState {
+    unsigned long long queued_frames = 0;
+    unsigned long long played_frames = 0;
+};
+
+// One entry per lifecycle or submission event, in order. Kept independent of wall-clock time so two
+// arms running on different clocks can be compared event for event.
+struct Event {
+    const char* kind;  // "create", "submit", "start", "stop", "callback", "destroy"
+    unsigned long long arg = 0;
+    bool operator==(const Event& other) const { return std::strcmp(kind, other.kind) == 0 && arg == other.arg; }
+};
+
+struct Trace {
+    std::vector<Event> events;
+    unsigned long long submitted_frames = 0;
+    unsigned long long submitted_buffers = 0;
+    unsigned long long callbacks = 0;
+    unsigned long long drops = 0;
+    unsigned long long queue_depth_max = 0;
+    unsigned long long clock_frames = 0;
+    bool started = false, stopped = false;
+};
+
+class Voice {
+public:
+    virtual ~Voice() = default;
+    // frames of quiet PCM; the plan owns the bytes so the provider never has to store audio content.
+    virtual bool submit(unsigned frames) = 0;
+    virtual void start() = 0;
+    virtual void stop() = 0;
+    virtual VoiceState state() = 0;
+    virtual Trace& trace() = 0;
+};
+
+class Provider {
+public:
+    virtual ~Provider() = default;
+    virtual const char* name() const = 0;
+    virtual std::string open() = 0;  // empty on success
+    virtual Voice* create_voice(const Format&) = 0;
+    virtual void close() = 0;
+};
+
+// ---------------------------------------------------------------------------------------------------
+// Diagnostic provider: no device, virtual clock, records the lifecycle the client drives.
+class DiagnosticVoice final : public Voice {
+public:
+    explicit DiagnosticVoice(Format format) : format_(format) {}
+    bool submit(unsigned frames) override
+    {
+        if (queue_ + frames > capacity_frames) {
+            ++trace_.drops;
+            return false;
+        }
+        queue_ += frames;
+        ++in_flight_;
+        trace_.submitted_frames += frames;
+        ++trace_.submitted_buffers;
+        trace_.events.push_back({"submit", frames});
+        drain();
+        return true;
+    }
+    void start() override
+    {
+        trace_.started = true;
+        trace_.events.push_back({"start", 0});
+    }
+    void stop() override
+    {
+        trace_.stopped = true;
+        trace_.events.push_back({"stop", 0});
+        // Stopping discards whatever is queued, which is what the system voice does on Stop().
+        queue_ = 0;
+        in_flight_ = 0;
+    }
+    VoiceState state() override
+    {
+        VoiceState s;
+        s.queued_frames = queue_;
+        s.played_frames = played_;
+        return s;
+    }
+    Trace& trace() override { return trace_; }
+
+    // The plan calls this once per submission period, so the virtual clock advances in the same steps
+    // as the real one would and the callbacks line up with the same submissions.
+    void advance(unsigned frames)
+    {
+        const unsigned consumed = (std::min)(frames, static_cast<unsigned>(queue_));
+        queue_ -= consumed;
+        played_ += consumed;
+        trace_.clock_frames += consumed;
+        while (in_flight_ > 0 && played_ >= next_callback_at_) {
+            --in_flight_;
+            ++trace_.callbacks;
+            trace_.events.push_back({"callback", 0});
+            next_callback_at_ += block_frames_;
+        }
+        trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_);
+    }
+
+private:
+    void drain() { trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_); }
+    Format format_;
+    unsigned capacity_frames = 4800;  // 100 ms
+    unsigned block_frames_ = 480;     // 10 ms
+    unsigned long long queue_ = 0, played_ = 0, next_callback_at_ = 480;
+    int in_flight_ = 0;
+    Trace trace_;
+};
+
+class DiagnosticProvider final : public Provider {
+public:
+    const char* name() const override { return "diagnostic"; }
+    std::string open() override { return {}; }
+    Voice* create_voice(const Format& format) override
+    {
+        auto* voice = new DiagnosticVoice(format);
+        voice->trace().events.push_back({"create", format.rate});
+        voices_.push_back(voice);
+        return voice;
+    }
+    void close() override
+    {
+        for (Voice* voice : voices_) delete voice;
+        voices_.clear();
+    }
+    void advance(unsigned frames)
+    {
+        for (Voice* voice : voices_)
+            if (auto* diagnostic = dynamic_cast<DiagnosticVoice*>(voice)) diagnostic->advance(frames);
+    }
+
+private:
+    std::vector<Voice*> voices_;
+};
+
+// ---------------------------------------------------------------------------------------------------
+// System provider: the real thing, called directly.
+class SystemVoice final : public Voice, public IXAudio2VoiceCallback {
+public:
+    SystemVoice(IXAudio2* engine, Format format) : engine_(engine), format_(format) {}
+    ~SystemVoice() override
+    {
+        if (voice_) voice_->DestroyVoice();
+        if (buffers_) delete[] buffers_;
+    }
+    std::string create()
+    {
+        WAVEFORMATEX wf{};
+        wf.wFormatTag = WAVE_FORMAT_PCM;
+        wf.nChannels = static_cast<WORD>(format_.channels);
+        wf.nSamplesPerSec = format_.rate;
+        wf.wBitsPerSample = static_cast<WORD>(format_.bits);
+        wf.nBlockAlign = static_cast<WORD>(wf.nChannels * wf.wBitsPerSample / 8);
+        wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
+        const HRESULT hr = engine_->CreateSourceVoice(&voice_, &wf, 0, 1.0f, this);
+        if (FAILED(hr)) return "CreateSourceVoice failed";
+        trace_.events.push_back({"create", format_.rate});
+        return {};
+    }
+    bool submit(unsigned frames) override
+    {
+        if (submit_index_ >= max_blocks) return false;
+        XAUDIO2_BUFFER& buffer = buffers_[submit_index_];
+        buffer = {};
+        buffer.AudioBytes = frames * (format_.bits / 8) * format_.channels;
+        buffer.pAudioData = pcm_.data();  // one shared quiet block; content is never recorded
+        buffer.Flags = XAUDIO2_END_OF_STREAM * 0;
+        const HRESULT hr = voice_->SubmitSourceBuffer(&buffer);
+        if (FAILED(hr)) {
+            ++trace_.drops;
+            return false;
+        }
+        ++submit_index_;
+        trace_.submitted_frames += frames;
+        ++trace_.submitted_buffers;
+        trace_.events.push_back({"submit", frames});
+        return true;
+    }
+    void start() override
+    {
+        if (SUCCEEDED(voice_->Start(0))) {
+            trace_.started = true;
+            trace_.events.push_back({"start", 0});
+        }
+    }
+    void stop() override
+    {
+        voice_->Stop(0);
+        trace_.stopped = true;
+        trace_.events.push_back({"stop", 0});
+    }
+    VoiceState state() override
+    {
+        XAUDIO2_VOICE_STATE s{};
+        voice_->GetState(&s, 0);
+        VoiceState out;
+        out.queued_frames = s.BuffersQueued * block_frames_;
+        out.played_frames = s.SamplesPlayed;
+        trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, out.queued_frames);
+        trace_.clock_frames = out.played_frames;
+        return out;
+    }
+    Trace& trace() override { return trace_; }
+    void prepare(unsigned block_frames)
+    {
+        block_frames_ = block_frames;
+        pcm_.assign(block_frames * format_.channels, 0);
+        buffers_ = new XAUDIO2_BUFFER[max_blocks]{};
+    }
+    IXAudio2SourceVoice* voice() const { return voice_; }
+
+    // IXAudio2VoiceCallback: count and record; nothing else.
+    void __stdcall OnVoiceProcessingPassStart(UINT32) override {}
+    void __stdcall OnVoiceProcessingPassEnd() override {}
+    void __stdcall OnStreamEnd() override {}
+    void __stdcall OnBufferStart(void*) override {}
+    void __stdcall OnBufferEnd(void*) override
+    {
+        InterlockedIncrement(reinterpret_cast<volatile LONG*>(&ended_));
+        ++trace_.callbacks;
+        trace_.events.push_back({"callback", 0});

P2 Badge Synchronize callback trace updates

When OnBufferEnd runs on XAudio2's processing thread, it updates this non-atomic count and events while run_plan reads trace().callbacks and the producer appends submit events. These unsynchronized accesses race, including concurrent std::vector::push_back calls, so the lifecycle comparison can be corrupted or crash; collect callback records through synchronized state and merge them on the main thread.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4678682827 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1399#discussion_r4678682827). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T10:33:32Z. **Code review location:** `tests/startup_audio_provider.cpp`; line 261 ~~~~diff @@ -0,0 +1,445 @@ +// Voice-lifecycle control for the playback-timing slice of #1145 (slice 2). +// +// The client here is deliberately not the title: it drives one small provider interface through a +// steady and a bursty submission plan, and it is given either of two explicit providers: +// +// diagnostic - records the voice lifecycle, buffer arguments and callbacks, and advances a virtual +// clock as the plan is pumped; it plays no audio and touches no device; +// system - calls XAudio2Create and the real IXAudio2 directly. No import patching, no hooking: +// the "diagnostics disabled" arm visibly calls the system provider. +// +// The precondition the slice starts from is that the diagnostic arm is a faithful window, so the +// fixture first checks that both arms observe the same lifecycle and the same buffer arguments for +// the same plan. If they diverge it fails there and prints the first divergence, because a timing +// number from an unfaithful window would be worthless. +// +// What is recorded (and nothing else): timestamps, frame counts, queue depth, drop counts, clock +// progress, callbacks observed, and buffer arguments. Audio bytes are never recorded or stored. +#include <xaudio2.h> + +#define NOMINMAX +#include <windows.h> +#include <objbase.h> + +#include <algorithm> +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +namespace { + +constexpr int skip_no_device = 77; + +struct Format { + unsigned rate = 48000, channels = 2, bits = 16; +}; + +struct VoiceState { + unsigned long long queued_frames = 0; + unsigned long long played_frames = 0; +}; + +// One entry per lifecycle or submission event, in order. Kept independent of wall-clock time so two +// arms running on different clocks can be compared event for event. +struct Event { + const char* kind; // "create", "submit", "start", "stop", "callback", "destroy" + unsigned long long arg = 0; + bool operator==(const Event& other) const { return std::strcmp(kind, other.kind) == 0 && arg == other.arg; } +}; + +struct Trace { + std::vector<Event> events; + unsigned long long submitted_frames = 0; + unsigned long long submitted_buffers = 0; + unsigned long long callbacks = 0; + unsigned long long drops = 0; + unsigned long long queue_depth_max = 0; + unsigned long long clock_frames = 0; + bool started = false, stopped = false; +}; + +class Voice { +public: + virtual ~Voice() = default; + // frames of quiet PCM; the plan owns the bytes so the provider never has to store audio content. + virtual bool submit(unsigned frames) = 0; + virtual void start() = 0; + virtual void stop() = 0; + virtual VoiceState state() = 0; + virtual Trace& trace() = 0; +}; + +class Provider { +public: + virtual ~Provider() = default; + virtual const char* name() const = 0; + virtual std::string open() = 0; // empty on success + virtual Voice* create_voice(const Format&) = 0; + virtual void close() = 0; +}; + +// --------------------------------------------------------------------------------------------------- +// Diagnostic provider: no device, virtual clock, records the lifecycle the client drives. +class DiagnosticVoice final : public Voice { +public: + explicit DiagnosticVoice(Format format) : format_(format) {} + bool submit(unsigned frames) override + { + if (queue_ + frames > capacity_frames) { + ++trace_.drops; + return false; + } + queue_ += frames; + ++in_flight_; + trace_.submitted_frames += frames; + ++trace_.submitted_buffers; + trace_.events.push_back({"submit", frames}); + drain(); + return true; + } + void start() override + { + trace_.started = true; + trace_.events.push_back({"start", 0}); + } + void stop() override + { + trace_.stopped = true; + trace_.events.push_back({"stop", 0}); + // Stopping discards whatever is queued, which is what the system voice does on Stop(). + queue_ = 0; + in_flight_ = 0; + } + VoiceState state() override + { + VoiceState s; + s.queued_frames = queue_; + s.played_frames = played_; + return s; + } + Trace& trace() override { return trace_; } + + // The plan calls this once per submission period, so the virtual clock advances in the same steps + // as the real one would and the callbacks line up with the same submissions. + void advance(unsigned frames) + { + const unsigned consumed = (std::min)(frames, static_cast<unsigned>(queue_)); + queue_ -= consumed; + played_ += consumed; + trace_.clock_frames += consumed; + while (in_flight_ > 0 && played_ >= next_callback_at_) { + --in_flight_; + ++trace_.callbacks; + trace_.events.push_back({"callback", 0}); + next_callback_at_ += block_frames_; + } + trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_); + } + +private: + void drain() { trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, queue_); } + Format format_; + unsigned capacity_frames = 4800; // 100 ms + unsigned block_frames_ = 480; // 10 ms + unsigned long long queue_ = 0, played_ = 0, next_callback_at_ = 480; + int in_flight_ = 0; + Trace trace_; +}; + +class DiagnosticProvider final : public Provider { +public: + const char* name() const override { return "diagnostic"; } + std::string open() override { return {}; } + Voice* create_voice(const Format& format) override + { + auto* voice = new DiagnosticVoice(format); + voice->trace().events.push_back({"create", format.rate}); + voices_.push_back(voice); + return voice; + } + void close() override + { + for (Voice* voice : voices_) delete voice; + voices_.clear(); + } + void advance(unsigned frames) + { + for (Voice* voice : voices_) + if (auto* diagnostic = dynamic_cast<DiagnosticVoice*>(voice)) diagnostic->advance(frames); + } + +private: + std::vector<Voice*> voices_; +}; + +// --------------------------------------------------------------------------------------------------- +// System provider: the real thing, called directly. +class SystemVoice final : public Voice, public IXAudio2VoiceCallback { +public: + SystemVoice(IXAudio2* engine, Format format) : engine_(engine), format_(format) {} + ~SystemVoice() override + { + if (voice_) voice_->DestroyVoice(); + if (buffers_) delete[] buffers_; + } + std::string create() + { + WAVEFORMATEX wf{}; + wf.wFormatTag = WAVE_FORMAT_PCM; + wf.nChannels = static_cast<WORD>(format_.channels); + wf.nSamplesPerSec = format_.rate; + wf.wBitsPerSample = static_cast<WORD>(format_.bits); + wf.nBlockAlign = static_cast<WORD>(wf.nChannels * wf.wBitsPerSample / 8); + wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; + const HRESULT hr = engine_->CreateSourceVoice(&voice_, &wf, 0, 1.0f, this); + if (FAILED(hr)) return "CreateSourceVoice failed"; + trace_.events.push_back({"create", format_.rate}); + return {}; + } + bool submit(unsigned frames) override + { + if (submit_index_ >= max_blocks) return false; + XAUDIO2_BUFFER& buffer = buffers_[submit_index_]; + buffer = {}; + buffer.AudioBytes = frames * (format_.bits / 8) * format_.channels; + buffer.pAudioData = pcm_.data(); // one shared quiet block; content is never recorded + buffer.Flags = XAUDIO2_END_OF_STREAM * 0; + const HRESULT hr = voice_->SubmitSourceBuffer(&buffer); + if (FAILED(hr)) { + ++trace_.drops; + return false; + } + ++submit_index_; + trace_.submitted_frames += frames; + ++trace_.submitted_buffers; + trace_.events.push_back({"submit", frames}); + return true; + } + void start() override + { + if (SUCCEEDED(voice_->Start(0))) { + trace_.started = true; + trace_.events.push_back({"start", 0}); + } + } + void stop() override + { + voice_->Stop(0); + trace_.stopped = true; + trace_.events.push_back({"stop", 0}); + } + VoiceState state() override + { + XAUDIO2_VOICE_STATE s{}; + voice_->GetState(&s, 0); + VoiceState out; + out.queued_frames = s.BuffersQueued * block_frames_; + out.played_frames = s.SamplesPlayed; + trace_.queue_depth_max = (std::max)(trace_.queue_depth_max, out.queued_frames); + trace_.clock_frames = out.played_frames; + return out; + } + Trace& trace() override { return trace_; } + void prepare(unsigned block_frames) + { + block_frames_ = block_frames; + pcm_.assign(block_frames * format_.channels, 0); + buffers_ = new XAUDIO2_BUFFER[max_blocks]{}; + } + IXAudio2SourceVoice* voice() const { return voice_; } + + // IXAudio2VoiceCallback: count and record; nothing else. + void __stdcall OnVoiceProcessingPassStart(UINT32) override {} + void __stdcall OnVoiceProcessingPassEnd() override {} + void __stdcall OnStreamEnd() override {} + void __stdcall OnBufferStart(void*) override {} + void __stdcall OnBufferEnd(void*) override + { + InterlockedIncrement(reinterpret_cast<volatile LONG*>(&ended_)); + ++trace_.callbacks; + trace_.events.push_back({"callback", 0}); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Synchronize callback trace updates** When `OnBufferEnd` runs on XAudio2's processing thread, it updates this non-atomic count and `events` while `run_plan` reads `trace().callbacks` and the producer appends submit events. These unsynchronized accesses race, including concurrent `std::vector::push_back` calls, so the lifecycle comparison can be corrupted or crash; collect callback records through synchronized state and merge them on the main thread. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
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!1392
No description provided.