xapu: decode the title's Opus packets and play them on the PC (retail title's sound) #294

Closed
github-bot wants to merge 2 commits from gh-pr/294/head into gh-pr/294/base
Owner

@⁠simnJS on GitHub · 2026-11-23 22:35 UTC · original
xapu-opus → main · +538 −25 · 4 files · 2 commits · closed without merging

The retail title is mute under XCL: it does not use XAudio2 but sends its sound to the console's audio decoder (xapu), and XCL answered every xapu command with silence. This decodes the Opus packets the title sends to xapu into the output buffer the title gives; the title then reads that PCM back, mixes it (its own volumes and panning) and plays its mix itself on the system's default endpoint through Windows Spatial Audio, so XCL has nothing more to play. It also gives Opus a decoder under Wine, where Windows' MSOpusDecoder.dll does not exist.

What the title sends (traced with the new XCL_TRACE_APU=1, documented at the top of hle/acphal.rs): everything goes to stream 0 through XApuEnqueueCommand; Activate (kind 1) carries the channel count at +24 and 48000 Hz at +56; each Process (kind 3) carries one raw Opus packet (80 or 160 B, CELT fullband 20 ms, mono), 960 frames, first_frame 312 on the first command (the pre-skip), into a 3840 B float output; Deactivate is kind 2. acphal gets one command at start-up; the DSP none. Nothing reaches xapu before the title's menu. The 350 "SHAPE" contexts it creates are XMA decode contexts, not a mixer; its final mix goes to an ISpatialAudioClient with two static objects (front left / right), seen with WINEDEBUG=+mmdevapi.

What is in it

  • Opus: libopus from opus.dll where Windows has no decoder (Wine) – hle/opus.rs: when the Media Foundation MFT cannot be created, libopus (BSD-3-Clause) is loaded at run time from %XCL_OPUS_DIR% or next to xcl.exe, as for DXC (a DLL without the four symbols is freed again); its decoder keeps a stream timestamp like the MFT's and refuses an empty or malformed packet as the MFT path does; the log names the decoder actually made; Windows keeps its own decoder; with neither, silence as before (logged once). THIRD_PARTY.md: libopus, not distributed.
  • xapu: decode the title's Opus packets into its output buffer (retail title's sound) – hle/acphal.rs: the first Activate of a stream creates its decoder, a later one with the same layout resets it (no new Media Foundation transform per sound), Process decodes into a local buffer, copies it into the title's output (no alignment assumed) and returns the frames written; a packet that does not decode, or a stream the title did not connect, still gets silence of the length asked, as before. report.json gets xapu_* counters, xcl.log a summary line every 5 s.

Tested

  • Ubuntu 26.04 (kernel 7.0), RTX 4080 SUPER (NVIDIA 595.99.02), Ryzen 9 7950X3D; Proton Experimental 11.0's Wine, vkd3d-proton v3.1 with the patch from #257, DXVK 3.1.1, DXC 1.9.2609; Rust stable, x86_64-pc-windows-gnu, release; libopus 1.5.2 built with mingw-w64 as opus.dll (#257's scripts/linux/build-opus.sh).
  • cargo build --workspace --all-targets --locked --target x86_64-pc-windows-gnu at each commit.
  • Retail title 1.0.2.1 (Series package), run to its menus: Opus: decoder = libopus (…opus.dll), xapu: 153 Opus packets decoded (0 errors), 144072 frames, 136590 non-zero samples. With the earlier revision's raw playback switched off – which is what this revision does – the menu sound was heard on the PC's speakers: the title's own mix is what plays.
  • On Windows, by others in this thread: the test suite (651 passed, 0 failed) and the MFT path (ersinhf), the title's sound in its intro and menus (ryosen0).

