XAudio2: add lock-free hook trampoline lookup, atomic silent-voice fast path, and zero-copy decoded PCM #2683

Open
github-bot wants to merge 1 commit from github-bot/gh-2683 into main AGit
Owner

@⁠Decodere on GitHub · 2026-11-26 06:11 UTC · original
Decodere:fix-xaudio2-lockfree-dispatch-and-zerocopy-pcm → main · +225 −29 · 1 files · 1 commits · open

What is in it

Removes per-call global mutex traffic, eliminates decoded PCM double-allocation/byte-copying, and replaces up-to-32 MiB decode-error heap allocations with the shared silence mapping in crates/xcl/src/hle/xaudio2.rs:

  • Lock-free hook trampoline lookup (FastOriginals, FAST_ORIG_CAP = 32): Mirrors the first 32 (vtable, slot, orig) entries published in patch() into FAST_ORIGINALS (Release/Acquire len, while still pushing to ORIGINALS so existing checks remain intact). original() now resolves patched slots lock-free without acquiring ORIGINALS, falling back to ORIGINALS.lock() only if the 32-slot cache is full.
  • Atomic silent-voice fast path (SILENT_LIVE_COUNT): Tracks live silent voices via SILENT_LIVE_COUNT: AtomicUsize updated strictly while holding the XMA lock (create_source_voice on .is_none(), destroy_voice on .is_some()), allowing submit_source_buffer and destroy_voice to bypass XMA.lock() when zero silent voices exist.
  • Zero-copy decoded PCM16 handoff (DecodedBuffer._pcm: Vec<i16> + prepare_decoded_pcm): Asserts cfg!(target_endian = "little") at compile time and hands decoded Vec<i16> buffers directly to XAudio2 without allocating a second Vec<u8> or copying 2 bytes per sample. prepare_decoded_pcm clamps whole frames within XAUDIO2_MAX_BUFFER_BYTES, returns None if fewer than 1 complete frame was decoded, and constructs Box::new(DecodedBuffer { ... }) before reading boxed._pcm.as_ptr().
  • Shared silence() fallback (prepare_fallback_silence): On decode error or < 1 decoded frame, submit_decoded_buffer points nb.audio_data at the process-wide read-only silence() mapping with _pcm: Vec::new() (0 bytes heap allocated, never overwriting nb.audio_data / nb.audio_bytes when _pcm.is_empty()), instead of allocating up to SILENCE_BYTES (32 MiB) on the heap.
  • Leaves pcm16_for_rate, submit_decoded_buffer entry, get_state, DECODED_VOICES teardown, and existing tests untouched.

Tested

  • Failing-first debug verification on unmodified origin/main (b49be183, cargo test -p xcl --lib "hle::xaudio2::tests::failing_first" -- --test-threads=1 --nocapture): confirmed pre-fix submit_decoded_buffer byte-by-byte conversion copied Vec<i16> into a separate heap allocation (0x445320 != 0x445410) and did not reject < 1 complete frame.
  • Post-fix debug WARP targeted tests (XCL_ADAPTER=warp, XCL_WARP=1, cargo test -p xcl --lib "hle::xaudio2::tests::" -- --test-threads=1 --nocapture): 12 passed; 0 failed; 0 ignored; 0 skipped (0.25s, including real Windows XAudio2 2.9 Opus & XMA2 decode/fallback and engine_from_the_system_dll; zero compiler warnings in xaudio2.rs).
  • Post-fix release WARP targeted tests (XCL_ADAPTER=warp, XCL_WARP=1, cargo test --release -p xcl --lib "hle::xaudio2::tests::" -- --test-threads=1 --nocapture): 12 passed; 0 failed; 0 ignored; 0 skipped (1.28s).
    • Release micro-benchmark (XAUDIO2_BENCH_NS):
      • original lookup over 6 entries (200,000 iters): 21.21 ns -> 3.65 ns (5.8x faster, WARP run) / 17.98 ns -> 3.74 ns (4.8x faster, RTX run).
      • 1920-sample (20 ms stereo 48 kHz) PCM16 buffer handoff (20,000 iters): 4,365.6 ns -> 131.5 ns (33.2x faster, WARP run) / 2,203.0 ns -> 121.9 ns (18.1x faster, RTX run).
  • Clippy check (cargo clippy --all-targets): 0 new warnings in crates/xcl/src/hle/xaudio2.rs (only the 3 pre-existing lints on untouched XAudio2Create, XAudio2CreateWithVersionInfo, and create_decoded_voice).
  • Post-fix release RTX 4060 targeted tests (cargo test --release -p xcl --lib "hle::xaudio2::tests::" -- --test-threads=1 --nocapture): 12 passed; 0 failed; 0 ignored; 0 skipped (0.41s).

