Opus: reuse multistream scratch buffers, validate sub-packets atomically, and bulk-append PCM16 #2696

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

@⁠Decodere on GitHub · 2026-11-26 06:46 UTC · original
Decodere:fix-opus-multistream-scratch-and-bulk-pcm → main · +421 −57 · 1 files · 1 commits · open

What is in it

Removes per-packet heap churn on multistream Opus decoding, bulk-copies decoded little-endian PCM16 samples, guards multistream interleaving against short or mismatched stream buffers, and preallocates decode_buffer output in crates/xcl/src/hle/opus.rs:

  • Reusable self-delimited splitting & atomic multistream validation: Refactored split_self_delimited into split_self_delimited_into(data, pos, out) (keeping split_self_delimited as a thin wrapper so split_multistream_packet stays untouched) and added split_multistream_into which enforces the minimum 2 * stream_count - 1 byte length and parses/validates all stream_count sub-packets via parse_packet(..., false) before returning Some(last) so malformed multistream packets never partially advance any SingleStreamDecoder.
  • Bulk little-endian PCM16 append: Added compile-time little-endian assertion (const _: () = assert!(cfg!(target_endian = "little"))) and extracted append_pcm16_le (guarding n == 0, reserving n, and copying n * 2 bytes via byte-aligned std::ptr::copy_nonoverlapping + set_len) and append_f32_le (via bytes.as_chunks::<4>().0), called from MftDecoder::append_sample_pcm16.
  • Persistent multistream scratch buffers, precomputed ChannelSrc, and OOB-safe interleaving: Added ChannelSrc (Silence, Mono, Coupled), defensive build_channel_map (mapping 255 and any out-of-range entries to ChannelSrc::Silence), and interleave_streams (clamping frames against every referenced stream buffer length). Appended channel_map, sub_pkts, and sub_pcm to Decoder (empty for mono/stereo; reused in place in Decoder::decode_packet_pcm with per-stream clamping frames = frames.min(n).min(pcm.len() / expected_ch)).
  • Preallocated decode_buffer output: Added expected_buffer_samples (using timing.decoded_48k when Ogg timing applies or summing parse_packet(p, multistream) otherwise, capped at MAX_PREALLOC_SAMPLES = 16 << 20) and initialized decode_buffer's out via Vec::with_capacity(...).
  • Unit tests: Added 5 tests covering aligned/unaligned/odd append_pcm16_le & append_f32_le, split_self_delimited_into / split_multistream_into parity and zero-reallocation reuse across codes 0–3 and 5.1 packets, build_channel_map & interleave_streams short-stream / OOB clamping, expected_buffer_samples sizing & cap safety (including multistream self-delimited code-1 packets), and live Decoder atomic validation, zero-reallocation scratch reuse, short-coupled-stream OOB clamping, and exact decode_buffer preallocation.

Tested

  • Failing-first baseline on unmodified origin/main (b49be183): Reproduced both issues before applying the fix under XCL_ADAPTER=warp XCL_WARP=1:
    • Feeding a 5.1 Decoder whose coupled stream 0 returned mono (960 samples instead of 1920) panicked inside Decoder::decode_packet_pcm at crates/xcl/src/hle/opus.rs:1438 (index out of bounds: the len is 960 but the index is 960).
    • Decoder::decode_buffer on a 5-packet 20 ms AWC block (4800 samples, pre_skip = 0) grew from capacity 0 to capacity() == 7680 instead of a single exact 4800-sample allocation.
  • Targeted unit & Windows MSOpusDecoder tests (hle::opus::tests::):
    • Debug WARP (XCL_ADAPTER=warp XCL_WARP=1 cargo test --lib hle::opus::tests:: -- --nocapture): 18 passed, 0 failed, 0 ignored (0.00s; decodes_a_game_sound skips cleanly when XCL_SAMPLE_AWC is unset).
    • Release WARP (XCL_ADAPTER=warp XCL_WARP=1 cargo test --release --lib hle::opus::tests:: -- --nocapture): 18 passed, 0 failed, 0 ignored (0.00s).
    • Release RTX 4060 (cargo test --release --lib hle::opus::tests:: -- --nocapture): 18 passed, 0 failed, 0 ignored (0.01s).
  • Clippy (cargo clippy --all-targets): 0 new warnings in crates/xcl/src/hle/opus.rs (only the 9 pre-existing warnings on untouched lines 176, 241, 528, 582, 742, 1870, 2112, 2113, 2124).
  • Standalone release micro-benchmark (rustc -O, before vs after on identical inputs):
    • pcm16_append_3840B (960 stereo frames, 200k iters): 1024.4 ns -> 31.5 ns (32.47x)
    • split_5_1_packet (SURROUND51_20MS[0], 4 streams, 200k iters): 148.7 ns -> 13.1 ns (11.38x, 0 steady-state allocs)
    • multistream_5_1_pcm_interleave (960 frames × 6 ch, 50k iters): 11798.8 ns -> 7073.5 ns (1.67x, 0 steady-state allocs)
    • decode_buffer_5pkt_stereo_alloc (5 × 960 stereo frames, 50k iters): 6885.0 ns -> 380.4 ns (18.10x, 1 allocation vs repeated doubling)

