formats: xma: decode Huffman codes with a 2-level O(1) lookup table #362

Manually merged
github merged 3 commits from github-bot/gh-362 into main 2026-12-05 17:31:18 +00:00 AGit
Owner

@⁠lucamzanon on GitHub · 2026-12-03 20:13 UTC · original
lucamzanon:xmem/2-xma-vlc → main · +1019 −8 · 1 files · 3 commits · merged 2026-12-05 17:27 UTC

Summary

Replaces the per-symbol partition_point binary search in Vlc::read (crates/victory-formats/src/xma.rs) with a compact 2-level O(1) lookup table and single-load peek32, keeping hot primary tables to 19 KB (63 KB total across all 7 XMA tables).

Design

  • Compact 4-byte Entry (u16 symbol/subtable offset, u8 length, u8 subtable bits).
  • Per-table optimal primary width chosen by min(total_entries + 2^bits):
    • scale: 9 bits (512 primary / 1,536 total)
    • scale_rl: 10 bits (1,024 / 3,264)
    • coef[0]: 10 bits (1,024 / 3,742)
    • coef[1]: 11 bits (2,048 / 6,520)
    • vec4: 7 bits (128 / 478), vec2: 7 bits (128 / 334), vec1: 6 bits (64 / 328)
    • Total: 4,928 primary entries (19 KB hot) / 16,202 total entries (63 KB).
  • Built directly using the reference partition_point logic so every entry is bit-exact by construction.
  • Also adds a synthetic valid-frame XMA generator + decode throughput benchmark (085263b).

Verification & Benchmarks (Ryzen 7 5700X / RX 9070 XT, Linux RADV)

  • Exhaustive bit-exactness: vlc_tables_match_the_binary_search_on_every_prefix checks all 2^maxlen prefixes (~8.9M lookups, up to 2^22 for coef1) against the old partition_point + byte-by-byte peek32; 8 end-to-end PCM checksums (mono/stereo × 4 sample rates) match bit-for-bit.
  • Tests / lints: cargo test -p victory-formats --lib xma 18/18 passed, Windows cross-compile x86_64-pc-windows-msvc + clippy --all-targets -D warnings + rustfmt --check clean.
  • Release micro-benchmark (Ryzen 7 5700X):
Workload Before After Speedup
VLC lookup (7 tables) 19.4–23.4 ns 3.8–4.3 ns 4.6×–5.9×
Mono XMA frame decode 8.5 µs 5.2 µs 1.63× (-39%)
Stereo XMA frame decode 17.6 µs 10.9 µs 1.61× (-38%)
  • In-game A/B/B/A sanity check (VICTORY_BENCH=rt, 4K FSR 4 Quality, scripted moving Prison 2m x 4, RX 9070 XT): 0 crashes, +2.38% 1% low (10.75 vs 10.50 fps; avg neutral at GPU-bound 4K RT).