Regression run

  • Full release workspace on RTX 4060 (cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture): 37 test binaries, 1438 passed; 0 failed; 47 ignored, 29 pre-existing environment-gated SKIPPED lines:

    • 21 skipped: no wave64 (RTX 4060 is wave32)
    • 3 skipped: wave32 per-lane form: refused by driver (f16 arithmetic, f16 packed, f32 conversions)
    • 3 skipped: no D3D12 debug layer (d3d12SDKLayers.dll unavailable on host: debug-layer dred: false/true and uploads_start_from_each_subresources_state)
    • 1 skipped: pso_measurement_compiles_an_exact_synthetic_record (cannot disable driver cache on Windows)
    • 1 skipped: heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows)
  • Paired 60 s RTX 4060 smoke capture (scripts/smoke.ps1):

Base (origin/main b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7):

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1433 (PresentX 1434)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14015 MB

PR (c970f2257e0935d8e1c17f14e62d9aade3838ee4):

xcl-smoke v1
commit: c970f2257e0935d8e1c17f14e62d9aade3838ee4
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1316 (PresentX 1317)
presents per 2 s (last 3): 6 36 60
device removals: 0
crashes: 0
peak commit: 13979 MB

Not tested

  • Live multi-hour retail audio streaming with sustained concurrent decode errors beyond the unit tests and 60 s smoke capture.
  • The 29 host-gated workspace tests skipped on this RTX 4060 machine (wave64 hardware, wave32 per-lane driver support, D3D12 SDK debug layer, driver cache disable, and heap windows).

AI use

Google Antigravity (Gemini 4 Neon) wrote the patch, unit tests, and PR description; all commands, test runs, micro-benchmarks, and paired 60 s GPU smoke captures were executed directly in this workspace.