Regression run

  • Full release workspace on RTX 4060 (cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture): 37 test binaries, 1440 passed, 0 failed, 47 ignored, with 29 pre-existing host-gated SKIPPED lines (21 no wave64, 3 wave32 per-lane form: refused, 3 no D3D12 debug layer / d3d12SDKLayers.dll, 1 pso_measurement_compiles_an_exact_synthetic_record driver cache, 1 heap_window_out_of_memory_falls_back_to_the_switch_form no heap windows).
  • Paired 60 s RTX 4060 smoke (scripts/smoke.ps1, origin/main b49be183 vs PR HEAD 70ce54a4):

Baseline (origin/main):

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

PR HEAD (70ce54a4):

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

Not tested

  • decodes_a_game_sound (XCL_SAMPLE_AWC was unset).
  • The libopus (opus.dll) fallback backend (Windows MSOpusDecoder.dll is present and selected on this host).
  • Big-endian targets (append_pcm16_le is compile-time guarded with assert!(cfg!(target_endian = "little"))).
  • The 29 pre-existing host-gated workspace skips listed above (wave64, wave32 per-lane refused, D3D12 debug layer, driver cache disable, heap windows).

AI use

Written and verified with assistance from Google Antigravity (Gemini 4 Neon). All changes, unit tests, micro-benchmarks, workspace tests, and paired RTX 4060 smoke runs were executed and reviewed directly against the repository.