**@⁠lucamzanon** on GitHub · 2026-12-03 20:13 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/362) `lucamzanon:xmem/2-xma-vlc` → `main` · +1019 −8 · 1 files · 3 commits · merged 2026-12-05 17:27 UTC ## Summary Replaces the per-symbol `partition_point` binary search in `Vlc::read` (`crates/victory-formats/src/xma.rs`) with a compact 2-level O(1) lookup table and single-load `peek32`, keeping hot primary tables to **19 KB** (63 KB total across all 7 XMA tables). ### Design - Compact 4-byte `Entry` (`u16` symbol/subtable offset, `u8` length, `u8` subtable bits). - Per-table optimal primary width chosen by `min(total_entries + 2^bits)`: - `scale`: 9 bits (512 primary / 1,536 total) - `scale_rl`: 10 bits (1,024 / 3,264) - `coef[0]`: 10 bits (1,024 / 3,742) - `coef[1]`: 11 bits (2,048 / 6,520) - `vec4`: 7 bits (128 / 478), `vec2`: 7 bits (128 / 334), `vec1`: 6 bits (64 / 328) - **Total: 4,928 primary entries (19 KB hot) / 16,202 total entries (63 KB)**. - Built directly using the reference `partition_point` logic so every entry is bit-exact by construction. - Also adds a synthetic valid-frame XMA generator + decode throughput benchmark (`085263b`). ## Verification & Benchmarks (Ryzen 7 5700X / RX 9070 XT, Linux RADV) - **Exhaustive bit-exactness:** `vlc_tables_match_the_binary_search_on_every_prefix` checks **all 2^maxlen prefixes (~8.9M lookups, up to 2^22 for `coef1`)** against the old `partition_point` + byte-by-byte `peek32`; 8 end-to-end PCM checksums (mono/stereo × 4 sample rates) match bit-for-bit. - **Tests / lints:** `cargo test -p victory-formats --lib xma` **18/18 passed**, Windows cross-compile `x86_64-pc-windows-msvc` + `clippy --all-targets -D warnings` + `rustfmt --check` clean. - **Release micro-benchmark (Ryzen 7 5700X):** | Workload | Before | After | Speedup | |---|---:|---:|---:| | VLC lookup (7 tables) | 19.4–23.4 ns | **3.8–4.3 ns** | **4.6×–5.9×** | | Mono XMA frame decode | 8.5 µs | **5.2 µs** | **1.63× (-39%)** | | Stereo XMA frame decode | 17.6 µs | **10.9 µs** | **1.61× (-38%)** | - **In-game A/B/B/A sanity check** (`VICTORY_BENCH=rt`, 4K FSR 4 Quality, scripted moving Prison `2m x 4`, RX 9070 XT): **0 crashes**, **+2.38% 1% low** (`10.75` vs `10.50 fps`; avg neutral at GPU-bound 4K RT).
The noise tests only reach the decoder's error paths. A generator now builds frames as the decoder reads them: tile header, subframe sizes, scale factors, quantisation steps, vector-coded and run-level coded coefficients, every choice random and every Huffman code drawn as a source the code fits would send. Every frame decodes. The test decodes such streams, mono and stereo at every sample rate, and prints the PCM checksums; decode_throughput is the release benchmark of a frame's decoding.
Vlc::read ran a binary search over the sorted codes for every symbol. Each Vlc now holds a two-level lookup table: the top bits of the stream index a primary table whose entry is the code, or the root of a sub-table that the next bits index for the longer codes. The primary width is the one leaving the fewest entries, the primary table counted twice as every symbol reads it: 64 to 2048 entries, 16 202 entries and 63 KB for the seven tables. Every entry holds what the binary search returned for the 32 bits ahead, which tests check on every prefix of every table and on noise; the synthetic streams give the same PCM. peek32 loads 8 bytes at once when it can, a byte at a time near the end of the data. A frame decodes 1.6 times faster (5.2 against 8.5 µs mono, 10.9 against 17.6 µs stereo, on synthetic streams); a code reads in 4 ns instead of 20.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-03 20:18:27 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-03 21:08 UTC · original

Tested d06d065 on Windows 11 with a native MSVC build, only -p victory-formats. Main hasn't touched this crate since the PR base, so I compared against current main.

For the differential check I copied main's Vlc::new, Vlc::read and the old 5-byte peek32 into a local test module (not committed) and ran them next to the new tables for all seven of them. Every code of every table at bit offsets 0 to 31, followed by 0, 1, 7 or 40 random bits, and the same buffers cut short at every byte so the code gets truncated. That's 910k reads with the same symbol and position, and the complete codes all give the expected symbol. Then every prefix up to each table's longest code length, with zero, one or random low bits at a random offset in the byte, 8.9M reads, all identical. Then random bitstreams of 0 to 200 bytes, some uniform and some mostly zeros or mostly ones, from a random start bit, picking tables at random and mixing in plain read(n) calls, and reading on until 40 bits past the end of the data. 60M reads in release and 6M in debug gave the same symbol, position and peek32 every time, and about 24M of those started within 32 bits of the end or beyond it.

For whole frames I took frames from your synthetic Stream and left some as they were, truncated some by bits or bytes, flipped a bit in some and replaced some with random bytes. I dumped them with the PR build and decoded the same input on main. In release that was 30720 frames, 16703 of them returning an error, and in debug 12288 frames with 6764 errors. Every frame gave the same result and the same PCM on both sides, flush output included.

All seven tables are complete and stored sorted, so any 32 bits decode to some symbol, same as before. I also fed random code sets to both builders. Well-formed ones (about 22k) matched every time. Sets whose lengths are not prefix-free trip a debug_assert in debug and decode differently from the old search in release, but the constant XMA tables can never be like that, so this only matters if Vlc::new is ever reused for other tables. The biggest table has 6520 entries, so u16 offsets are nowhere near the limit, and all symbols fit in i16.

cargo test -p victory-formats passes in debug and release, 57 passed and 9 ignored here against 52 and 7 on main. The new tests passed 20 runs out of 20. clippy with --all-targets has no warnings on either side and fmt is clean.