**@⁠Decodere** on GitHub · 2026-11-26 06:11 UTC · [original](https://github.com/xcl-dev/xcl/pull/2683) `Decodere:fix-xaudio2-lockfree-dispatch-and-zerocopy-pcm` → `main` · +225 −29 · 1 files · 1 commits · open **What is in it** Removes per-call global mutex traffic, eliminates decoded PCM double-allocation/byte-copying, and replaces up-to-32 MiB decode-error heap allocations with the shared silence mapping in `crates/xcl/src/hle/xaudio2.rs`: - **Lock-free hook trampoline lookup (`FastOriginals`, `FAST_ORIG_CAP = 32`):** Mirrors the first 32 `(vtable, slot, orig)` entries published in `patch()` into `FAST_ORIGINALS` (Release/Acquire `len`, while still pushing to `ORIGINALS` so existing checks remain intact). `original()` now resolves patched slots lock-free without acquiring `ORIGINALS`, falling back to `ORIGINALS.lock()` only if the 32-slot cache is full. - **Atomic silent-voice fast path (`SILENT_LIVE_COUNT`):** Tracks live silent voices via `SILENT_LIVE_COUNT: AtomicUsize` updated strictly while holding the `XMA` lock (`create_source_voice` on `.is_none()`, `destroy_voice` on `.is_some()`), allowing `submit_source_buffer` and `destroy_voice` to bypass `XMA.lock()` when zero silent voices exist. - **Zero-copy decoded PCM16 handoff (`DecodedBuffer._pcm: Vec<i16>` + `prepare_decoded_pcm`):** Asserts `cfg!(target_endian = "little")` at compile time and hands decoded `Vec<i16>` buffers directly to XAudio2 without allocating a second `Vec<u8>` or copying 2 bytes per sample. `prepare_decoded_pcm` clamps whole frames within `XAUDIO2_MAX_BUFFER_BYTES`, returns `None` if fewer than 1 complete frame was decoded, and constructs `Box::new(DecodedBuffer { ... })` before reading `boxed._pcm.as_ptr()`. - **Shared `silence()` fallback (`prepare_fallback_silence`):** On decode error or `< 1` decoded frame, `submit_decoded_buffer` points `nb.audio_data` at the process-wide read-only `silence()` mapping with `_pcm: Vec::new()` (0 bytes heap allocated, never overwriting `nb.audio_data` / `nb.audio_bytes` when `_pcm.is_empty()`), instead of allocating up to `SILENCE_BYTES` (32 MiB) on the heap. - Leaves `pcm16_for_rate`, `submit_decoded_buffer` entry, `get_state`, `DECODED_VOICES` teardown, and existing tests untouched. **Tested** - **Failing-first debug verification** on unmodified `origin/main` (`b49be183`, `cargo test -p xcl --lib "hle::xaudio2::tests::failing_first" -- --test-threads=1 --nocapture`): confirmed pre-fix `submit_decoded_buffer` byte-by-byte conversion copied `Vec<i16>` into a separate heap allocation (`0x445320 != 0x445410`) and did not reject `< 1` complete frame. - **Post-fix debug WARP targeted tests** (`XCL_ADAPTER=warp`, `XCL_WARP=1`, `cargo test -p xcl --lib "hle::xaudio2::tests::" -- --test-threads=1 --nocapture`): `12 passed; 0 failed; 0 ignored; 0 skipped` (`0.25s`, including real Windows XAudio2 2.9 Opus & XMA2 decode/fallback and `engine_from_the_system_dll`; zero compiler warnings in `xaudio2.rs`). - **Post-fix release WARP targeted tests** (`XCL_ADAPTER=warp`, `XCL_WARP=1`, `cargo test --release -p xcl --lib "hle::xaudio2::tests::" -- --test-threads=1 --nocapture`): `12 passed; 0 failed; 0 ignored; 0 skipped` (`1.28s`). - Release micro-benchmark (`XAUDIO2_BENCH_NS`): - `original` lookup over 6 entries (200,000 iters): `21.21 ns` -> `3.65 ns` (`5.8x` faster, WARP run) / `17.98 ns` -> `3.74 ns` (`4.8x` faster, RTX run). - 1920-sample (20 ms stereo 48 kHz) PCM16 buffer handoff (20,000 iters): `4,365.6 ns` -> `131.5 ns` (`33.2x` faster, WARP run) / `2,203.0 ns` -> `121.9 ns` (`18.1x` faster, RTX run). - **Clippy check** (`cargo clippy --all-targets`): `0` new warnings in `crates/xcl/src/hle/xaudio2.rs` (only the 3 pre-existing lints on untouched `XAudio2Create`, `XAudio2CreateWithVersionInfo`, and `create_decoded_voice`). - **Post-fix release RTX 4060 targeted tests** (`cargo test --release -p xcl --lib "hle::xaudio2::tests::" -- --test-threads=1 --nocapture`): `12 passed; 0 failed; 0 ignored; 0 skipped` (`0.41s`). **Regression run** - **Full release workspace on RTX 4060** (`cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture`): `37` test binaries, `1438 passed; 0 failed; 47 ignored`, `29` pre-existing environment-gated `SKIPPED` lines: - `21` skipped: `no wave64` (RTX 4060 is wave32) - `3` skipped: wave32 `per-lane form: refused` by driver (`f16 arithmetic`, `f16 packed`, `f32 conversions`) - `3` skipped: no D3D12 debug layer (`d3d12SDKLayers.dll` unavailable on host: debug-layer `dred: false`/`true` and `uploads_start_from_each_subresources_state`) - `1` skipped: `pso_measurement_compiles_an_exact_synthetic_record` (cannot disable driver cache on Windows) - `1` skipped: `heap_window_out_of_memory_falls_back_to_the_switch_form` (no heap windows) - **Paired 60 s RTX 4060 smoke capture (`scripts/smoke.ps1`):** Base (`origin/main` `b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7`): ``` xcl-smoke v1 commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7 gpu: NVIDIA GeForce RTX 4060 title: 29640639 seconds: 60 exit: 0x0 frames shown: 1433 (PresentX 1434) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 14015 MB ``` PR (`c970f2257e0935d8e1c17f14e62d9aade3838ee4`): ``` xcl-smoke v1 commit: c970f2257e0935d8e1c17f14e62d9aade3838ee4 gpu: NVIDIA GeForce RTX 4060 title: 29640639 seconds: 60 exit: 0x0 frames shown: 1316 (PresentX 1317) presents per 2 s (last 3): 6 36 60 device removals: 0 crashes: 0 peak commit: 13979 MB ``` **Not tested** - Live multi-hour retail audio streaming with sustained concurrent decode errors beyond the unit tests and 60 s smoke capture. - The `29` host-gated workspace tests skipped on this RTX 4060 machine (wave64 hardware, wave32 per-lane driver support, D3D12 SDK debug layer, driver cache disable, and heap windows). **AI use** Google Antigravity (Gemini 4 Neon) wrote the patch, unit tests, and PR description; all commands, test runs, micro-benchmarks, and paired 60 s GPU smoke captures were executed directly in this workspace.
Mirror patched vtable originals in a lock-free FastOriginals table so
original() avoids locking ORIGINALS on every XAudio2 call, guard XMA
lookups in submit_source_buffer and destroy_voice with an atomic
SILENT_LIVE_COUNT updated under the XMA lock, hand decoded Vec<i16>
PCM16 buffers directly to XAudio2 without allocating/copying a second
byte buffer (clamping to whole frames within XAUDIO2_MAX_BUFFER_BYTES and
falling back to shared silence on < 1 frame), and back decode-error
silence fallbacks with the shared read-only silence() mapping instead of
allocating up to 32 MiB on the heap.

Assisted-by: Google Antigravity (Gemini 4 Neon)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 06:15:28 +00:00
Author
Owner

@⁠luckyteagirl on GitHub · 2026-11-26 06:18 UTC · original · reviewed

At the new decoded-error path in submit_decoded_buffer, prepare_fallback_silence() now requires the process-wide 32 MiB silence() mapping. If that VirtualAlloc fails once, OnceLock<usize> permanently stores the null result, so every later decoded-error or short-frame fallback returns E_FAIL even if memory becomes available. Before this PR, the decoded path allocated only the selected buffer's sb.audio_bytes of silence (the PR's 480-stereo-frame case needs 1,920 bytes). Could the shared mapping stay the fast path while allocation failure falls back to a buffer-sized owned silence allocation or a retryable mapping? A test with an injectable failing mapping would cover the recovery case; the new test currently exercises only successful mapping.