**@⁠Decodere** on GitHub · 2026-11-26 06:46 UTC · [original](https://github.com/xcl-dev/xcl/pull/2696) `Decodere:fix-opus-multistream-scratch-and-bulk-pcm` → `main` · +421 −57 · 1 files · 1 commits · open **What is in it** Removes per-packet heap churn on multistream Opus decoding, bulk-copies decoded little-endian PCM16 samples, guards multistream interleaving against short or mismatched stream buffers, and preallocates `decode_buffer` output in `crates/xcl/src/hle/opus.rs`: - **Reusable self-delimited splitting & atomic multistream validation:** Refactored `split_self_delimited` into `split_self_delimited_into(data, pos, out)` (keeping `split_self_delimited` as a thin wrapper so `split_multistream_packet` stays untouched) and added `split_multistream_into` which enforces the minimum `2 * stream_count - 1` byte length and parses/validates all `stream_count` sub-packets via `parse_packet(..., false)` before returning `Some(last)` so malformed multistream packets never partially advance any `SingleStreamDecoder`. - **Bulk little-endian PCM16 append:** Added compile-time little-endian assertion (`const _: () = assert!(cfg!(target_endian = "little"))`) and extracted `append_pcm16_le` (guarding `n == 0`, reserving `n`, and copying `n * 2` bytes via byte-aligned `std::ptr::copy_nonoverlapping` + `set_len`) and `append_f32_le` (via `bytes.as_chunks::<4>().0`), called from `MftDecoder::append_sample_pcm16`. - **Persistent multistream scratch buffers, precomputed `ChannelSrc`, and OOB-safe interleaving:** Added `ChannelSrc` (`Silence`, `Mono`, `Coupled`), defensive `build_channel_map` (mapping `255` and any out-of-range entries to `ChannelSrc::Silence`), and `interleave_streams` (clamping `frames` against every referenced stream buffer length). Appended `channel_map`, `sub_pkts`, and `sub_pcm` to `Decoder` (empty for mono/stereo; reused in place in `Decoder::decode_packet_pcm` with per-stream clamping `frames = frames.min(n).min(pcm.len() / expected_ch)`). - **Preallocated `decode_buffer` output:** Added `expected_buffer_samples` (using `timing.decoded_48k` when Ogg timing applies or summing `parse_packet(p, multistream)` otherwise, capped at `MAX_PREALLOC_SAMPLES = 16 << 20`) and initialized `decode_buffer`'s `out` via `Vec::with_capacity(...)`. - **Unit tests:** Added 5 tests covering aligned/unaligned/odd `append_pcm16_le` & `append_f32_le`, `split_self_delimited_into` / `split_multistream_into` parity and zero-reallocation reuse across codes 0–3 and 5.1 packets, `build_channel_map` & `interleave_streams` short-stream / OOB clamping, `expected_buffer_samples` sizing & cap safety (including multistream self-delimited code-1 packets), and live `Decoder` atomic validation, zero-reallocation scratch reuse, short-coupled-stream OOB clamping, and exact `decode_buffer` preallocation. **Tested** - **Failing-first baseline on unmodified `origin/main` (`b49be183`):** Reproduced both issues before applying the fix under `XCL_ADAPTER=warp XCL_WARP=1`: - Feeding a 5.1 `Decoder` whose coupled stream 0 returned mono (960 samples instead of 1920) panicked inside `Decoder::decode_packet_pcm` at `crates/xcl/src/hle/opus.rs:1438` (`index out of bounds: the len is 960 but the index is 960`). - `Decoder::decode_buffer` on a 5-packet 20 ms AWC block (`4800` samples, `pre_skip = 0`) grew from capacity `0` to `capacity() == 7680` instead of a single exact `4800`-sample allocation. - **Targeted unit & Windows `MSOpusDecoder` tests (`hle::opus::tests::`):** - Debug WARP (`XCL_ADAPTER=warp XCL_WARP=1 cargo test --lib hle::opus::tests:: -- --nocapture`): `18` passed, `0` failed, `0` ignored (`0.00s`; `decodes_a_game_sound` skips cleanly when `XCL_SAMPLE_AWC` is unset). - Release WARP (`XCL_ADAPTER=warp XCL_WARP=1 cargo test --release --lib hle::opus::tests:: -- --nocapture`): `18` passed, `0` failed, `0` ignored (`0.00s`). - Release RTX 4060 (`cargo test --release --lib hle::opus::tests:: -- --nocapture`): `18` passed, `0` failed, `0` ignored (`0.01s`). - **Clippy (`cargo clippy --all-targets`):** `0` new warnings in `crates/xcl/src/hle/opus.rs` (only the 9 pre-existing warnings on untouched lines `176, 241, 528, 582, 742, 1870, 2112, 2113, 2124`). - **Standalone release micro-benchmark (`rustc -O`, before vs after on identical inputs):** - `pcm16_append_3840B` (960 stereo frames, 200k iters): `1024.4 ns` -> `31.5 ns` (`32.47x`) - `split_5_1_packet` (`SURROUND51_20MS[0]`, 4 streams, 200k iters): `148.7 ns` -> `13.1 ns` (`11.38x`, `0` steady-state allocs) - `multistream_5_1_pcm_interleave` (960 frames × 6 ch, 50k iters): `11798.8 ns` -> `7073.5 ns` (`1.67x`, `0` steady-state allocs) - `decode_buffer_5pkt_stereo_alloc` (5 × 960 stereo frames, 50k iters): `6885.0 ns` -> `380.4 ns` (`18.10x`, `1` allocation vs repeated doubling) **Regression run** - **Full release workspace on RTX 4060** (`cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture`): `37` test binaries, `1440` passed, `0` failed, `47` ignored, with `29` pre-existing host-gated `SKIPPED` lines (`21` `no wave64`, `3` wave32 `per-lane form: refused`, `3` no D3D12 debug layer / `d3d12SDKLayers.dll`, `1` `pso_measurement_compiles_an_exact_synthetic_record` driver cache, `1` `heap_window_out_of_memory_falls_back_to_the_switch_form` no heap windows). - **Paired 60 s RTX 4060 smoke (`scripts/smoke.ps1`, `origin/main` `b49be183` vs PR HEAD `70ce54a4`):** Baseline (`origin/main`): ``` xcl-smoke v1 commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7 gpu: NVIDIA GeForce RTX 4060 title: 29640639 seconds: 60 exit: 0x0 frames shown: 1506 (PresentX 1506) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 14011 MB ``` PR HEAD (`70ce54a4`): ``` xcl-smoke v1 commit: 70ce54a41198899bfebc9feda607ad6e6a1fc346 gpu: NVIDIA GeForce RTX 4060 title: 29640639 seconds: 60 exit: 0x0 frames shown: 1572 (PresentX 1572) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 13967 MB ``` **Not tested** - `decodes_a_game_sound` (`XCL_SAMPLE_AWC` was unset). - The `libopus` (`opus.dll`) fallback backend (Windows `MSOpusDecoder.dll` is present and selected on this host). - Big-endian targets (`append_pcm16_le` is compile-time guarded with `assert!(cfg!(target_endian = "little"))`). - The `29` pre-existing host-gated workspace skips listed above (wave64, wave32 per-lane refused, D3D12 debug layer, driver cache disable, heap windows). **AI use** Written and verified with assistance from Google Antigravity (Gemini 4 Neon). All changes, unit tests, micro-benchmarks, workspace tests, and paired RTX 4060 smoke runs were executed and reviewed directly against the repository.
Reuse per-decoder multistream sub-packet and PCM scratch buffers on
`opus::Decoder`, validate all `stream_count` sub-packets before invoking
any sub-stream decoder, precompute defensive `ChannelSrc` mappings with
OOB-safe stream clamping in `interleave_streams`, bulk-copy little-endian
PCM16 output in `append_pcm16_le`, and preallocate `decode_buffer` output
capacity via `expected_buffer_samples`.

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

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

The new atomic split validates each sub-packet's framing but discards parse_packet(...).total_samples_48k, so it still accepts streams with different packet durations. The added six-stream positive fixture includes a 20 ms code-0 sub-packet (0xFC) and a 40 ms code-1 sub-packet (0xFD), and expects the split to succeed. RFC 7845 §3 requires all sub-packets in one multistream packet to have the same duration and recommends treating a mismatch as malformed. In Decoder::decode_packet, all backends are then advanced before the output is clamped to the shortest stream, leaving their timelines out of step. Could the prevalidation compare total_samples_48k across every sub-packet, including the tail, before decoding any stream? The positive fixture could use equal durations, with a mismatched-tail negative fixture asserting no decoder timestamp advances.

The malformed-packet acceptance predates this PR, but its new atomic validation and fixture are a natural place to close it. Exact-head source review of 70ce54a41198899bfebc9feda607ad6e6a1fc346; no audio decode was run. AI-assisted review with Codex.

**@⁠luckyteagirl** on GitHub · 2026-11-26 06:50 UTC · [original](https://github.com/xcl-dev/xcl/pull/2696#pullrequestreview-6069695231) · **reviewed** The new atomic split validates each sub-packet's framing but discards `parse_packet(...).total_samples_48k`, so it still accepts streams with different packet durations. The added six-stream positive fixture includes a 20 ms code-0 sub-packet (`0xFC`) and a 40 ms code-1 sub-packet (`0xFD`), and expects the split to succeed. [RFC 7845 §3](https://www.rfc-editor.org/rfc/rfc7845#section-3) requires all sub-packets in one multistream packet to have the same duration and recommends treating a mismatch as malformed. In `Decoder::decode_packet`, all backends are then advanced before the output is clamped to the shortest stream, leaving their timelines out of step. Could the prevalidation compare `total_samples_48k` across every sub-packet, including the tail, before decoding any stream? The positive fixture could use equal durations, with a mismatched-tail negative fixture asserting no decoder timestamp advances. The malformed-packet acceptance predates this PR, but its new atomic validation and fixture are a natural place to close it. Exact-head source review of `70ce54a41198899bfebc9feda607ad6e6a1fc346`; no audio decode was run. AI-assisted review with Codex.
Author
Owner

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

Test report: passes on NVIDIA. Exact head 70ce54a4 (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: 1440 passed, 0 failed, 47 ignored; the 5 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 real Opus / AWC streams.

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/2696#issuecomment-7185091263) **Test report: passes on NVIDIA.** Exact head `70ce54a4` (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`: 1440 passed, 0 failed, 47 ignored; the 5 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 real Opus / AWC streams. 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/2696/head:github-bot/gh-2696'
git switch 'github-bot/gh-2696'

Merge

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