Your vlc_throughput in release puts the table at roughly 5.2x to 6.7x faster per code than the binary search, depending on the table. I only timed read by itself, not a full decode.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-03 21:08 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/362#issuecomment-7392348675) Tested d06d065 on Windows 11 with a native MSVC build, only `-p victory-formats`. Main hasn't touched this crate since the PR base, so I compared against current main. For the differential check I copied main's `Vlc::new`, `Vlc::read` and the old 5-byte `peek32` into a local test module (not committed) and ran them next to the new tables for all seven of them. Every code of every table at bit offsets 0 to 31, followed by 0, 1, 7 or 40 random bits, and the same buffers cut short at every byte so the code gets truncated. That's 910k reads with the same symbol and position, and the complete codes all give the expected symbol. Then every prefix up to each table's longest code length, with zero, one or random low bits at a random offset in the byte, 8.9M reads, all identical. Then random bitstreams of 0 to 200 bytes, some uniform and some mostly zeros or mostly ones, from a random start bit, picking tables at random and mixing in plain `read(n)` calls, and reading on until 40 bits past the end of the data. 60M reads in release and 6M in debug gave the same symbol, position and `peek32` every time, and about 24M of those started within 32 bits of the end or beyond it. For whole frames I took frames from your synthetic `Stream` and left some as they were, truncated some by bits or bytes, flipped a bit in some and replaced some with random bytes. I dumped them with the PR build and decoded the same input on main. In release that was 30720 frames, 16703 of them returning an error, and in debug 12288 frames with 6764 errors. Every frame gave the same result and the same PCM on both sides, flush output included. All seven tables are complete and stored sorted, so any 32 bits decode to some symbol, same as before. I also fed random code sets to both builders. Well-formed ones (about 22k) matched every time. Sets whose lengths are not prefix-free trip a debug_assert in debug and decode differently from the old search in release, but the constant XMA tables can never be like that, so this only matters if `Vlc::new` is ever reused for other tables. The biggest table has 6520 entries, so u16 offsets are nowhere near the limit, and all symbols fit in i16. `cargo test -p victory-formats` passes in debug and release, 57 passed and 9 ignored here against 52 and 7 on main. The new tests passed 20 runs out of 20. clippy with `--all-targets` has no warnings on either side and fmt is clean. Your `vlc_throughput` in release puts the table at roughly 5.2x to 6.7x faster per code than the binary search, depending on the table. I only timed `read` by itself, not a full decode. AI-assisted: yes
Author
Owner

@⁠Luxuride on GitHub · 2026-12-04 12:10 UTC · original

Most complete PR in this batch, and the only one that holds up against today's main after 173 commits: crates/victory-formats/src/xma.rs is untouched on main since your base, so the diff still applies to the real file, and I ran cargo test -p victory-formats --lib xma twice on Linux — 18 passed, 5 ignored — once on your head, once with only this file swapped into current main.

Two hardening lines, then it is a yes.

  1. A missing code decodes as garbage instead of failing. lookup_table only fills codes present in the frame's length table, so for an incomplete (corrupt) set a primary entry can stay Entry::EMPTY, or a sub-table entry can be EMPTY, and Vlc::read (crates/victory-formats/src/xma.rs:310) does bits.pos += 0 and returns i32::from(0 as i16). The frame loop (xma.rs:853) gets no progress from that and overread() is only tested at the end of the frame, so a crafted or garbage packet can spin instead of returning Err. One if e.len == 0 { return Err(..) } (or advancing bits.pos) closes it. It is reachable only from bad input, but "only from bad input" is where a decoder spends its adversarial budget.
  2. Entry.value is u16 (xma.rs:261) and the sub-table base is stored in it with a debug-only debug_assert! (xma.rs:384). In release, an unusually wide table truncates the base and decodes to the wrong entries silently. Theoretical with the 64–2048-entry tables you measured, but a u32 field costs nothing.

Behaviour is otherwise preserved exactly, which is the part I checked hardest: answer = partition_point(c.0 <= v) - 1 (xma.rs:358) is the same expression the old binary search used, so unreachable prefixes map to the same longer code as before — including the over-advance, which is therefore not a regression. peek32's (u64::from_be_bytes(*b) << shift >> 32) is the same 32 bits as the old five-byte loop, and peek32_loads_eight_bytes_like_five covers it.

One honest note on evidence: the bit-exact PCM parity test against a reference decoder is ignored (it needs outside files), so the parity you have actually demonstrated is the synthetic generator and the noise case, not a real soundtrack. A stale branch this clean should not still be in the pile.