This is an exact-head source review of c970f2257e0935d8e1c17f14e62d9aade3838ee4; I did not force an allocation failure or run a retail title. AI-assisted review with Codex.

**@⁠luckyteagirl** on GitHub · 2026-11-26 06:18 UTC · [original](https://github.com/xcl-dev/xcl/pull/2683#pullrequestreview-6069416135) · **reviewed** At the new decoded-error path in `submit_decoded_buffer`, `prepare_fallback_silence()` now requires the process-wide 32 MiB `silence()` mapping. If that `VirtualAlloc` fails once, `OnceLock<usize>` permanently stores the null result, so every later decoded-error or short-frame fallback returns `E_FAIL` even if memory becomes available. Before this PR, the decoded path allocated only the selected buffer's `sb.audio_bytes` of silence (the PR's 480-stereo-frame case needs 1,920 bytes). Could the shared mapping stay the fast path while allocation failure falls back to a buffer-sized owned silence allocation or a retryable mapping? A test with an injectable failing mapping would cover the recovery case; the new test currently exercises only successful mapping. This is an exact-head source review of `c970f2257e0935d8e1c17f14e62d9aade3838ee4`; I did not force an allocation failure or run a retail title. AI-assisted review with Codex.
Author
Owner

@⁠luckyteagirl on GitHub · 2026-11-26 06:18 UTC · original · reviewed

The new FAST_ORIG_CAP test fills a local FastOriginals to 32 entries and checks that an unknown key requests fallback. The later original() assertion uses a separate process-wide registry with just one patched entry, so the production lookup's overflow path (Err(()) to ORIGINALS) is never exercised. This test would still pass if original() accidentally returned None for every entry beyond the fast table. Could a fresh-process fixture register 33 distinct originals and assert that original() resolves both a mirrored key and the 33rd key (while an absent key stays absent), or could an injectable local fast/slow pair test the same path without polluting process-wide tables with short-lived stack vtables?

This is an exact-head source review of c970f2257e0935d8e1c17f14e62d9aade3838ee4; no runtime build was run. AI-assisted review with Codex.

**@⁠luckyteagirl** on GitHub · 2026-11-26 06:18 UTC · [original](https://github.com/xcl-dev/xcl/pull/2683#pullrequestreview-6069418870) · **reviewed** The new `FAST_ORIG_CAP` test fills a *local* `FastOriginals` to 32 entries and checks that an unknown key requests fallback. The later `original()` assertion uses a separate process-wide registry with just one patched entry, so the production lookup's overflow path (`Err(())` to `ORIGINALS`) is never exercised. This test would still pass if `original()` accidentally returned `None` for every entry beyond the fast table. Could a fresh-process fixture register 33 distinct originals and assert that `original()` resolves both a mirrored key and the 33rd key (while an absent key stays absent), or could an injectable local fast/slow pair test the same path without polluting process-wide tables with short-lived stack vtables? This is an exact-head source review of `c970f2257e0935d8e1c17f14e62d9aade3838ee4`; no runtime build was run. AI-assisted review with Codex.
Author
Owner

@⁠SlopTart on GitHub · 2026-11-26 06:50 UTC · original · edited 2026-11-26 07:02 UTC

Tested on the Linux/Wine lane, full standard env (AMD rig: Ryzen 9 9900X, 96 GB DDR5, RX 7900 XT 20 GB, Arch kernel 7.2.15, Mesa 26.2.5 RADV, wine-11.0 Proton, rustc 1.94.0; d3d12,d3d12core,dxgi,d3d11,d3d10core=n,b overrides, official DXC kit, VKD3D_CONFIG=ignore_shared_fence, threads=2), head c970f225, mergeable against main b49be183:
non-gpu suite (--skip gpu::): 600 passed, 2 failed, 4 ignored, 733 filtered.
The failure set is identical to bare main b49be183 measured on the same rig the same day (596 passed, 3 failed): gpu_promoted_uav_clear (our #2490), xma2_source_voice (#2481, vendored-FAudio gate). The third red, the sparse tile video-memory test, is a known batch flake (green solo; it did not reproduce in this run).
Zero delta from this PR; every test it adds passes inside the suite.
Not tested: gpu suite, Windows native.
Correction: an earlier version of this row reported three extra reds; those runs lacked the d3d12,d3d12core=n,b DLL overrides and hit stub-DLL NOTIMPL artifacts. Re-ran with the standard env, artifacts gone.
AI use: Hermes agent (local Qwen-class) ran the tests and drafted this; I checked it before posting.

**@⁠SlopTart** on GitHub · 2026-11-26 06:50 UTC · [original](https://github.com/xcl-dev/xcl/pull/2683#issuecomment-7184842203) · edited 2026-11-26 07:02 UTC **Tested** on the Linux/Wine lane, full standard env (AMD rig: Ryzen 9 9900X, 96 GB DDR5, RX 7900 XT 20 GB, Arch kernel 7.2.15, Mesa 26.2.5 RADV, wine-11.0 Proton, rustc 1.94.0; `d3d12,d3d12core,dxgi,d3d11,d3d10core=n,b` overrides, official DXC kit, `VKD3D_CONFIG=ignore_shared_fence`, threads=2), head `c970f225`, mergeable against main `b49be183`: non-gpu suite (`--skip gpu::`): **600 passed, 2 failed, 4 ignored, 733 filtered**. The failure set is identical to bare main `b49be183` measured on the same rig the same day (596 passed, 3 failed): gpu_promoted_uav_clear (our #2490), xma2_source_voice (#2481, vendored-FAudio gate). The third red, the sparse tile video-memory test, is a known batch flake (green solo; it did not reproduce in this run). Zero delta from this PR; every test it adds passes inside the suite. **Not tested**: gpu suite, Windows native. **Correction**: an earlier version of this row reported three extra reds; those runs lacked the `d3d12,d3d12core=n,b` DLL overrides and hit stub-DLL NOTIMPL artifacts. Re-ran with the standard env, artifacts gone. **AI use**: Hermes agent (local Qwen-class) ran the tests and drafted this; I checked it before posting.
Author
Owner

@⁠sage-sage on GitHub · 2026-11-26 07:05 UTC · original

Test report: passes on NVIDIA. Exact head c970f225 (its base is current main b49be18, so head = merged).

Tested

  • RTX 4080 SUPER (driver 621.40), Ryzen 5 7600X, Windows 11 26H2 build 26300.10075, rustc 1.100.0 MSVC, DXC 1.9.2602.17 (Windows SDK 10.0.26100), debug build
  • cargo test --workspace -- --test-threads=4: 1438 passed, 0 failed, 47 ignored; the 3 new tests pass
  • SKIPPED (29 lines, the same as on main on this machine): 21 wave64 tests (NVIDIA is wave32 only), 3 per-lane wave32 f16/f32 forms (refused), 3 D3D12 debug layer (d3d12SDKLayers.dll not installed), 1 no heap windows, 1 pso_measurement_compiles_an_exact_synthetic_record (Developer Mode off)

Not tested

  • No game, so no XAudio2 voices from a title.

Claude Code (Claude Opus 5.5) ran the tests and wrote this report.

**@⁠sage-sage** on GitHub · 2026-11-26 07:05 UTC · [original](https://github.com/xcl-dev/xcl/pull/2683#issuecomment-7185092609) **Test report: passes on NVIDIA.** Exact head `c970f225` (its base is current `main` `b49be18`, so head = merged). **Tested** - RTX 4080 SUPER (driver 621.40), Ryzen 5 7600X, Windows 11 26H2 build 26300.10075, rustc 1.100.0 MSVC, DXC 1.9.2602.17 (Windows SDK 10.0.26100), debug build - `cargo test --workspace -- --test-threads=4`: 1438 passed, 0 failed, 47 ignored; the 3 new tests pass - SKIPPED (29 lines, the same as on `main` on this machine): 21 wave64 tests (NVIDIA is wave32 only), 3 per-lane wave32 f16/f32 forms (refused), 3 D3D12 debug layer (`d3d12SDKLayers.dll` not installed), 1 `no heap windows`, 1 `pso_measurement_compiles_an_exact_synthetic_record` (Developer Mode off) **Not tested** - No game, so no XAudio2 voices from a title. Claude Code (Claude Opus 5.5) ran the tests and wrote this report.
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2683/head:github-bot/gh-2683'
git switch 'github-bot/gh-2683'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2683'
git switch 'github-bot/gh-2683'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2683'
git switch 'github-bot/gh-2683'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2683'
git switch 'main'
git merge --squash 'github-bot/gh-2683'
git switch 'main'
git merge --ff-only 'github-bot/gh-2683'
git switch 'main'
git merge 'github-bot/gh-2683'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.