Regression run
Made with scripts/linux/smoke.sh (#257: smoke.ps1's run and block under Wine), 50 s, on Ubuntu 26.04 / RTX 4080 SUPER, Proton Experimental 11.0's Wine, vkd3d-proton v3.1 + patch, DXVK 3.1.1, XCL_OPUS_DIR set for both runs. In both runs the account prompt was answered by hand with A and the title went to its "Brightness Level" screen; both ended by themselves (exit: 0x0). Under Wine XCL's end takes ~15 s after XCL_RUN_SECONDS (its watchdog: suspending every thread also stops vkd3d-proton's), so the earlier 60 s blocks with a 10 s grace said killed. peak commit reads 0 under Wine.

main at 4017f8f:

xcl-smoke v1
commit: 4017f8ff8faaae6007fd83910d230a027dd85a33
gpu: NVIDIA GeForce RTX 4080 SUPER
title: 78b7bda4
seconds: 50
exit: 0x0
frames shown: 722 (PresentX 722)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 0 MB

This PR's head 38bbfda:

xcl-smoke v1
commit: 38bbfdabf42f69a271c993375140d6fb552312f2
gpu: NVIDIA GeForce RTX 4080 SUPER
title: 78b7bda4
seconds: 50
exit: 0x0
frames shown: 712 (PresentX 712)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 0 MB

Not tested

  • Windows, by me: the test suite and scripts/smoke.ps1 (no Windows machine; see the Windows runs above).
  • A long run with the title's continuous music; other titles that use xapu (Activate creates one Opus decoder per activated stream – an MFT on Windows).

AI use

  • Written with an AI coding agent (tracing, code and this description), then read and checked by the author.
**@⁠simnJS** on GitHub · 2026-11-23 22:35 UTC · [original](https://github.com/xcl-dev/xcl/pull/294) `xapu-opus` → `main` · +538 −25 · 4 files · 2 commits · closed without merging The retail title is mute under XCL: it does not use XAudio2 but sends its sound to the console's audio decoder (xapu), and XCL answered every xapu command with silence. This decodes the Opus packets the title sends to xapu into the output buffer the title gives; the title then reads that PCM back, mixes it (its own volumes and panning) and plays its mix itself on the system's default endpoint through Windows Spatial Audio, so XCL has nothing more to play. It also gives Opus a decoder under Wine, where Windows' `MSOpusDecoder.dll` does not exist. What the title sends (traced with the new `XCL_TRACE_APU=1`, documented at the top of `hle/acphal.rs`): everything goes to stream 0 through `XApuEnqueueCommand`; Activate (kind 1) carries the channel count at +24 and 48000 Hz at +56; each Process (kind 3) carries **one raw Opus packet** (80 or 160 B, CELT fullband 20 ms, mono), 960 frames, `first_frame` 312 on the first command (the pre-skip), into a 3840 B float output; Deactivate is kind 2. acphal gets one command at start-up; the DSP none. Nothing reaches xapu before the title's menu. The 350 "SHAPE" contexts it creates are XMA decode contexts, not a mixer; its final mix goes to an `ISpatialAudioClient` with two static objects (front left / right), seen with `WINEDEBUG=+mmdevapi`. **What is in it** - `Opus: libopus from opus.dll where Windows has no decoder (Wine)` – `hle/opus.rs`: when the Media Foundation MFT cannot be created, libopus (BSD-3-Clause) is loaded at run time from `%XCL_OPUS_DIR%` or next to `xcl.exe`, as for DXC (a DLL without the four symbols is freed again); its decoder keeps a stream timestamp like the MFT's and refuses an empty or malformed packet as the MFT path does; the log names the decoder actually made; Windows keeps its own decoder; with neither, silence as before (logged once). `THIRD_PARTY.md`: libopus, not distributed. - `xapu: decode the title's Opus packets into its output buffer (retail title's sound)` – `hle/acphal.rs`: the first Activate of a stream creates its decoder, a later one with the same layout resets it (no new Media Foundation transform per sound), Process decodes into a local buffer, copies it into the title's output (no alignment assumed) and returns the frames written; a packet that does not decode, or a stream the title did not connect, still gets silence of the length asked, as before. `report.json` gets `xapu_*` counters, `xcl.log` a summary line every 5 s. **Tested** - Ubuntu 26.04 (kernel 7.0), RTX 4080 SUPER (NVIDIA 595.99.02), Ryzen 9 7950X3D; Proton Experimental 11.0's Wine, vkd3d-proton v3.1 with the patch from #257, DXVK 3.1.1, DXC 1.9.2609; Rust stable, `x86_64-pc-windows-gnu`, release; libopus 1.5.2 built with mingw-w64 as `opus.dll` (#257's `scripts/linux/build-opus.sh`). - `cargo build --workspace --all-targets --locked --target x86_64-pc-windows-gnu` at each commit. - Retail title 1.0.2.1 (Series package), run to its menus: `Opus: decoder = libopus (…opus.dll)`, `xapu: 153 Opus packets decoded (0 errors), 144072 frames, 136590 non-zero samples`. With the earlier revision's raw playback switched off – which is what this revision does – the menu sound was heard on the PC's speakers: the title's own mix is what plays. - On Windows, by others in this thread: the test suite (651 passed, 0 failed) and the MFT path (ersinhf), the title's sound in its intro and menus (ryosen0). **Regression run** Made with `scripts/linux/smoke.sh` (#257: `smoke.ps1`'s run and block under Wine), 50 s, on Ubuntu 26.04 / RTX 4080 SUPER, Proton Experimental 11.0's Wine, vkd3d-proton v3.1 + patch, DXVK 3.1.1, `XCL_OPUS_DIR` set for both runs. In both runs the account prompt was answered by hand with A and the title went to its "Brightness Level" screen; both ended by themselves (`exit: 0x0`). Under Wine XCL's end takes ~15 s after `XCL_RUN_SECONDS` (its watchdog: suspending every thread also stops vkd3d-proton's), so the earlier 60 s blocks with a 10 s grace said `killed`. `peak commit` reads 0 under Wine. `main` at `4017f8f`: ``` xcl-smoke v1 commit: 4017f8ff8faaae6007fd83910d230a027dd85a33 gpu: NVIDIA GeForce RTX 4080 SUPER title: 78b7bda4 seconds: 50 exit: 0x0 frames shown: 722 (PresentX 722) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 0 MB ``` This PR's head `38bbfda`: ``` xcl-smoke v1 commit: 38bbfdabf42f69a271c993375140d6fb552312f2 gpu: NVIDIA GeForce RTX 4080 SUPER title: 78b7bda4 seconds: 50 exit: 0x0 frames shown: 712 (PresentX 712) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 0 MB ``` **Not tested** - Windows, by me: the test suite and `scripts/smoke.ps1` (no Windows machine; see the Windows runs above). - A long run with the title's continuous music; other titles that use xapu (Activate creates one Opus decoder per activated stream – an MFT on Windows). **AI use** - Written with an AI coding agent (tracing, code and this description), then read and checked by the author.
Windows' MSOpusDecoder.dll (a Media Foundation MFT) does not exist under
Wine or Proton, so every Opus voice was silent there. When the MFT cannot
be created, opus.rs now loads libopus (BSD-3-Clause) from an opus.dll at
run time, as XCL does for DXC: %XCL_OPUS_DIR% first, then next to
xcl.exe. Windows keeps its own decoder; without either decoder nothing
changes (silence, logged once). xcl.log says which decoder is used.

The libopus decoder keeps its stream time like the MFT one (it starts at
0 and after a flush), so the check that a stream is at its start before
the Ogg timing is applied stays true under Wine. A DLL that loads but
lacks one of the four libopus functions is unloaded again.
GTA VI does not use XAudio2: it sends its sound to the console's decoder
(xapu), and XCL answered every command with silence, so the game was mute.
Traced with the new XCL_TRACE_APU=1 (acphal / xapu / DSP commands, their
structures, buffers and callers): everything is on stream 0; Activate
(kind 1) gives channels at +24 and 48000 Hz at +56; each Process (kind 3)
carries one raw Opus packet (80 or 160 B, CELT fullband 20 ms, mono),
960 frames, first_frame 312 on the first command (the pre-skip), into a
3840 B f32 output; Deactivate is kind 2. The title sends nothing to xapu
before its menu.

Activate now creates an Opus decoder for the stream, Process decodes the
packet into the title's output buffer and returns the frames written.
Nothing is played from here: the title reads that output back, mixes it
and plays its own mix on a system audio endpoint (Windows Spatial Audio),
so decoding into the buffer is all XCL has to do. A listening test with
the PCM also played on a voice of XCL's own heard the sound twice.

The output is decoded into a local buffer and copied byte by byte (the
title's pointer is not known to be 4-byte aligned); a stream the
connection does not have is not decoded (silence of the length asked
for); XCL_TRACE_APU reads only the size of the command's own structure.
report.json gets xapu_* counters, and xcl.log a line every 5 s.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:19:08 +00:00
github-bot closed this pull request 2026-11-26 04:19:08 +00:00
Author
Owner

@⁠mastrr9 on GitHub · 2026-11-23 22:52 UTC · original

Independent static code audit of 6bae125e8 (code inspection only — cargo test not run on macOS; no game files):

Concrete issues found

  1. Ring-buffer use-after-free on repeated SubmitSourceBuffer failure (xaudio2.rs:1333-1354): v.next = (v.next + 1) % SINK_RING advances before checking hr >= 0 from submit(v.voice, &b, ...). If queued == SINK_RING - 2 (22 buffers still playing in XAudio2) and submit fails more than twice in a row, v.next walks past the 2 free slots and overwrites a Vec<f32> still referenced by an active XAudio2 buffer. Only advancing v.next in the hr >= 0 branch fixes this cleanly.
  2. LibDecoder::timestamp_100ns() hardcoded to 0 (opus.rs:623-628): Decoder::decode_buffer checks self.streams.iter().all(|s| s.timestamp_100ns() == 0) to confirm the decoder is at a fresh stream boundary before applying Ogg timing. Returning 0 unconditionally for LibDecoder means an already-used libopus stream (under Wine) will still pass that check on later buffers. Tracking decoded state / timestamp_100ns on LibDecoder (resetting it in flush()) matches MftDecoder.

Minor safety / edge-case notes

  • Output pointer alignment & trace reads (acphal.rs:885-910, 184-190): std::slice::from_raw_parts_mut(p.output as *mut f32, ...) requires 4-byte alignment of p.output (otherwise Rust UB); decoding into a local Vec<f32> and writing via copy_nonoverlapping avoids alignment assumptions. Similarly, under XCL_TRACE_APU=1, hex(command, 64) reads 64 bytes even for 24-byte commands (XApuDeactivate) without a readable() guard.
  • Stream bounds (acphal.rs:890): If n_streams == 0 in XApuConnect, ch[0] panics; and if c.stream as usize >= ch.len(), decoding mutates ch[0] while console_pcm(c.stream, ...) plays under c.stream.
  • DLL handle leak on partial symbol match (opus.rs:522-531): If a candidate DLL in libopus() loads via LoadLibraryW but lacks one of the four Opus exports, FreeLibrary is not called before continue.

(AI-assisted)

**@⁠mastrr9** on GitHub · 2026-11-23 22:52 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7116287496) Independent static code audit of `6bae125e8` (code inspection only — `cargo test` not run on macOS; no game files): ### Concrete issues found 1. **Ring-buffer use-after-free on repeated `SubmitSourceBuffer` failure (`xaudio2.rs:1333-1354`):** `v.next = (v.next + 1) % SINK_RING` advances *before* checking `hr >= 0` from `submit(v.voice, &b, ...)`. If `queued == SINK_RING - 2` (22 buffers still playing in XAudio2) and `submit` fails more than twice in a row, `v.next` walks past the 2 free slots and overwrites a `Vec<f32>` still referenced by an active XAudio2 buffer. Only advancing `v.next` in the `hr >= 0` branch fixes this cleanly. 2. **`LibDecoder::timestamp_100ns()` hardcoded to `0` (`opus.rs:623-628`):** `Decoder::decode_buffer` checks `self.streams.iter().all(|s| s.timestamp_100ns() == 0)` to confirm the decoder is at a fresh stream boundary before applying Ogg `timing`. Returning `0` unconditionally for `LibDecoder` means an already-used `libopus` stream (under Wine) will still pass that check on later buffers. Tracking decoded state / `timestamp_100ns` on `LibDecoder` (resetting it in `flush()`) matches `MftDecoder`. ### Minor safety / edge-case notes - **Output pointer alignment & trace reads (`acphal.rs:885-910`, `184-190`):** `std::slice::from_raw_parts_mut(p.output as *mut f32, ...)` requires 4-byte alignment of `p.output` (otherwise Rust UB); decoding into a local `Vec<f32>` and writing via `copy_nonoverlapping` avoids alignment assumptions. Similarly, under `XCL_TRACE_APU=1`, `hex(command, 64)` reads 64 bytes even for 24-byte commands (`XApuDeactivate`) without a `readable()` guard. - **Stream bounds (`acphal.rs:890`):** If `n_streams == 0` in `XApuConnect`, `ch[0]` panics; and if `c.stream as usize >= ch.len()`, decoding mutates `ch[0]` while `console_pcm(c.stream, ...)` plays under `c.stream`. - **DLL handle leak on partial symbol match (`opus.rs:522-531`):** If a candidate DLL in `libopus()` loads via `LoadLibraryW` but lacks one of the four Opus exports, `FreeLibrary` is not called before `continue`. *(AI-assisted)*
Author
Owner

@⁠ryosen0 on GitHub · 2026-11-23 23:03 UTC · original

Ran this stacked with #300 on our machine (main 4017f8f + 9507d05 + 7535ef3, Ryzen 7 9800X3D, RTX 3060 Ti 8 GB, driver 32.0.16.1742, Windows 11, release, XCL_NETWORK=0 XCL_TRACE_APU=1, 120 s):

  • timer: finest resolution for the title (was 1.00 ms, now 0.50 ms) - #300's line; our default was already 1.0 ms, not 15.6, which may explain why the choppiness here sounded like short gaps rather than 2/3 silence.
  • Opus decode: at t=77 s, 153 packets decoded, 0 errors, 144072 frames, 136590 non-zero samples; played on the PC: 143424 samples (135942 non-zero, 0 dropped, 0 errors, 1 voice). First Process at t=48.0 s (after the first A press), first_frame 312 pre-skip as described.
  • The human listener confirms the intro/menu sound is now continuous - before this stack it was choppy on the same machine (our data point in #260).
  • Packet sizes here: 80/160 B as traced; stream 0 only; Activate carries 1 channel / 48000 Hz. Matches the description.

The run reached the settings menus and then a solid-colour background; the log at that point shows BCPack BC1/BC5/BC7 requests refused (E_DECOMPRESSION) - texture data, unrelated to this PR's audio path.

AI use: GPT-6.2 Astra (API model selector) wrote this comment from our run's log; the human contributor listened and checked the numbers.

**@⁠ryosen0** on GitHub · 2026-11-23 23:03 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7116500235) Ran this stacked with #300 on our machine (main 4017f8f + 9507d05 + 7535ef3, Ryzen 7 9800X3D, RTX 3060 Ti 8 GB, driver 32.0.16.1742, Windows 11, release, `XCL_NETWORK=0 XCL_TRACE_APU=1`, 120 s): - `timer: finest resolution for the title (was 1.00 ms, now 0.50 ms)` - #300's line; our default was already 1.0 ms, not 15.6, which may explain why the choppiness here sounded like short gaps rather than 2/3 silence. - Opus decode: at t=77 s, **153 packets decoded, 0 errors, 144072 frames, 136590 non-zero samples; played on the PC: 143424 samples (135942 non-zero, 0 dropped, 0 errors, 1 voice)**. First Process at t=48.0 s (after the first A press), `first_frame` 312 pre-skip as described. - The human listener confirms the intro/menu sound is now continuous - before this stack it was choppy on the same machine (our data point in #260). - Packet sizes here: 80/160 B as traced; stream 0 only; Activate carries 1 channel / 48000 Hz. Matches the description. The run reached the settings menus and then a solid-colour background; the log at that point shows BCPack BC1/BC5/BC7 requests refused (`E_DECOMPRESSION`) - texture data, unrelated to this PR's audio path. AI use: GPT-6.2 Astra (API model selector) wrote this comment from our run's log; the human contributor listened and checked the numbers.
Author
Owner

@⁠mastrr9 on GitHub · 2026-11-23 23:12 UTC · original

Follow-up audit notes on 7535ef336 (static inspection only, no game files; adding only what wasn't in my earlier comment):

  1. Double-playback risk on Windows (ISpatialAudioClient found in #300): PR #300 found where GTA VI's software mixer sends its final mix on Windows — Windows Spatial Audio (ISpatialAudioClient, 48 kHz float). Because this PR both writes decoded PCM into p.output and unconditionally plays it via xaudio2::console_pcm, Windows users running #294 + #300 risk hearing every xapu-decoded sound twice (once properly mixed/attenuated via ISpatialAudioClient, plus a raw full-volume copy from console_pcm 0–460 ms offset). Adding a switch (e.g. XCL_CONSOLE_PCM=0/1, or defaulting it off on Windows once confirmed that p.output flows through ISpatialAudioClient) would let Windows use the game's real mix while keeping direct playback for Wine / SHAPE-only titles.
  2. Activate / Deactivate / XApuDisconnect never flush or clean up the console_pcm voice (acphal.rs:895-896, xaudio2.rs:1290+): Up to 23 queued buffers (~460 ms) keep playing after Deactivate and delay the next sound reusing the same stream slot by up to ~0.46 s, and XApuDisconnect leaves sink voices alive. Sending a Reset/Destroy control message keyed by (handle as usize, stream) fixes both and avoids collisions if a title opens two XApuConnect handles.
  3. Packet-length truncation & Activate MFT churn (acphal.rs:800, 894):
    • If a packet decodes to more frames than out.len() / ch (e.g. 40/60 ms packets or frames_per_output = 256), the excess PCM is discarded while the Opus decoder advances past the whole packet.
    • Rebuilding opus::Decoder on every Activate recreates Media Foundation MFTs on the title's audio thread when short sounds alternate Activate/Deactivate; calling flush() when channels is unchanged avoids that churn.
  4. Minor sink_thread & LibDecoder hardening:
    • Unbounded mpsc::channel (xaudio2.rs:1236) can grow without bound if sink_engine() stalls (e.g. under Wine); sync_channel + try_send bounds memory.
    • Failed CreateSourceVoice (xaudio2.rs:1319) retries and logs ~50×/s per stream.
    • LibDecoder::decode_packet skips parse_packet (unlike MftDecoder), so empty packets invoke 120 ms PLC instead of returning Err; and backend() can misreport MSOpusDecoder if mf_runtime() succeeds but MftDecoder::new falls back to libopus.

(AI-assisted — Gemini 4 Neon + Claude Opus/Sonnet 5.5)

**@⁠mastrr9** on GitHub · 2026-11-23 23:12 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7116687782) Follow-up audit notes on `7535ef336` (static inspection only, no game files; adding only what wasn't in my earlier comment): 1. **Double-playback risk on Windows (`ISpatialAudioClient` found in #300):** PR #300 found where GTA VI's software mixer sends its final mix on Windows — Windows Spatial Audio (`ISpatialAudioClient`, 48 kHz float). Because this PR both writes decoded PCM into `p.output` *and* unconditionally plays it via `xaudio2::console_pcm`, Windows users running #294 + #300 risk hearing every `xapu`-decoded sound **twice** (once properly mixed/attenuated via `ISpatialAudioClient`, plus a raw full-volume copy from `console_pcm` 0–460 ms offset). Adding a switch (e.g. `XCL_CONSOLE_PCM=0/1`, or defaulting it off on Windows once confirmed that `p.output` flows through `ISpatialAudioClient`) would let Windows use the game's real mix while keeping direct playback for Wine / SHAPE-only titles. 2. **`Activate` / `Deactivate` / `XApuDisconnect` never flush or clean up the `console_pcm` voice (`acphal.rs:895-896`, `xaudio2.rs:1290+`):** Up to 23 queued buffers (~460 ms) keep playing after `Deactivate` and delay the next sound reusing the same stream slot by up to ~0.46 s, and `XApuDisconnect` leaves sink voices alive. Sending a `Reset`/`Destroy` control message keyed by `(handle as usize, stream)` fixes both and avoids collisions if a title opens two `XApuConnect` handles. 3. **Packet-length truncation & `Activate` MFT churn (`acphal.rs:800`, `894`):** - If a packet decodes to more frames than `out.len() / ch` (e.g. 40/60 ms packets or `frames_per_output = 256`), the excess PCM is discarded while the Opus decoder advances past the whole packet. - Rebuilding `opus::Decoder` on every `Activate` recreates Media Foundation MFTs on the title's audio thread when short sounds alternate `Activate`/`Deactivate`; calling `flush()` when `channels` is unchanged avoids that churn. 4. **Minor `sink_thread` & `LibDecoder` hardening:** - Unbounded `mpsc::channel` (`xaudio2.rs:1236`) can grow without bound if `sink_engine()` stalls (e.g. under Wine); `sync_channel` + `try_send` bounds memory. - Failed `CreateSourceVoice` (`xaudio2.rs:1319`) retries and logs ~50×/s per stream. - `LibDecoder::decode_packet` skips `parse_packet` (unlike `MftDecoder`), so empty packets invoke 120 ms PLC instead of returning `Err`; and `backend()` can misreport `MSOpusDecoder` if `mf_runtime()` succeeds but `MftDecoder::new` falls back to `libopus`. *(AI-assisted — Gemini 4 Neon + Claude Opus/Sonnet 5.5)*
Author
Owner

@⁠simnJS on GitHub · 2026-11-23 23:22 UTC · original

Thanks to all three of you – the PR is updated (force-pushed, still two commits: 600ded9, 268e376), with the two xcl-smoke blocks in the description.

The biggest change came from looking further: the title reads the decoded PCM back, mixes it (its own volumes and panning) and plays its mix itself through Windows Spatial Audio on the default endpoint (ISpatialAudioClient, two static objects, seen with WINEDEBUG=+mmdevapi). So the raw per-stream playback (console_pcm) played every sound a second time, unmixed. It is gone: XCL now only decodes into the title's buffer. With it switched off the menu sound was still heard.

@⁠ethandepstein-del

  1. Ring-buffer use-after-free: the sink went away with console_pcm.
  2. LibDecoder now keeps a stream timestamp like MftDecoder (advanced by each packet's frames, reset in flush()).
  • Output alignment: the packet is decoded into a local Vec<f32> and copied into the title's buffer with copy_nonoverlapping.
  • Stream bounds: Activate / Deactivate on a stream the title did not connect are ignored, a Process on one gets silence of the length asked; no ch[0] fallback is left (XApuConnect already made at least one stream).
  • DLL handle: a candidate without the four exports is freed before the next one is tried.
  • Trace: the hex dump reads only the command's own size for its kind.

@⁠ersinhf thanks for the Windows run and the MFT check. The dropped-buffer limit you found was in console_pcm's sink, so it is gone too. If you post your temporary test (Activate, 25 Process, Deactivate, gated on opus::is_available()) or open it on top of this branch, I'm happy to take it.

@⁠ryosen0 thanks for running it with #300. Your run still had the raw playback (played on the PC: 143424 samples), so the sound you heard was probably doubled; this revision leaves only the title's own mix, if you get the chance to hear it again.

**@⁠simnJS** on GitHub · 2026-11-23 23:22 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7116873701) Thanks to all three of you – the PR is updated (force-pushed, still two commits: `600ded9`, `268e376`), with the two `xcl-smoke` blocks in the description. The biggest change came from looking further: the title reads the decoded PCM back, mixes it (its own volumes and panning) and plays its mix itself through Windows Spatial Audio on the default endpoint (`ISpatialAudioClient`, two static objects, seen with `WINEDEBUG=+mmdevapi`). So the raw per-stream playback (`console_pcm`) played every sound a second time, unmixed. It is gone: XCL now only decodes into the title's buffer. With it switched off the menu sound was still heard. @⁠ethandepstein-del 1. Ring-buffer use-after-free: the sink went away with `console_pcm`. 2. `LibDecoder` now keeps a stream timestamp like `MftDecoder` (advanced by each packet's frames, reset in `flush()`). - Output alignment: the packet is decoded into a local `Vec<f32>` and copied into the title's buffer with `copy_nonoverlapping`. - Stream bounds: Activate / Deactivate on a stream the title did not connect are ignored, a Process on one gets silence of the length asked; no `ch[0]` fallback is left (`XApuConnect` already made at least one stream). - DLL handle: a candidate without the four exports is freed before the next one is tried. - Trace: the hex dump reads only the command's own size for its kind. @⁠ersinhf thanks for the Windows run and the MFT check. The dropped-buffer limit you found was in `console_pcm`'s sink, so it is gone too. If you post your temporary test (Activate, 25 Process, Deactivate, gated on `opus::is_available()`) or open it on top of this branch, I'm happy to take it. @⁠ryosen0 thanks for running it with #300. Your run still had the raw playback (`played on the PC: 143424 samples`), so the sound you heard was probably doubled; this revision leaves only the title's own mix, if you get the chance to hear it again.
Author
Owner

@⁠mastrr9 on GitHub · 2026-11-23 23:30 UTC · original

Re-reviewed force-pushed head 268e376 (static inspection only on macOS — cargo test and Windows smoke.ps1 not run; no game files):

Confirmed fixed in 268e376

  • No double-playback / console_pcm removal (hle/acphal.rs, hle/xaudio2.rs): Removing XCL's extra XAudio2 playback voice cleanly resolves the Windows double-playback issue with ISpatialAudioClient, along with the ring-buffer reuse race, Activate/Deactivate/XApuDisconnect voice tail/leak, and unbounded mpsc::channel.
  • LibDecoder::timestamp_100ns() (hle/opus.rs:661, 682, 697, 735): Now tracks decoded stream time (n * 10_000_000 / output_rate) and resets to 0 on flush(), matching MftDecoder for Ogg stream-boundary detection.
  • p.output alignment & bounds (hle/acphal.rs:504-511): Decodes into a local Vec<f32> and copies byte-by-byte via copy_nonoverlapping into p.output, eliminating alignment UB while zeroing any trailing frames within out.len() * 4.
  • Out-of-range c.stream (hle/acphal.rs:480-496): Guarded with known / ch.get_mut(...), so an invalid stream index no longer clobbers stream 0's channel count or decoder.
  • XCL_TRACE_APU command sizing (hle/acphal.rs:260-266, 463): Uses command_len(kind) instead of reading past 24-byte commands like Deactivate.
  • LoadLibraryW cleanup (hle/opus.rs:635-637): Calls FreeLibrary if a candidate DLL lacks any of the four libopus symbols.

Remaining nits (non-blocking)

  • LibDecoder::decode_packet (hle/opus.rs:690): xapu already guards input_bytes == 0, so GTA VI is unaffected, but on the shared XAudio2 Opus path an empty slice passed to opus_decode(..., 0, ...) triggers libopus PLC instead of returning an error like MftDecoder (and i32::try_from(packet.len()) avoids wrapping on absurdly large lengths).
  • PR checks: Only failing because the Wine smoke.sh block reports exit: killed (no exit) — once a Windows tester drops in a clean scripts/smoke.ps1 pair for main and 268e376, this looks ready to go.

AI use: static code re-review of 268e376 with Antigravity (Gemini 4 Neon).

**@⁠mastrr9** on GitHub · 2026-11-23 23:30 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7117040459) Re-reviewed force-pushed head `268e376` (static inspection only on macOS — `cargo test` and Windows `smoke.ps1` not run; no game files): ### Confirmed fixed in `268e376` - **No double-playback / `console_pcm` removal (`hle/acphal.rs`, `hle/xaudio2.rs`):** Removing XCL's extra XAudio2 playback voice cleanly resolves the Windows double-playback issue with `ISpatialAudioClient`, along with the ring-buffer reuse race, `Activate`/`Deactivate`/`XApuDisconnect` voice tail/leak, and unbounded `mpsc::channel`. - **`LibDecoder::timestamp_100ns()` (`hle/opus.rs:661, 682, 697, 735`):** Now tracks decoded stream time (`n * 10_000_000 / output_rate`) and resets to `0` on `flush()`, matching `MftDecoder` for Ogg stream-boundary detection. - **`p.output` alignment & bounds (`hle/acphal.rs:504-511`):** Decodes into a local `Vec<f32>` and copies byte-by-byte via `copy_nonoverlapping` into `p.output`, eliminating alignment UB while zeroing any trailing frames within `out.len() * 4`. - **Out-of-range `c.stream` (`hle/acphal.rs:480-496`):** Guarded with `known` / `ch.get_mut(...)`, so an invalid stream index no longer clobbers stream 0's channel count or decoder. - **`XCL_TRACE_APU` command sizing (`hle/acphal.rs:260-266, 463`):** Uses `command_len(kind)` instead of reading past 24-byte commands like `Deactivate`. - **`LoadLibraryW` cleanup (`hle/opus.rs:635-637`):** Calls `FreeLibrary` if a candidate DLL lacks any of the four libopus symbols. ### Remaining nits (non-blocking) - **`LibDecoder::decode_packet` (`hle/opus.rs:690`):** `xapu` already guards `input_bytes == 0`, so GTA VI is unaffected, but on the shared XAudio2 Opus path an empty slice passed to `opus_decode(..., 0, ...)` triggers libopus PLC instead of returning an error like `MftDecoder` (and `i32::try_from(packet.len())` avoids wrapping on absurdly large lengths). - **`PR checks`:** Only failing because the Wine `smoke.sh` block reports `exit: killed (no exit)` — once a Windows tester drops in a clean `scripts/smoke.ps1` pair for `main` and `268e376`, this looks ready to go. *AI use: static code re-review of `268e376` with Antigravity (Gemini 4 Neon).*
Author
Owner

@⁠simnJS on GitHub · 2026-11-23 23:38 UTC · original

@⁠ethandepstein-del thanks for the re-review. New head 38bbfda (5bc2f12 + 38bbfda), from your earlier follow-up and this one:

  • LibDecoder::decode_packet runs parse_packet first, as MftDecoder does, so an empty or malformed packet is an error instead of libopus concealment.
  • The "Opus: decoder = …" line is logged after the decoder is made, so it names the one actually used (Media Foundation loading but failing to make a transform no longer reads as MSOpusDecoder).
  • A later Activate of a stream with the same channel count resets its decoder instead of building a new one (no MFT churn on Windows); Deactivate keeps it, and a Process outside Activate/Deactivate still gets silence.
  • PR checks: the killed was the grace I gave smoke.sh – under Wine XCL's end takes ~15 s (its watchdog), so the blocks are redone at 50 s and both runs now end by themselves (exit: 0x0).

Not changed: packets longer than the title's output buffer (40/60 ms) would still lose their tail; GTA's are all 20 ms / 960 frames, so I left a carry-over buffer out of this PR.

**@⁠simnJS** on GitHub · 2026-11-23 23:38 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7117187750) @⁠ethandepstein-del thanks for the re-review. New head `38bbfda` (`5bc2f12` + `38bbfda`), from your earlier follow-up and this one: - `LibDecoder::decode_packet` runs `parse_packet` first, as `MftDecoder` does, so an empty or malformed packet is an error instead of libopus concealment. - The "Opus: decoder = …" line is logged after the decoder is made, so it names the one actually used (Media Foundation loading but failing to make a transform no longer reads as MSOpusDecoder). - A later Activate of a stream with the same channel count resets its decoder instead of building a new one (no MFT churn on Windows); Deactivate keeps it, and a Process outside Activate/Deactivate still gets silence. - `PR checks`: the `killed` was the grace I gave `smoke.sh` – under Wine XCL's end takes ~15 s (its watchdog), so the blocks are redone at 50 s and both runs now end by themselves (`exit: 0x0`). Not changed: packets longer than the title's output buffer (40/60 ms) would still lose their tail; GTA's are all 20 ms / 960 frames, so I left a carry-over buffer out of this PR.
Author
Owner

@⁠ersinhf on GitHub · 2026-11-23 22:49 UTC · original · edited 2026-11-23 23:46 UTC

Updated for head 38bbfda (5bc2f12 + 38bbfda; the first version of this comment was about 6bae125). Windows run, clean tree, based on main 4017f8f. This covers the "Windows (the MFT path for xapu), the test suite" items; it does not cover scripts/smoke.ps1 (no retail title here).

Tested

  • NVIDIA GeForce RTX 4070 (Ada), driver 621.14 (32.0.16.2114); AMD Ryzen 5 7500F, 32 GB; Windows 11 build 26200; rustc 1.100.0 stable-x86_64-pc-windows-msvc; DXC 1.9.2602.17 (SDK 10.0.26100.0); no XCL_SAMPLE_* set
  • cargo build --workspace --release, then cargo test --workspace --release --no-fail-fast -- --test-threads=4: 652 passed, 0 failed, 40 ignored
  • cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4 (debug): 652 passed, 0 failed, 40 ignored
  • SKIPPED in both: gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware (no wave64)
  • Same counts as main 4017f8f on this machine; no new compiler warning (the fetch_update deprecation is on main too). 268e376 gave the same counts before the last push.

The xapu → MFT path on Windows, with the two tests below

Both pass on 38bbfda in debug and release, three runs each, and next to the PR's own acphal tests (9 / 9):

  • Opus: decoder = Windows' MSOpusDecoder (Media Foundation)
  • Activate (mono, the title's layout), 25 Process with the repo's 440 Hz libopus packets (MONO_HYBRID_20MS from opus.rs), first_frame 312 on the first: 648 frames, then 960 for each of the others; nothing left over past the frames written; the 440 Hz tone comes out; xapu_decode_errors stays 0
  • after Deactivate: 960 frames of silence
  • Activate again with the same layout (your new reset path, the MFT is flushed instead of rebuilt): 648 then 960 frames, and the samples are identical to what the first decoder gave for the same packets
  • an output buffer one byte off a 4-byte boundary: decoded into, nothing written outside it
  • stream 7 on a 2-stream connection: Activate / Deactivate ignored, a Process gives silence of the length asked, and stream 0 keeps decoding in sequence afterwards

The 2 dropped buffers from my first run were in console_pcm's sink, which is gone, so that note no longer applies.

The tests (for hle/acphal.rs's mod tests; gated on opus::is_available() like the opus.rs ones)
    // libopus test packets (the same as opus.rs's MONO_HYBRID_20MS: a 440 Hz tone, mono, 20 ms each)
    const OPUS_440HZ_20MS: &[&[u8]] = &[
        &[0x78, 0x81, 0x7b, 0xc6, 0x11, 0x76, 0xf4, 0x75, 0x00, 0x00, 0x07, 0x8e, 0xca, 0x69, 0xdb, 0xbb, 0xcc, 0x48, 0xdc, 0x16, 0xbd, 0x9b, 0xd3, 0x58, 0x27, 0x78, 0x93, 0xbc, 0x37, 0x44, 0x5e, 0xcf, 0x2d, 0x97, 0x00, 0x69, 0x80, 0x11, 0x80, 0x2c, 0x03, 0x38, 0xab, 0x45, 0x61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0xeb, 0xae, 0xba, 0x19, 0x9b, 0xdb, 0xe1, 0xd7, 0x19, 0xb5, 0xc8, 0xa1, 0x79, 0xd6, 0x1c, 0xb3, 0x68, 0xe5, 0x2b, 0x25, 0x98, 0x0c, 0x5c, 0xbd, 0x64, 0x08, 0x11, 0xbb, 0x14, 0xd0, 0xbb, 0x08, 0x0d, 0xf9, 0xff, 0xdb, 0x05],
        &[0x78, 0x99, 0xc2, 0x5f, 0x73, 0x2d, 0xd2, 0x2d, 0xed, 0xd7, 0x7f, 0xc4, 0x72, 0x9e, 0xe4, 0xeb, 0x27, 0x57, 0xa3, 0x16, 0xf3, 0xb3, 0xb6, 0x2c, 0x03, 0xfc, 0x49, 0x19, 0x83, 0x78, 0x64, 0x9d, 0x41, 0x4c, 0x6a, 0x16, 0xfc, 0x80, 0xea, 0x13, 0xc6, 0x03, 0x49, 0xbf, 0xa5, 0x19, 0x46, 0x91, 0x46, 0x8c, 0xc6, 0x1e, 0x3d, 0x86, 0xd9, 0x6e, 0x57, 0xa8, 0x95, 0x55, 0x90, 0x38, 0x9d, 0xf3, 0x03, 0x88, 0x71, 0x90, 0x83, 0x6f, 0x80, 0x8a, 0x96, 0x45, 0xb9, 0x64, 0xc3, 0xb6, 0x4d],
        &[0x78, 0x99, 0xc2, 0x5f, 0x73, 0x2d, 0xd2, 0x31, 0x33, 0xbf, 0x7b, 0x34, 0x8a, 0x71, 0x0f, 0x77, 0xd5, 0xd5, 0x1b, 0xda, 0x78, 0xa4, 0x47, 0xbb, 0x8c, 0x85, 0x53, 0xbe, 0x21, 0xd6, 0x5f, 0x9f, 0x2e, 0xba, 0x38, 0xfa, 0x2d, 0x32, 0xbc, 0xa1, 0xd7, 0xce, 0xb0, 0x1b, 0x08, 0x44, 0x28, 0x21, 0xcb, 0x80, 0x40, 0xaf, 0xc4, 0x08, 0xdc, 0x96, 0xfd, 0xb6, 0x95, 0x96, 0xda, 0xf3, 0xae, 0x6c, 0x2b, 0x04, 0xc4, 0x23, 0xb8, 0x12, 0x45, 0x51, 0xf9, 0x5f, 0x9b, 0xb0, 0xc6, 0x86, 0xed, 0x08, 0x0c],
    ];

    /// an xapu connection with `streams` streams; the handle
    unsafe fn xapu_connect(streams: u32) -> *mut c_void {
        let input = XApuConnectInput { process: 1, streams, commands_per_stream: 64, data_bytes: 0, frames_per_output: 960, options: 0 };
        let mut out = XApuConnectOutput { data: std::ptr::null_mut(), ready: std::ptr::null_mut() };
        let mut h = std::ptr::null_mut();
        assert_eq!(XApuConnect(&input, &mut out, &mut h), S_OK);
        h
    }

    /// sends a command (its bytes), returns the results it queued
    unsafe fn xapu_send(h: *mut c_void, command: *const u8) -> Vec<XApuResult> {
        let mut n = 0;
        assert_eq!(XApuEnqueueCommand(h, command as *const XApuCommand, &mut n), S_OK);
        let mut v = Vec::new();
        let mut r: XApuResult = std::mem::zeroed();
        while XApuDequeueResult(h, &mut r) == S_OK {
            v.push(r);
        }
        v
    }

    /// Activate / Deactivate as the title builds them: the header, channels at +24, the rate at +56
    unsafe fn xapu_control(h: *mut c_void, kind: u32, stream: u32, channels: u32) {
        let mut c = [0u8; 64];
        c[0..4].copy_from_slice(&kind.to_le_bytes());
        c[4..8].copy_from_slice(&stream.to_le_bytes());
        c[24..28].copy_from_slice(&channels.to_le_bytes());
        c[56..60].copy_from_slice(&48_000u32.to_le_bytes());
        xapu_send(h, c.as_ptr());
    }

    /// a Process of one packet into `out` (float32 at any byte address); the frames the result reports
    unsafe fn xapu_process(h: *mut c_void, stream: u32, packet: &[u8], first_frame: u32, out: *mut u8, out_bytes: u32) -> u32 {
        let p = XApuProcess {
            id: XApuCommand { kind: XAPU_PROCESS, stream, sequence: 0, options: 0, context: std::ptr::null_mut() },
            ramp: 0.0,
            pitch: 48000.0,
            first_frame,
            frames: 960,
            input_bytes: packet.len() as u32,
            input: packet.as_ptr() as *mut c_void,
            output_bytes: out_bytes,
            output: out as *mut c_void,
        };
        let r = xapu_send(h, &p as *const _ as *const u8);
        let r = r.iter().rev().find(|r| { let k = r.id.kind; k == XAPU_PROCESS }).copied().expect("a Process result");
        r.frames
    }

    /// float32 samples at a byte address that may not be 4-byte aligned
    unsafe fn read_f32s(p: *const u8, n: usize) -> Vec<f32> {
        (0..n).map(|i| (p.add(i * 4) as *const f32).read_unaligned()).collect()
    }

    fn tone_energy(samples: &[f32], freq: f64) -> f64 {
        let n = samples.len();
        let k = (0.5 + (n as f64 * freq) / 48_000.0).floor();
        let w = 2.0 * std::f64::consts::PI * k / n as f64;
        let c = 2.0 * w.cos();
        let (mut s1, mut s2) = (0.0, 0.0);
        for &x in samples {
            let s0 = x as f64 + c * s1 - s2;
            s2 = s1;
            s1 = s0;
        }
        (s1 * s1 + s2 * s2 - c * s1 * s2).sqrt() / n as f64
    }

    /// The title's sequence (Activate, Process per packet with the pre-skip on the first, Deactivate)
    /// decodes the Opus packets into its output buffer.
    #[test]
    fn xapu_decodes_the_titles_opus_packets_into_its_buffer() {
        if !opus::is_available() {
            eprintln!("skipping: no Opus decoder");
            return;
        }
        unsafe {
            let h = xapu_connect(2);
            xapu_control(h, XAPU_ACTIVATE, 0, 1);
            let before = xaudio2::stats();
            let (mut frames, mut all) = (Vec::new(), Vec::new());
            for round in 0..5 {
                for (i, &pkt) in OPUS_440HZ_20MS.iter().enumerate() {
                    let mut buf = vec![7.0f32; 960];
                    let first = if round == 0 && i == 0 { 312 } else { 0 };
                    let f = xapu_process(h, 0, pkt, first, buf.as_mut_ptr() as *mut u8, 960 * 4);
                    assert!(buf[f as usize..].iter().all(|&s| s == 0.0), "past the frames written: silence, not what was there");
                    frames.push(f);
                    all.extend_from_slice(&buf[..f as usize]);
                }
            }
            assert_eq!(frames[0], 960 - 312, "first_frame (the pre-skip) is left out");
            assert!(frames[1..].iter().all(|&f| f == 960), "a 20 ms packet is 960 frames");
            assert!(all.iter().any(|s| s.abs() > 0.05), "the output is not silent");
            let (e440, e880) = (tone_energy(&all[480..], 440.0), tone_energy(&all[480..], 880.0));
            assert!(e440 > e880 * 10.0, "the 440 Hz tone comes out ({e440} vs {e880})");
            let a = xaudio2::stats();
            // the counters are global: other tests running beside this one may add to them
            assert!(a.xapu_packets_decoded - before.xapu_packets_decoded >= 25, "report.json counts the packets");
            assert_eq!(a.xapu_decode_errors - before.xapu_decode_errors, 0);

            // Deactivate: the stream has no decoder, a Process answers silence of the length asked
            xapu_control(h, XAPU_DEACTIVATE, 0, 0);
            let mut buf = vec![7.0f32; 960];
            assert_eq!(xapu_process(h, 0, OPUS_440HZ_20MS[1], 0, buf.as_mut_ptr() as *mut u8, 960 * 4), 960);
            assert!(buf.iter().all(|&s| s == 0.0), "a deactivated stream gives silence");

            // Activate again with the same layout (the decoder is reset, not rebuilt): the stream starts
            // over, pre-skip and all
            xapu_control(h, XAPU_ACTIVATE, 0, 1);
            let mut again = Vec::new();
            for (i, &pkt) in OPUS_440HZ_20MS.iter().enumerate() {
                let mut buf = vec![7.0f32; 960];
                let f = xapu_process(h, 0, pkt, if i == 0 { 312 } else { 0 }, buf.as_mut_ptr() as *mut u8, 960 * 4);
                assert_eq!(f, if i == 0 { 648 } else { 960 }, "packet {i} after the second Activate");
                again.extend_from_slice(&buf[..f as usize]);
            }
            assert_eq!(again, all[..again.len()], "a reset decoder gives what a new one gave");
            assert_eq!(XApuDisconnect(h), S_OK);
        }
    }

    /// The title's output buffer need not be 4-byte aligned, and a stream the connection does not have
    /// gets silence without touching stream 0.
    #[test]
    fn xapu_writes_unaligned_buffers_and_ignores_unknown_streams() {
        if !opus::is_available() {
            eprintln!("skipping: no Opus decoder");
            return;
        }
        unsafe {
            let h = xapu_connect(2);
            xapu_control(h, XAPU_ACTIVATE, 0, 1);
            // one byte off a 4-byte boundary, guarded on both sides
            let mut raw = vec![0xAAu8; 960 * 4 + 8];
            let out = raw.as_mut_ptr().add(if raw.as_ptr() as usize % 4 == 0 { 1 } else { 0 });
            let f = xapu_process(h, 0, OPUS_440HZ_20MS[0], 0, out, 960 * 4);
            assert_eq!(f, 960);
            let s = read_f32s(out, 960);
            assert!(s.iter().any(|x| x.abs() > 0.01), "decoded into the unaligned buffer");
            let off = out as usize - raw.as_ptr() as usize;
            assert!(raw[..off].iter().all(|&b| b == 0xAA) && raw[off + 960 * 4..].iter().all(|&b| b == 0xAA), "nothing written outside it");

            // stream 7 on a 2-stream connection: Activate / Deactivate are ignored, a Process is silence
            xapu_control(h, XAPU_ACTIVATE, 7, 2);
            let mut buf = vec![7.0f32; 960];
            assert_eq!(xapu_process(h, 7, OPUS_440HZ_20MS[1], 0, buf.as_mut_ptr() as *mut u8, 960 * 4), 960, "the length asked, mono like stream 0");
            assert!(buf.iter().all(|&s| s == 0.0), "an unknown stream gives silence");
            xapu_control(h, XAPU_DEACTIVATE, 7, 0);
            // stream 0 still has its decoder and its state: the next packet decodes in sequence
            let mut buf = vec![0.0f32; 960];
            assert_eq!(xapu_process(h, 0, OPUS_440HZ_20MS[1], 0, buf.as_mut_ptr() as *mut u8, 960 * 4), 960);
            assert!(buf.iter().any(|x| x.abs() > 0.01), "stream 0 still decodes");
            assert_eq!(XApuDisconnect(h), S_OK);
        }
    }

The xapu_packets_decoded check is >=, because the counters are global and the two tests run in parallel.

Not tested

  • scripts/smoke.ps1 / a retail title (no game here), so I could not listen to the title's own mix through Spatial Audio
  • libopus (opus.dll) on Windows, stereo xapu streams, a long continuous stream

AI use

  • Claude Code with Claude Opus 5.5 ran the builds, the suites and the tests on this machine, wrote the tests and this comment; the person posting it checked each point.
**@⁠ersinhf** on GitHub · 2026-11-23 22:49 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7116228416) · edited 2026-11-23 23:46 UTC **Updated for head `38bbfda`** (`5bc2f12` + `38bbfda`; the first version of this comment was about `6bae125`). Windows run, clean tree, based on `main` 4017f8f. This covers the "Windows (the MFT path for xapu), the test suite" items; it does not cover `scripts/smoke.ps1` (no retail title here). **Tested** - NVIDIA GeForce RTX 4070 (Ada), driver 621.14 (32.0.16.2114); AMD Ryzen 5 7500F, 32 GB; Windows 11 build 26200; rustc 1.100.0 `stable-x86_64-pc-windows-msvc`; DXC 1.9.2602.17 (SDK 10.0.26100.0); no `XCL_SAMPLE_*` set - `cargo build --workspace --release`, then `cargo test --workspace --release --no-fail-fast -- --test-threads=4`: **652 passed, 0 failed, 40 ignored** - `cargo build --workspace`, then `cargo test --workspace --no-fail-fast -- --test-threads=4` (debug): **652 passed, 0 failed, 40 ignored** - `SKIPPED` in both: `gpu_geometry_wave32_prefix_count_over_a_mask`, `gpu_wave32_program_in_wave64_hardware` (no wave64) - Same counts as `main` 4017f8f on this machine; no new compiler warning (the `fetch_update` deprecation is on `main` too). `268e376` gave the same counts before the last push. **The xapu → MFT path on Windows, with the two tests below** Both pass on `38bbfda` in debug and release, three runs each, and next to the PR's own `acphal` tests (9 / 9): - `Opus: decoder = Windows' MSOpusDecoder (Media Foundation)` - Activate (mono, the title's layout), 25 Process with the repo's 440 Hz libopus packets (`MONO_HYBRID_20MS` from `opus.rs`), `first_frame` 312 on the first: 648 frames, then 960 for each of the others; nothing left over past the frames written; the 440 Hz tone comes out; `xapu_decode_errors` stays 0 - after Deactivate: 960 frames of silence - Activate again with the same layout (your new reset path, the MFT is flushed instead of rebuilt): 648 then 960 frames, and the samples are identical to what the first decoder gave for the same packets - an output buffer one byte off a 4-byte boundary: decoded into, nothing written outside it - stream 7 on a 2-stream connection: Activate / Deactivate ignored, a Process gives silence of the length asked, and stream 0 keeps decoding in sequence afterwards The 2 dropped buffers from my first run were in `console_pcm`'s sink, which is gone, so that note no longer applies. <details><summary>The tests (for <code>hle/acphal.rs</code>'s <code>mod tests</code>; gated on <code>opus::is_available()</code> like the <code>opus.rs</code> ones)</summary> ```rust // libopus test packets (the same as opus.rs's MONO_HYBRID_20MS: a 440 Hz tone, mono, 20 ms each) const OPUS_440HZ_20MS: &[&[u8]] = &[ &[0x78, 0x81, 0x7b, 0xc6, 0x11, 0x76, 0xf4, 0x75, 0x00, 0x00, 0x07, 0x8e, 0xca, 0x69, 0xdb, 0xbb, 0xc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xb0, 0x1b, 0x08, 0x44, 0x28, 0x21, 0xcb, 0x80, 0x40, 0xaf, 0xc4, 0x08, 0xdc, 0x96, 0xfd, 0xb6, 0x95, 0x96, 0xda, 0xf3, 0xae, 0x6c, 0x2b, 0x04, 0xc4, 0x23, 0xb8, 0x12, 0x45, 0x51, 0xf9, 0x5f, 0x9b, 0xb0, 0xc6, 0x86, 0xed, 0x08, 0x0c], ]; /// an xapu connection with `streams` streams; the handle unsafe fn xapu_connect(streams: u32) -> *mut c_void { let input = XApuConnectInput { process: 1, streams, commands_per_stream: 64, data_bytes: 0, frames_per_output: 960, options: 0 }; let mut out = XApuConnectOutput { data: std::ptr::null_mut(), ready: std::ptr::null_mut() }; let mut h = std::ptr::null_mut(); assert_eq!(XApuConnect(&input, &mut out, &mut h), S_OK); h } /// sends a command (its bytes), returns the results it queued unsafe fn xapu_send(h: *mut c_void, command: *const u8) -> Vec<XApuResult> { let mut n = 0; assert_eq!(XApuEnqueueCommand(h, command as *const XApuCommand, &mut n), S_OK); let mut v = Vec::new(); let mut r: XApuResult = std::mem::zeroed(); while XApuDequeueResult(h, &mut r) == S_OK { v.push(r); } v } /// Activate / Deactivate as the title builds them: the header, channels at +24, the rate at +56 unsafe fn xapu_control(h: *mut c_void, kind: u32, stream: u32, channels: u32) { let mut c = [0u8; 64]; c[0..4].copy_from_slice(&kind.to_le_bytes()); c[4..8].copy_from_slice(&stream.to_le_bytes()); c[24..28].copy_from_slice(&channels.to_le_bytes()); c[56..60].copy_from_slice(&48_000u32.to_le_bytes()); xapu_send(h, c.as_ptr()); } /// a Process of one packet into `out` (float32 at any byte address); the frames the result reports unsafe fn xapu_process(h: *mut c_void, stream: u32, packet: &[u8], first_frame: u32, out: *mut u8, out_bytes: u32) -> u32 { let p = XApuProcess { id: XApuCommand { kind: XAPU_PROCESS, stream, sequence: 0, options: 0, context: std::ptr::null_mut() }, ramp: 0.0, pitch: 48000.0, first_frame, frames: 960, input_bytes: packet.len() as u32, input: packet.as_ptr() as *mut c_void, output_bytes: out_bytes, output: out as *mut c_void, }; let r = xapu_send(h, &p as *const _ as *const u8); let r = r.iter().rev().find(|r| { let k = r.id.kind; k == XAPU_PROCESS }).copied().expect("a Process result"); r.frames } /// float32 samples at a byte address that may not be 4-byte aligned unsafe fn read_f32s(p: *const u8, n: usize) -> Vec<f32> { (0..n).map(|i| (p.add(i * 4) as *const f32).read_unaligned()).collect() } fn tone_energy(samples: &[f32], freq: f64) -> f64 { let n = samples.len(); let k = (0.5 + (n as f64 * freq) / 48_000.0).floor(); let w = 2.0 * std::f64::consts::PI * k / n as f64; let c = 2.0 * w.cos(); let (mut s1, mut s2) = (0.0, 0.0); for &x in samples { let s0 = x as f64 + c * s1 - s2; s2 = s1; s1 = s0; } (s1 * s1 + s2 * s2 - c * s1 * s2).sqrt() / n as f64 } /// The title's sequence (Activate, Process per packet with the pre-skip on the first, Deactivate) /// decodes the Opus packets into its output buffer. #[test] fn xapu_decodes_the_titles_opus_packets_into_its_buffer() { if !opus::is_available() { eprintln!("skipping: no Opus decoder"); return; } unsafe { let h = xapu_connect(2); xapu_control(h, XAPU_ACTIVATE, 0, 1); let before = xaudio2::stats(); let (mut frames, mut all) = (Vec::new(), Vec::new()); for round in 0..5 { for (i, &pkt) in OPUS_440HZ_20MS.iter().enumerate() { let mut buf = vec![7.0f32; 960]; let first = if round == 0 && i == 0 { 312 } else { 0 }; let f = xapu_process(h, 0, pkt, first, buf.as_mut_ptr() as *mut u8, 960 * 4); assert!(buf[f as usize..].iter().all(|&s| s == 0.0), "past the frames written: silence, not what was there"); frames.push(f); all.extend_from_slice(&buf[..f as usize]); } } assert_eq!(frames[0], 960 - 312, "first_frame (the pre-skip) is left out"); assert!(frames[1..].iter().all(|&f| f == 960), "a 20 ms packet is 960 frames"); assert!(all.iter().any(|s| s.abs() > 0.05), "the output is not silent"); let (e440, e880) = (tone_energy(&all[480..], 440.0), tone_energy(&all[480..], 880.0)); assert!(e440 > e880 * 10.0, "the 440 Hz tone comes out ({e440} vs {e880})"); let a = xaudio2::stats(); // the counters are global: other tests running beside this one may add to them assert!(a.xapu_packets_decoded - before.xapu_packets_decoded >= 25, "report.json counts the packets"); assert_eq!(a.xapu_decode_errors - before.xapu_decode_errors, 0); // Deactivate: the stream has no decoder, a Process answers silence of the length asked xapu_control(h, XAPU_DEACTIVATE, 0, 0); let mut buf = vec![7.0f32; 960]; assert_eq!(xapu_process(h, 0, OPUS_440HZ_20MS[1], 0, buf.as_mut_ptr() as *mut u8, 960 * 4), 960); assert!(buf.iter().all(|&s| s == 0.0), "a deactivated stream gives silence"); // Activate again with the same layout (the decoder is reset, not rebuilt): the stream starts // over, pre-skip and all xapu_control(h, XAPU_ACTIVATE, 0, 1); let mut again = Vec::new(); for (i, &pkt) in OPUS_440HZ_20MS.iter().enumerate() { let mut buf = vec![7.0f32; 960]; let f = xapu_process(h, 0, pkt, if i == 0 { 312 } else { 0 }, buf.as_mut_ptr() as *mut u8, 960 * 4); assert_eq!(f, if i == 0 { 648 } else { 960 }, "packet {i} after the second Activate"); again.extend_from_slice(&buf[..f as usize]); } assert_eq!(again, all[..again.len()], "a reset decoder gives what a new one gave"); assert_eq!(XApuDisconnect(h), S_OK); } } /// The title's output buffer need not be 4-byte aligned, and a stream the connection does not have /// gets silence without touching stream 0. #[test] fn xapu_writes_unaligned_buffers_and_ignores_unknown_streams() { if !opus::is_available() { eprintln!("skipping: no Opus decoder"); return; } unsafe { let h = xapu_connect(2); xapu_control(h, XAPU_ACTIVATE, 0, 1); // one byte off a 4-byte boundary, guarded on both sides let mut raw = vec![0xAAu8; 960 * 4 + 8]; let out = raw.as_mut_ptr().add(if raw.as_ptr() as usize % 4 == 0 { 1 } else { 0 }); let f = xapu_process(h, 0, OPUS_440HZ_20MS[0], 0, out, 960 * 4); assert_eq!(f, 960); let s = read_f32s(out, 960); assert!(s.iter().any(|x| x.abs() > 0.01), "decoded into the unaligned buffer"); let off = out as usize - raw.as_ptr() as usize; assert!(raw[..off].iter().all(|&b| b == 0xAA) && raw[off + 960 * 4..].iter().all(|&b| b == 0xAA), "nothing written outside it"); // stream 7 on a 2-stream connection: Activate / Deactivate are ignored, a Process is silence xapu_control(h, XAPU_ACTIVATE, 7, 2); let mut buf = vec![7.0f32; 960]; assert_eq!(xapu_process(h, 7, OPUS_440HZ_20MS[1], 0, buf.as_mut_ptr() as *mut u8, 960 * 4), 960, "the length asked, mono like stream 0"); assert!(buf.iter().all(|&s| s == 0.0), "an unknown stream gives silence"); xapu_control(h, XAPU_DEACTIVATE, 7, 0); // stream 0 still has its decoder and its state: the next packet decodes in sequence let mut buf = vec![0.0f32; 960]; assert_eq!(xapu_process(h, 0, OPUS_440HZ_20MS[1], 0, buf.as_mut_ptr() as *mut u8, 960 * 4), 960); assert!(buf.iter().any(|x| x.abs() > 0.01), "stream 0 still decodes"); assert_eq!(XApuDisconnect(h), S_OK); } } ``` The `xapu_packets_decoded` check is `>=`, because the counters are global and the two tests run in parallel. </details> **Not tested** - `scripts/smoke.ps1` / a retail title (no game here), so I could not listen to the title's own mix through Spatial Audio - libopus (`opus.dll`) on Windows, stereo xapu streams, a long continuous stream **AI use** - Claude Code with Claude Opus 5.5 ran the builds, the suites and the tests on this machine, wrote the tests and this comment; the person posting it checked each point.
Author
Owner

@⁠ersinhf on GitHub · 2026-11-23 23:46 UTC · original

@⁠simnJS I updated my comment above for 38bbfda (Windows, debug and release: 652 / 0 / 40) and put the two xapu tests in it: the title's sequence through the MFT including your new reset on a second Activate, plus an unaligned output buffer and an unknown stream. Both pass here; take them if they fit.

Claude Code with Claude Opus 5.5 wrote this; the person posting it checked it.

**@⁠ersinhf** on GitHub · 2026-11-23 23:46 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7117352235) @⁠simnJS I updated my comment above for `38bbfda` (Windows, debug and release: 652 / 0 / 40) and put the two xapu tests in it: the title's sequence through the MFT including your new reset on a second Activate, plus an unaligned output buffer and an unknown stream. Both pass here; take them if they fit. *Claude Code with Claude Opus 5.5 wrote this; the person posting it checked it.*
Author
Owner

@⁠ivall on GitHub · 2026-11-23 23:48 UTC · original

Merged as a squash commit on main (2b4bb43), with the game's name left out of the message and two code comments (the repository does not name it) - thanks! Checked on an RX 9070 (RDNA4) on main 2b4bb43 together with #306, #288 and #294: cargo build --workspace && cargo test --workspace -- --test-threads=4 - 630 unit tests passed, 0 failed; the retail game reaches its menus and starts loading the world (stopped at ~150 s by the machine's commit limit, not by the game). On Windows the decoder is Windows' MSOpusDecoder: xapu: … Opus packets decoded (0 errors) with non-zero samples once the intro starts, ~95 packets every 5 s.

**@⁠ivall** on GitHub · 2026-11-23 23:48 UTC · [original](https://github.com/xcl-dev/xcl/pull/294#issuecomment-7117384811) Merged as a squash commit on main (2b4bb43), with the game's name left out of the message and two code comments (the repository does not name it) - thanks! Checked on an RX 9070 (RDNA4) on main 2b4bb43 together with #306, #288 and #294: `cargo build --workspace && cargo test --workspace -- --test-threads=4` - 630 unit tests passed, 0 failed; the retail game reaches its menus and starts loading the world (stopped at ~150 s by the machine's commit limit, not by the game). On Windows the decoder is Windows' MSOpusDecoder: `xapu: … Opus packets decoded (0 errors)` with non-zero samples once the intro starts, ~95 packets every 5 s.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.