**@⁠Luxuride** on GitHub · 2026-12-04 12:10 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/362#issuecomment-7411075614) Most complete PR in this batch, and the only one that holds up against today's `main` after 173 commits: `crates/victory-formats/src/xma.rs` is untouched on `main` since your base, so the diff still applies to the real file, and I ran `cargo test -p victory-formats --lib xma` twice on Linux — 18 passed, 5 ignored — once on your head, once with only this file swapped into current `main`. Two hardening lines, then it is a yes. 1. **A missing code decodes as garbage instead of failing.** `lookup_table` only fills codes present in the frame's length table, so for an incomplete (corrupt) set a primary entry can stay `Entry::EMPTY`, or a sub-table entry can be `EMPTY`, and `Vlc::read` (`crates/victory-formats/src/xma.rs:310`) does `bits.pos += 0` and returns `i32::from(0 as i16)`. The frame loop (`xma.rs:853`) gets no progress from that and `overread()` is only tested at the end of the frame, so a crafted or garbage packet can spin instead of returning `Err`. One `if e.len == 0 { return Err(..) }` (or advancing `bits.pos`) closes it. It is reachable only from bad input, but "only from bad input" is where a decoder spends its adversarial budget. 2. **`Entry.value` is `u16`** (`xma.rs:261`) and the sub-table base is stored in it with a debug-only `debug_assert!` (`xma.rs:384`). In release, an unusually wide table truncates the base and decodes to the wrong entries silently. Theoretical with the 64–2048-entry tables you measured, but a `u32` field costs nothing. Behaviour is otherwise preserved exactly, which is the part I checked hardest: `answer = partition_point(c.0 <= v) - 1` (`xma.rs:358`) is the same expression the old binary search used, so unreachable prefixes map to the same longer code as before — including the over-advance, which is therefore not a regression. `peek32`'s `(u64::from_be_bytes(*b) << shift >> 32)` is the same 32 bits as the old five-byte loop, and `peek32_loads_eight_bytes_like_five` covers it. One honest note on evidence: the bit-exact PCM parity test against a reference decoder is `ignored` (it needs outside files), so the parity you have actually demonstrated is the synthetic generator and the noise case, not a real soundtrack. A stale branch this clean should not still be in the pile.
github-bot force-pushed github-bot/gh-362 from d06d0652c9 to c71a806ae9 2026-12-04 13:02:52 +00:00 Compare
Author
Owner

@⁠lucamzanon on GitHub · 2026-12-04 12:57 UTC · original

Thanks @⁠Luxuride and @⁠Kal0s-design for the thorough reviews!

Rebased cleanly onto main (0fd7614) and applied both hardening items in c71a806:

  1. Guarded empty/unpopulated entries (e.len == 0) in Vlc::read: sub-table lookup only runs when e.bits > 0, and any remaining e.len == 0 forces bits.pos = bits.end.saturating_add(1) so overread() trips immediately instead of spinning with zero progress. Added empty_entry_marks_overread_instead_of_spinning covering both primary and sub-table Entry::EMPTY.
  2. Widened Entry.value from u16 to u32 (with u32::try_from(at) instead of a debug-only u16 assert).

Re-verified cargo test --locked --lib -p victory-formats xma in debug & release (19/19 pass), cargo clippy --no-deps --all-targets -p victory-formats -- -D warnings, and rustfmt --edition 2024 --check.

**@⁠lucamzanon** on GitHub · 2026-12-04 12:57 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/362#issuecomment-7412151857) Thanks @⁠Luxuride and @⁠Kal0s-design for the thorough reviews! Rebased cleanly onto `main` (`0fd7614`) and applied both hardening items in `c71a806`: 1. Guarded empty/unpopulated entries (`e.len == 0`) in `Vlc::read`: sub-table lookup only runs when `e.bits > 0`, and any remaining `e.len == 0` forces `bits.pos = bits.end.saturating_add(1)` so `overread()` trips immediately instead of spinning with zero progress. Added `empty_entry_marks_overread_instead_of_spinning` covering both primary and sub-table `Entry::EMPTY`. 2. Widened `Entry.value` from `u16` to `u32` (with `u32::try_from(at)` instead of a debug-only `u16` assert). Re-verified `cargo test --locked --lib -p victory-formats xma` in debug & release (19/19 pass), `cargo clippy --no-deps --all-targets -p victory-formats -- -D warnings`, and `rustfmt --edition 2024 --check`.
github manually merged commit b106423450 into main 2026-12-05 17:31:17 +00:00
This discussion has been locked. Commenting is limited to contributors.
No description provided.