xapu: decode the title's Opus packets and play them on the PC (retail title's sound) #294
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
goal:world-load
good first issue
help wanted
invalid
keep-open
off-goal
question
stale
test-only
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/xcl-dev--xcl!294
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/294/head"
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?
@simnJS on GitHub · 2026-11-23 22:35 UTC · original
xapu-opus→main· +538 −25 · 4 files · 2 commits · closed without mergingThe 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.dlldoes not exist.What the title sends (traced with the new
XCL_TRACE_APU=1, documented at the top ofhle/acphal.rs): everything goes to stream 0 throughXApuEnqueueCommand; 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_frame312 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 anISpatialAudioClientwith two static objects (front left / right), seen withWINEDEBUG=+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 toxcl.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.jsongetsxapu_*counters,xcl.loga summary line every 5 s.Tested
x86_64-pc-windows-gnu, release; libopus 1.5.2 built with mingw-w64 asopus.dll(#257'sscripts/linux/build-opus.sh).cargo build --workspace --all-targets --locked --target x86_64-pc-windows-gnuat each commit.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.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_DIRset 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 afterXCL_RUN_SECONDS(its watchdog: suspending every thread also stops vkd3d-proton's), so the earlier 60 s blocks with a 10 s grace saidkilled.peak commitreads 0 under Wine.mainat4017f8f:This PR's head
38bbfda:Not tested
scripts/smoke.ps1(no Windows machine; see the Windows runs above).AI use
@mastrr9 on GitHub · 2026-11-23 22:52 UTC · original
Independent static code audit of
6bae125e8(code inspection only —cargo testnot run on macOS; no game files):Concrete issues found
SubmitSourceBufferfailure (xaudio2.rs:1333-1354):v.next = (v.next + 1) % SINK_RINGadvances before checkinghr >= 0fromsubmit(v.voice, &b, ...). Ifqueued == SINK_RING - 2(22 buffers still playing in XAudio2) andsubmitfails more than twice in a row,v.nextwalks past the 2 free slots and overwrites aVec<f32>still referenced by an active XAudio2 buffer. Only advancingv.nextin thehr >= 0branch fixes this cleanly.LibDecoder::timestamp_100ns()hardcoded to0(opus.rs:623-628):Decoder::decode_bufferchecksself.streams.iter().all(|s| s.timestamp_100ns() == 0)to confirm the decoder is at a fresh stream boundary before applying Oggtiming. Returning0unconditionally forLibDecodermeans an already-usedlibopusstream (under Wine) will still pass that check on later buffers. Tracking decoded state /timestamp_100nsonLibDecoder(resetting it inflush()) matchesMftDecoder.Minor safety / edge-case notes
acphal.rs:885-910,184-190):std::slice::from_raw_parts_mut(p.output as *mut f32, ...)requires 4-byte alignment ofp.output(otherwise Rust UB); decoding into a localVec<f32>and writing viacopy_nonoverlappingavoids alignment assumptions. Similarly, underXCL_TRACE_APU=1,hex(command, 64)reads 64 bytes even for 24-byte commands (XApuDeactivate) without areadable()guard.acphal.rs:890): Ifn_streams == 0inXApuConnect,ch[0]panics; and ifc.stream as usize >= ch.len(), decoding mutatesch[0]whileconsole_pcm(c.stream, ...)plays underc.stream.opus.rs:522-531): If a candidate DLL inlibopus()loads viaLoadLibraryWbut lacks one of the four Opus exports,FreeLibraryis not called beforecontinue.(AI-assisted)
@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.first_frame312 pre-skip as described.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.
@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):ISpatialAudioClientfound 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 intop.outputand unconditionally plays it viaxaudio2::console_pcm, Windows users running #294 + #300 risk hearing everyxapu-decoded sound twice (once properly mixed/attenuated viaISpatialAudioClient, plus a raw full-volume copy fromconsole_pcm0–460 ms offset). Adding a switch (e.g.XCL_CONSOLE_PCM=0/1, or defaulting it off on Windows once confirmed thatp.outputflows throughISpatialAudioClient) would let Windows use the game's real mix while keeping direct playback for Wine / SHAPE-only titles.Activate/Deactivate/XApuDisconnectnever flush or clean up theconsole_pcmvoice (acphal.rs:895-896,xaudio2.rs:1290+): Up to 23 queued buffers (~460 ms) keep playing afterDeactivateand delay the next sound reusing the same stream slot by up to ~0.46 s, andXApuDisconnectleaves sink voices alive. Sending aReset/Destroycontrol message keyed by(handle as usize, stream)fixes both and avoids collisions if a title opens twoXApuConnecthandles.ActivateMFT churn (acphal.rs:800,894):out.len() / ch(e.g. 40/60 ms packets orframes_per_output = 256), the excess PCM is discarded while the Opus decoder advances past the whole packet.opus::Decoderon everyActivaterecreates Media Foundation MFTs on the title's audio thread when short sounds alternateActivate/Deactivate; callingflush()whenchannelsis unchanged avoids that churn.sink_thread&LibDecoderhardening:mpsc::channel(xaudio2.rs:1236) can grow without bound ifsink_engine()stalls (e.g. under Wine);sync_channel+try_sendbounds memory.CreateSourceVoice(xaudio2.rs:1319) retries and logs ~50×/s per stream.LibDecoder::decode_packetskipsparse_packet(unlikeMftDecoder), so empty packets invoke 120 ms PLC instead of returningErr; andbackend()can misreportMSOpusDecoderifmf_runtime()succeeds butMftDecoder::newfalls back tolibopus.(AI-assisted — Gemini 4 Neon + Claude Opus/Sonnet 5.5)
@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 twoxcl-smokeblocks 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 withWINEDEBUG=+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
console_pcm.LibDecodernow keeps a stream timestamp likeMftDecoder(advanced by each packet's frames, reset inflush()).Vec<f32>and copied into the title's buffer withcopy_nonoverlapping.ch[0]fallback is left (XApuConnectalready made at least one stream).@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 onopus::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.@mastrr9 on GitHub · 2026-11-23 23:30 UTC · original
Re-reviewed force-pushed head
268e376(static inspection only on macOS —cargo testand Windowssmoke.ps1not run; no game files):Confirmed fixed in
268e376console_pcmremoval (hle/acphal.rs,hle/xaudio2.rs): Removing XCL's extra XAudio2 playback voice cleanly resolves the Windows double-playback issue withISpatialAudioClient, along with the ring-buffer reuse race,Activate/Deactivate/XApuDisconnectvoice tail/leak, and unboundedmpsc::channel.LibDecoder::timestamp_100ns()(hle/opus.rs:661, 682, 697, 735): Now tracks decoded stream time (n * 10_000_000 / output_rate) and resets to0onflush(), matchingMftDecoderfor Ogg stream-boundary detection.p.outputalignment & bounds (hle/acphal.rs:504-511): Decodes into a localVec<f32>and copies byte-by-byte viacopy_nonoverlappingintop.output, eliminating alignment UB while zeroing any trailing frames withinout.len() * 4.c.stream(hle/acphal.rs:480-496): Guarded withknown/ch.get_mut(...), so an invalid stream index no longer clobbers stream 0's channel count or decoder.XCL_TRACE_APUcommand sizing (hle/acphal.rs:260-266, 463): Usescommand_len(kind)instead of reading past 24-byte commands likeDeactivate.LoadLibraryWcleanup (hle/opus.rs:635-637): CallsFreeLibraryif a candidate DLL lacks any of the four libopus symbols.Remaining nits (non-blocking)
LibDecoder::decode_packet(hle/opus.rs:690):xapualready guardsinput_bytes == 0, so GTA VI is unaffected, but on the shared XAudio2 Opus path an empty slice passed toopus_decode(..., 0, ...)triggers libopus PLC instead of returning an error likeMftDecoder(andi32::try_from(packet.len())avoids wrapping on absurdly large lengths).PR checks: Only failing because the Winesmoke.shblock reportsexit: killed (no exit)— once a Windows tester drops in a cleanscripts/smoke.ps1pair formainand268e376, this looks ready to go.AI use: static code re-review of
268e376with Antigravity (Gemini 4 Neon).@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_packetrunsparse_packetfirst, asMftDecoderdoes, so an empty or malformed packet is an error instead of libopus concealment.PR checks: thekilledwas the grace I gavesmoke.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.
@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 about6bae125). Windows run, clean tree, based onmain4017f8f. This covers the "Windows (the MFT path for xapu), the test suite" items; it does not coverscripts/smoke.ps1(no retail title here).Tested
stable-x86_64-pc-windows-msvc; DXC 1.9.2602.17 (SDK 10.0.26100.0); noXCL_SAMPLE_*setcargo build --workspace --release, thencargo test --workspace --release --no-fail-fast -- --test-threads=4: 652 passed, 0 failed, 40 ignoredcargo build --workspace, thencargo test --workspace --no-fail-fast -- --test-threads=4(debug): 652 passed, 0 failed, 40 ignoredSKIPPEDin both:gpu_geometry_wave32_prefix_count_over_a_mask,gpu_wave32_program_in_wave64_hardware(no wave64)main4017f8fon this machine; no new compiler warning (thefetch_updatedeprecation is onmaintoo).268e376gave the same counts before the last push.The xapu → MFT path on Windows, with the two tests below
Both pass on
38bbfdain debug and release, three runs each, and next to the PR's ownacphaltests (9 / 9):Opus: decoder = Windows' MSOpusDecoder (Media Foundation)MONO_HYBRID_20MSfromopus.rs),first_frame312 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_errorsstays 0The 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'smod tests; gated onopus::is_available()like theopus.rsones)The
xapu_packets_decodedcheck 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 Audioopus.dll) on Windows, stereo xapu streams, a long continuous streamAI use
@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.
@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 main2b4bb43together 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.mainreaches on Windows; the obstacle is replaced vtables — proposal: proxies #175Pull request closed