Audio/XMA: box voices, skip inactive slots in pump, and reuse per-frame scratch #3383
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3383"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from Marvisak/VIctory. Originally posted by Desamodeth on 2026-11-26T21:12:51Z.
Claimed in #1633: https://github.com/Marvisak/VIctory/issues/1633#issuecomment-7203278391
Problem
On
main(63bcca43c6a00a758510398fa43096ce7e4f7df0):VoiceembedsOption<xma::Decoder>(14,304 B) inline (size_of::<Voice>() = 14,448 B), andXma::voicesstoresVec<Mutex<Option<Voice>>>contiguously. Allocating 512 XMA contexts (as instartup_as_fmod_does_it) immediately allocates and permanently retains 7,405,568 B (~7.06 MiB) even when idle or after a burst of voices is disabled.Xma::pump()scans all 512 voice slots on every wakeup and every 2 ms idle poll, locking/unlocking 512 mutexes spaced ~14.5 KiB apart across 7.06 MiB even when 0 or 16 voices are active.xma::read_frameallocates a freshVec<u8>andaudio::decodeallocates a freshVec<i16>(plus a thirdVec<i16>onflush).xma::Decoder::newrecomputes and stores 2,832 B of constant scale-factor band tables (num_sfb,sfb_offsets,sf_offsets) inline per voice.Changes
crates/victory-formats/src/xma.rs:FrameMetaandread_frame_into(data, start, out)so callers can reuse encoded-frame byte capacity across frames; implement existingread_frameon top of it (next_frameuntouched).BandTablesacross the four clamped sample-rate buckets (24 / 32 / 44.1 / 48 kHz) viaOnceLock, shrinkingDecoderfrom 14,304 B to 11,480 B and avoiding per-voice table construction.Decoder::decodeandDecoder::flushso fresh scratchVec<i16>buffers grow in one allocation instead of geometric reallocations.crates/victory-hle/src/modules/audio.rs:Voiceandxma::Decoder(Vec<Mutex<Option<Box<Voice>>>>;size_of::<Voice>() = 208 B), freeing decoder and scratch memory when a voice is disabled.Xma::active: Vec<AtomicU64>(updated under the matching voice mutex withReleaseordering, read withAcquireinXma::pump) sopumponly locks active slots.frame: Vec<u8>andscratch: Vec<i16>acrossdecodeandflush.Separate from #2788 (lock split / MMCSS), #1880 (reserve refill), #2663 (VLC / quant LUT), #2795 (IMDCT), and #2423 (Opus APU).
Measurements (Windows 11 Pro 10.0.26300, Ryzen 7 9800X3D, rustc 1.98.1,
--release, CPU-only, synthetic streams)Compared standalone
--releasebinaries ofmain(63bcca43) vs this branch (23e62b7c) using identical synthetic 48 kHz non-silent XMA2 streams (512 allocated contexts, 4-block rings) and a countingGlobalAllocwrapper, run interleaved in 6x A/B forward + 6x B/A reverse (12 runs each).Memory & allocations
main(63bcca43)23e62b7c)enable+disablechurn (32,000 pairs)Box<Voice>/ pair)CPU timings (median [min..max] over 12 runs; forward A/B vs reverse B/A medians)
mainXma::pump()(0/512 active)Xma::pump()(16/512 active, rings full)Xma::pump()(512/512 active, rings full)enable+disablechurn (ns / pair)enable+decode+disable(us / voice)Trade-off
Boxing
VoiceandDecodertrades 0-frame/1-frame voice churn allocator traffic (+1Box<Voice>onenable, +1Box<Decoder>on first frame) for ~7.05 MiB lower idle/post-burst heap retention, 0 steady-state per-frame allocations, and skipping inactive slots inXma::pump(). Even in the 0-frame and 1-ring churn tests, wall time stayed faster on this host becauseenableno longer initializes a 14.4 KiB inline struct andDecoder::newno longer rebuilds band tables, though heavy multi-threaded allocator contention on very short-lived voices is the main potential regression case.Correctness & Checks (CPU-only, no GPU/WARP, no game files)
66,048samples, FNV-1a0x29b87c8ab9c1311d, peak2384, 0 bad frames (identical).loops=2,start_skip=1,loop_skip=2) + flush:19,584samples, FNV-1a0x6deafbf1c8a3834d, peak1302, 0 bad frames (identical).cargo test --locked -p victory-formats --lib: 48 passed, 0 failed, 5 ignored (incl.read_frame_into_matches_read_frame_and_reuses_capacityandshared_band_tables_cover_all_sample_rate_buckets).cargo test --release --locked -p victory-formats --lib xma::: 22 passed, 0 failed, 3 ignored.cargo test --locked -p victory-hle --lib modules::audio:: -- --test-threads=1(debug & release): 9 passed, 0 failed (incl.xma_active_bitset_tracks_words_and_reuses_voice_scratch).cargo test --locked -p victory-hle --lib modules::apu::(2 passed) andmodules::dsp::(1 passed).cargo clippy --locked -p victory-formats -p victory-hle --all-targets -- -D warnings: clean.cargo check --workspace --all-targets --locked: clean.cargo xtask policy: 191 files ok.AI-assisted with Gemini 4 Neon.
Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T21:29:55Z.
Review: APPROVED
LGTM — verified on Windows against
origin/main(63bcca4).pump, sharing band tables by sample-rate bucket, and reusing per-frame scratch buffers cleanly reduce memory footprint and per-frame allocations.cargo test -p victory-formats --lib xma:: -- --test-threads=1: 22 passed, 0 failed (3 ignored; includingread_frame_into_matches_read_frame_and_reuses_capacityandshared_band_tables_cover_all_sample_rate_buckets).cargo test -p victory-hle --lib modules::audio:: -- --test-threads=1: 9 passed, 0 failed (includingxma_active_bitset_tracks_words_and_reuses_voice_scratch).cargo clippy -p victory-formats -p victory-hle --all-targets -- -D warnings: clean.cargo xtask policy: 191 files ok.Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Imported from Marvisak/VIctory. Originally posted by passerbyyhx on 2026-11-26T21:35:50Z.
I measured the short-lived-voice case at
23e62b7cagainst63bcca43on Windows x64 (Core i9-14900HX, Rust 1.98.1 release). There were 1, 2 or 4 concurrent command workers sharing the XMA instance and a single pump thread. Each worker owned one voice. Each configuration used 12 adjacent base/head pairs, six in each order, with 1,024 waves per process. Timing binaries had no allocator instrumentation.These are production full-pump results. The selected-slot control, which bypassed the inactive-slot scan while retaining the codec and shared XMA path, gave ratios of 1.051×, 0.973× and 1.016×. The one-worker median favors the change with wide dispersion. This workload did not establish a throughput change at two or four workers.
Separate warmed binaries counted Rust global allocation/reallocation calls in the command and pump spans. The command span went from 0 to 1 per voice; the pump went from 13 to 4 (4.25 at four workers). Total calls were 13 → 5–5.25. Four-worker PCM and voice/channel ownership matched byte-for-byte across both revisions and both pump modes: 20,480 PCM bytes plus 40 metadata bytes, SHA-256
b538f6b1f8f5b90a4b06af4b216fc85e0e76a0d387359d092b214d394025561d. The one- and two-worker files matched as well. The counter measures allocation traffic; mutex wait time, allocator wait time, and asynchronous real-time playback were not measured.Base benchmark fixture · PR benchmark fixture.
AI-assisted with Codex.
Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T21:41:02Z.
Review: APPROVED
Clean, focused optimization with solid test coverage across both
victory-formatsandvictory-hle.Checked the key invariants:
xma::read_frame_into(crates/victory-formats/src/xma.rs:139) clearsouton entry and on every earlyNonepath while preserving its allocation, andband_tables(xma.rs:630) matches the exact four sample-rate buckets in a sharedOnceLock.Xma::active(crates/victory-hle/src/modules/audio.rs:408) is allocated alongsidevoicesinAcpHalAllocateShapeContexts(audio.rs:317) and cleared atomically viaXma::EMPTYunder theXMAwrite lock inAcpHalReleaseShapeContexts(audio.rs:321), sopump(audio.rs:554) can never observe a stale set bit pastvoices.len().enable(audio.rs:462) anddisable(audio.rs:500) updateactivewithOrdering::Releasewhile holding the per-voice lock (withenablewaking the decoder thread afterward), matchingpump'sOrdering::Acquireload and per-slot re-check.voice.scratchis cleared before bothdecoder.flush(audio.rs:626) anddecoder.decode(audio.rs:664), avoiding stale PCM leakage across frames or failed decodes.Verification on
origin/main(63bcca43):cargo xtask policy: ok (191 files ok)cargo clippy --locked -p victory-formats -p victory-hle --all-targets -- -D warnings: cleancargo test --locked -p victory-formats -- xma::: 22/22 passed (3 ignored)cargo test --locked -p victory-hle -- modules::audio::: 9/9 passedAcpHalReleaseShapeContexts()while voices are active followed bypump(): passed.Imported from Marvisak/VIctory. Originally posted by passerbyyhx on 2026-11-26T22:34:48Z.
I captured one Windows kernel scheduler trace per revision with the same four-worker, single-pump Release workload used in the earlier allocation and timing comparison. At 4,096 rounds per run (16,384 voices), the parent
63bcca43c6a00a758510398fa43096ce7e4f7df0and head23e62b7c04f253f4e2fee181b77c16ec093350afproduced the same PCM checksum926c28842c9fde16. Both ETLs reported zero lost buffers and zero lost events.For each wait, I used the old thread's switch-out stack, the first matching ReadyThread event, and the next switch-in. The table excludes time spent ready to run. All completed intervals had a corresponding wakeup. At the right window boundary, three parent intervals and four head intervals were still open. Every measured pump wakeup came from a worker.
The fixture barrier accounts for over 99.9% of observed worker blocked time in both runs. No resolved blocking site identified a heap wait, per-voice lock wait or APU queue wait. These traces leave spinning, allocation work on CPU and the six unresolved worker intervals per build unattributed. One trace per revision cannot establish a timing regression or its cause.
Synthetic workload scheduler study and analysis source
AI-assisted with Codex.
Imported from Marvisak/VIctory. Originally posted by Damokles2 on 2026-11-27T06:51:28Z.
Nice work! I independently implemented a similar encoded XMA frame buffer reuse optimization yesterday, using a single 4 KiB scratch buffer owned by the audio worker.
While both ownership models have their merits, my implementation includes a synthetic regression fixture that may complement your existing tests.
It verifies:
The fixture should be adaptable to your
FrameMetaAPI without changing your buffer ownership model.Implementation and regression test:
https://github.com/Damokles2/VIctory/pull/1/files
Native Windows CI (872 tests passed, strict Clippy passed):
https://github.com/Damokles2/VIctory/actions/runs/45874582469
Feel free to incorporate the regression fixture if you find it useful.
Imported from Marvisak/VIctory. Originally posted by andrewpozdnakov7-jpg on 2026-11-28T00:27:45Z.
I checked
23e62b7together with the PCM output change from #3631. Both exact PR commits are retained in 6a92aae. The conflict resolution keeps your explicit output reservations in decode and flush, then uses the channel-specific PCM append.On Windows the combined branch matched all 32,000 PCM samples from the 62 generated mono frames and flush. The stereo flush regression passed as well. All 49 active formats tests and all nine HLE audio tests passed, including the active voice bitset, scratch reuse and output ring tests. Strict formats Clippy and the asset policy check passed.
If you reuse the PCM append or its test, please retain the Git author on cherry-pick or rebase, or add Co-authored-by: andrewpozdnakov7-jpg [email protected] if folding it into another commit.
Imported from Marvisak/VIctory. Originally posted by andrewpozdnakov7-jpg on 2026-11-28T02:20:02Z.
I added #3649 to the previously tested #3383/#3629/#3631 integration at
7713c9a. 2172a38 merges cleanly and retains all four exact PR heads. The new delta is the stereo coefficient-band transform.63bcca43, this PR's23e62b7, and the integration decoded the same 288 generated stereo frames at 24, 32, 44.1, and 48 kHz. The input frame bytes matched across all three runs. All 301,056 PCM samples, including flush output, matched bit for bit. The test exercised all-band transform, alternating-band transform, and scale-only bands.The integrated formats release suite passed 44 tests, with five ignored and five noise tests filtered. Strict formats Clippy and the asset policy check passed. This run covers decoder behavior on generated audio.
Please preserve the Git author if cherry-picking or rebasing, or keep this trailer if folding the change into another commit.
Co-authored-by: andrewpozdnakov7-jpg <[email protected]>Imported from Marvisak/VIctory. Originally posted by andrewpozdnakov7-jpg on 2026-11-28T04:45:15Z.
I checked #3666 with this PR in ae59889. The branch keeps the exact #3383 head and the tested #3629, #3631 and #3649 stack. I resolved the overlap in the shared band tables so only the selected sample rate is initialized on first use. The existing rate-bucket test and the new sharing test both pass.
Compared with the earlier combined branch, every band-table entry matched at 12 rates and all 301,056 generated PCM samples matched across the four rate buckets. The combined formats suite passed 50 tests, with five ignored. Strict formats Clippy and the asset policy passed.
In 21 paired fresh-process 48 kHz probes, the constructor median was 61.4 µs with this PR's first-use initialization of all four tables and 31.2 µs with per-rate initialization. Desamodeth or a maintainer can pick up the integration if the per-rate option fits the PR.
Please retain the Git authors on cherry-pick or rebase, or add
Co-authored-by: andrewpozdnakov7-jpg <[email protected]>if folding this resolution into another commit.AI-assisted with OpenAI Codex.
Imported from Marvisak/VIctory. Originally posted by Desamodeth on 2026-11-30T06:32:59Z.
Thanks @Damokles2 and @andrewpozdnakov7-jpg for the regression fixture offer and the integration testing across
#3629/#3631/#3649/#3666(ae59889)!Handoff note: I'm stepping away from this project, so I'm leaving
#3383as-is (clean onmain, green CI, 2 approvals). Maintainers or other contributors are welcome to merge it as-is or fold in the per-rateband_tablesinitialization / extra regression fixtures in a follow-up.AI-assisted with Gemini 4 Neon
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.