From 5bc2f120d01df1a2269d2cd8c77ba0f0e8af6b34 Mon Sep 17 00:00:00 2001 From: Simon GAY <86597303+simnJS@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:10:29 +0100 Subject: [PATCH 1/2] Opus: libopus from opus.dll where Windows has no decoder (Wine) Windows' MSOpusDecoder.dll (a Media Foundation MFT) does not exist under Wine or Proton, so every Opus voice was silent there. When the MFT cannot be created, opus.rs now loads libopus (BSD-3-Clause) from an opus.dll at run time, as XCL does for DXC: %XCL_OPUS_DIR% first, then next to xcl.exe. Windows keeps its own decoder; without either decoder nothing changes (silence, logged once). xcl.log says which decoder is used. The libopus decoder keeps its stream time like the MFT one (it starts at 0 and after a flush), so the check that a stream is at its start before the Ogg timing is applied stays true under Wine. A DLL that loads but lacks one of the four libopus functions is unloaded again. --- THIRD_PARTY.md | 1 + crates/xcl/src/hle/opus.rs | 206 +++++++++++++++++++++++++++++++++++-- 2 files changed, 201 insertions(+), 6 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 4afc9f29d..e2f7ec0d0 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -16,6 +16,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed | | docs.xbox.com | documentation | signatures, enums, structs written independently | reference | | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | +| [libopus](https://opus-codec.org/) (`opus.dll`) | BSD-3-Clause | Opus decoding where Windows has no `MSOpusDecoder.dll` (Wine): loaded at runtime from `%XCL_OPUS_DIR%` / next to xcl.exe (`hle/opus.rs`) | **not** distributed with XCL | | DXC (`dxcompiler.dll`, `dxil.dll`) from the Windows SDK | NCSA (dxcompiler) / Microsoft (dxil) | HLSL → DXIL compilation at runtime | loaded from the user's SDK, **not** distributed with XCL | | Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index c2d10189c..ac9c01313 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -826,9 +826,203 @@ fn mf_runtime() -> Result<&'static MfRuntime, String> { .map_err(|e| e.clone()) } -/// Whether Windows' built-in `MSOpusDecoder.dll` + Media Foundation runtime is available. +/// Whether an Opus decoder is available: Windows' built-in `MSOpusDecoder.dll` + Media Foundation +/// runtime, or libopus loaded from `opus.dll` (see [`libopus`]). pub fn is_available() -> bool { - mf_runtime().is_ok() + mf_runtime().is_ok() || libopus().is_ok() +} + +/// The decoder in use ("Windows MSOpusDecoder", "libopus (path)"), or why there is none. Logged once. +pub fn backend() -> String { + match (mf_runtime(), libopus()) { + (Ok(_), _) => "Windows' MSOpusDecoder (Media Foundation)".to_string(), + (_, Ok(l)) => format!("libopus ({})", l.path), + (Err(a), Err(b)) => format!("none ({a}; {b})"), + } +} + +// --------------------------------------------------------------------------------------- +// libopus from `opus.dll`, loaded at run time (where Windows' decoder does not exist: Wine) +// --------------------------------------------------------------------------------------- +// +// Not distributed with XCL (like DXC): `opus.dll` – libopus (BSD-3-Clause), built for Windows – is +// looked for in `%XCL_OPUS_DIR%`, then next to xcl.exe (`opus.dll`, `libopus.dll`, `libopus-0.dll`). +// Windows' own decoder is used first when the system has it. Only the decoder is used. + +type OpusDecoderCreateFn = unsafe extern "C" fn(i32, i32, *mut i32) -> *mut c_void; +type OpusDecodeFn = unsafe extern "C" fn(*mut c_void, *const u8, i32, *mut i16, i32, i32) -> i32; +type OpusDecoderDestroyFn = unsafe extern "C" fn(*mut c_void); +type OpusDecoderCtlFn = unsafe extern "C" fn(*mut c_void, i32, ...) -> i32; + +/// `OPUS_RESET_STATE`: the decoder starts again +const OPUS_RESET_STATE: i32 = 4028; + +struct LibOpus { + path: String, + create: OpusDecoderCreateFn, + decode: OpusDecodeFn, + destroy: OpusDecoderDestroyFn, + ctl: OpusDecoderCtlFn, +} + +static LIBOPUS: OnceLock> = OnceLock::new(); + +fn libopus() -> Result<&'static LibOpus, String> { + LIBOPUS + .get_or_init(|| unsafe { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Foundation::FreeLibrary; + use windows_sys::Win32::System::LibraryLoader::LoadLibraryW; + let mut dirs: Vec = Vec::new(); + if let Some(d) = std::env::var_os("XCL_OPUS_DIR") { + dirs.push(d.into()); + } + if let Some(d) = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())) { + dirs.push(d); + } + for dir in &dirs { + for name in ["opus.dll", "libopus.dll", "libopus-0.dll"] { + let path = dir.join(name); + if !path.is_file() { + continue; + } + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let h = LoadLibraryW(wide.as_ptr()) as usize; + if h == 0 { + continue; + } + let f = |n: &str| crate::resolver::system_proc_in(h, &crate::pe::ImportName::Name { hint: 0, name: n.into() }); + let (Some(create), Some(decode), Some(destroy), Some(ctl)) = + (f("opus_decoder_create"), f("opus_decode"), f("opus_decoder_destroy"), f("opus_decoder_ctl")) + else { + // a DLL that is not libopus (one of the four symbols is missing): not kept loaded + FreeLibrary(h as _); + continue; + }; + return Ok(LibOpus { + path: path.display().to_string(), + create: std::mem::transmute::(create), + decode: std::mem::transmute::(decode), + destroy: std::mem::transmute::(destroy), + ctl: std::mem::transmute::(ctl), + }); + } + } + Err("no opus.dll (libopus) in %XCL_OPUS_DIR% or next to xcl.exe".to_string()) + }) + .as_ref() + .map_err(|e| e.clone()) +} + +/// One libopus decoder (1 or 2 channels), the same job as [`MftDecoder`]. +struct LibDecoder { + lib: &'static LibOpus, + state: *mut c_void, + channels: u16, + output_rate: u32, + /// stream time of the next packet, as [`MftDecoder`] keeps it (0: nothing decoded since the start / the last flush) + timestamp_100ns: i64, +} + +impl LibDecoder { + fn new(channels: u16, sample_rate: u32) -> Result { + let lib = libopus()?; + let ch = channels.clamp(1, 2); + // libopus decodes to 8, 12, 16, 24 or 48 kHz + let rate = if matches!(sample_rate, 8_000 | 12_000 | 16_000 | 24_000 | 48_000) { sample_rate } else { 48_000 }; + let mut err = 0i32; + let state = unsafe { (lib.create)(rate as i32, ch as i32, &mut err) }; + if state.is_null() || err != 0 { + return Err(format!("opus_decoder_create: {err}")); + } + Ok(Self { lib, state, channels: ch, output_rate: rate, timestamp_100ns: 0 }) + } + + fn flush(&mut self) { + unsafe { + (self.lib.ctl)(self.state, OPUS_RESET_STATE); + } + self.timestamp_100ns = 0; + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + // as MftDecoder: an empty or malformed packet is an error (libopus would conceal a lost one) + parse_packet(packet, false).ok_or_else(|| "invalid RFC 6716 Opus packet".to_string())?; + let max_frames = (MAX_PACKET_SAMPLES_48K as usize * self.output_rate as usize) / 48_000; + let ch = self.channels as usize; + let start = out.len(); + out.resize(start + max_frames * ch, 0); + let n = unsafe { (self.lib.decode)(self.state, packet.as_ptr(), packet.len() as i32, out[start..].as_mut_ptr(), max_frames as i32, 0) }; + if n < 0 { + out.truncate(start); + return Err(format!("opus_decode: {n}")); + } + out.truncate(start + n as usize * ch); + // the time the packet covers: its frames at the output rate + self.timestamp_100ns = self.timestamp_100ns.saturating_add(n as i64 * 10_000_000 / self.output_rate as i64); + Ok(n as usize) + } +} + +impl Drop for LibDecoder { + fn drop(&mut self) { + unsafe { (self.lib.destroy)(self.state) } + } +} + +// SAFETY: a libopus decoder state is used by one thread at a time (`&mut self`). +unsafe impl Send for LibDecoder {} + +/// One single-stream decoder: Windows' MFT where there is one, else libopus. +enum SingleStreamDecoder { + Mft(MftDecoder), + Lib(LibDecoder), +} + +impl SingleStreamDecoder { + fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { + // the decoder actually made, logged once (Media Foundation can load and still fail to make one) + static CHOICE: std::sync::Once = std::sync::Once::new(); + let d = match MftDecoder::new(channels, sample_rate, head_bytes) { + Ok(d) => Ok(Self::Mft(d)), + Err(mft) => LibDecoder::new(channels, sample_rate).map(Self::Lib).map_err(|lib| format!("{mft}; {lib}")), + }; + CHOICE.call_once(|| match &d { + Ok(Self::Mft(_)) => crate::xlog_info!("Opus: decoder = Windows' MSOpusDecoder (Media Foundation)"), + Ok(Self::Lib(l)) => crate::xlog_info!("Opus: decoder = libopus ({})", l.lib.path), + Err(e) => crate::xlog_info!("Opus: decoder = none ({e})"), + }); + d + } + + fn output_rate(&self) -> u32 { + match self { + Self::Mft(d) => d.output_rate, + Self::Lib(d) => d.output_rate, + } + } + + /// stream time of the next packet (0: nothing decoded since the start / the last flush) + fn timestamp_100ns(&self) -> i64 { + match self { + Self::Mft(d) => d.timestamp_100ns, + Self::Lib(d) => d.timestamp_100ns, + } + } + + fn flush(&mut self) { + match self { + Self::Mft(d) => d.flush(), + Self::Lib(d) => d.flush(), + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + match self { + Self::Mft(d) => d.decode_packet(packet, out), + Self::Lib(d) => d.decode_packet(packet, out), + } + } } fn mf_create_media_type(rt: &MfRuntime) -> Result { @@ -882,7 +1076,7 @@ enum OutputSampleFormat { Float32, } -struct SingleStreamDecoder { +struct MftDecoder { mft: IMFTransform, channels: u16, output_rate: u32, @@ -892,7 +1086,7 @@ struct SingleStreamDecoder { timestamp_100ns: i64, } -impl SingleStreamDecoder { +impl MftDecoder { fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { let rt = mf_runtime()?; let mft = create_opus_mft(rt)?; @@ -1163,7 +1357,7 @@ impl Decoder { streams.push(SingleStreamDecoder::new(sch, rate, Some(&ud))?); } } - let output_rate = streams[0].output_rate; + let output_rate = streams[0].output_rate(); let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; let output_gain_scale = gain_scale(head.output_gain); @@ -1291,7 +1485,7 @@ impl Decoder { && t.head.coupled_count == self.coupled_count && t.head.mapping == self.mapping && gain_scale(t.head.output_gain) == self.output_gain_scale - && self.streams.iter().all(|s| s.timestamp_100ns == 0) + && self.streams.iter().all(|s| s.timestamp_100ns() == 0) }); if let Some(timing) = timing { for pkt in &packets { From 38bbfdabf42f69a271c993375140d6fb552312f2 Mon Sep 17 00:00:00 2001 From: Simon GAY <86597303+simnJS@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:11:33 +0100 Subject: [PATCH 2/2] xapu: decode the title's Opus packets into its output buffer (GTA VI's sound) GTA VI does not use XAudio2: it sends its sound to the console's decoder (xapu), and XCL answered every command with silence, so the game was mute. Traced with the new XCL_TRACE_APU=1 (acphal / xapu / DSP commands, their structures, buffers and callers): everything is on stream 0; Activate (kind 1) gives channels 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_frame 312 on the first command (the pre-skip), into a 3840 B f32 output; Deactivate is kind 2. The title sends nothing to xapu before its menu. Activate now creates an Opus decoder for the stream, Process decodes the packet into the title's output buffer and returns the frames written. Nothing is played from here: the title reads that output back, mixes it and plays its own mix on a system audio endpoint (Windows Spatial Audio), so decoding into the buffer is all XCL has to do. A listening test with the PCM also played on a voice of XCL's own heard the sound twice. The output is decoded into a local buffer and copied byte by byte (the title's pointer is not known to be 4-byte aligned); a stream the connection does not have is not decoded (silence of the length asked for); XCL_TRACE_APU reads only the size of the command's own structure. report.json gets xapu_* counters, and xcl.log a line every 5 s. --- crates/xcl/src/hle/acphal.rs | 327 ++++++++++++++++++++++++++++++++-- crates/xcl/src/hle/xaudio2.rs | 29 +++ 2 files changed, 337 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/acphal.rs b/crates/xcl/src/hle/acphal.rs index f43e43c38..3e2017aa6 100644 --- a/crates/xcl/src/hle/acphal.rs +++ b/crates/xcl/src/hle/acphal.rs @@ -1,12 +1,48 @@ //! The console's audio processor (`acphal.dll`, `xapu.dll`): memory the audio hardware //! addresses, the processor's command / message channel, SHAPE contexts and the decoder queue. //! -//! Nothing is decoded or mixed here – the processor answers as hardware with no work to do: -//! commands are acknowledged, audio frames tick (one every 128 samples at 48 kHz), SHAPE -//! context arrays exist, and the decoder returns silence of the length asked for. A title's -//! audio engine then starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole -//! audio setup), sounds decoded in software go wherever the engine sends them, and nothing -//! waits forever on the processor. Audio through the console's mixer (SHAPE) stays silent. +//! The processor answers as hardware with little to do: commands are acknowledged, audio frames +//! tick (one every 128 samples at 48 kHz), SHAPE context arrays exist. A title's audio engine then +//! starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole audio setup), and +//! nothing waits forever on the processor. The SHAPE mixer is not run. +//! +//! What runs is the decoder (xapu): Opus packets a title sends are decoded (`hle::opus`: Windows' +//! Media Foundation decoder, or libopus where Windows has none – without either the decoder answers +//! silence, logged once) and the PCM is written into the title's output buffer. Nothing is played +//! from here: the title reads that output back itself, mixes it and plays its own mix through a +//! system audio endpoint (Windows Spatial Audio), as a listening test showed – with the decoder's +//! PCM played on a voice of XCL's own as well, the sound came out twice. So XCL only has to decode +//! into the buffer. The SHAPE mixer is not run. `XCL_TRACE_APU=1` logs what a title sends (acphal +//! commands, xapu commands with their structures and the start of the Opus input, the caller in the +//! title, the rate per kind of command). +//! +//! # The decoder's commands as GTA sends them (observed with `XCL_TRACE_APU=1`, retail build) +//! +//! Every command starts with the 24-byte `XApuCommand` (`kind`, `stream`, `sequence`, `options`, +//! `context` u64); the title builds it on its stack and sets only the fields it uses (`kind` and +//! `stream`, the others are left as they were – `sequence`, `options`, `context` mean nothing to it), +//! then calls `XApuEnqueueCommand(handle, &command, &count)` and polls `XApuDequeueResult`. +//! GTA drives stream 0 only (so far) and is on one thread. +//! +//! * kind 1, Activate: `u32 channels` at +24 (1: mono, 2: stereo), the output rate 48000 at +56 (the +//! decoder is 48 kHz). Starts a stream. +//! * kind 3, Process: one Opus packet (RFC 6716, no length prefix, no container: 80 / 160 B mono +//! CELT full band 20 ms, TOC 0xF8; 320 B stereo, TOC 0xFC) in `input` / `input_bytes`; `frames` = 960 +//! (one packet), `first_frame` = 312 on the first command of a stream (the Opus pre-skip: decoded +//! frames to leave out), 0 after; the output is `frames × channels` float32 at `output` +//! (3 840 B mono). The input and output buffers are the same two for every command of the stream +//! (a ring the title refills); `ramp` is 0, the f32 "pitch" field holds 48000.0. A command every ~20 ms +//! once the title's own prefetch (a burst of ~20 commands, 4–6 ms apart) is done. +//! * kind 2, Deactivate: nothing after the header (the 40 bytes behind are the title's stack); the +//! title sends it when it releases the stream (`kind`, `stream`, sequence 0), then frees the +//! stream's slot. Activate / Deactivate alternate with no Process in between for short sounds. +//! * results: `state` bits 0 (output ready) and 1 (more input wanted), `frames` / `output_bytes` +//! the frames written (those after `first_frame`), `input` / `input_bytes` as sent. +//! * acphal: one command (`type` 2, id 0xF0F0F0F0, no data) right after `Connect`, nothing after +//! it during menus / sound (the SHAPE contexts are written in APU memory, not through commands); +//! the DSP (chad) gets nothing. +//! * APU memory: `ApuCreateHeap`, then `ApuAlloc` of 0x5780 (align 0x100), 0x222E00 (align 0x800, +//! flags 2) and 0x1913AFA0 (align 0x800, flags 1); `ApuMapVirtualAddress` is not called. //! //! Interfaces as titles call them (observed on retail titles; another project's notes on //! the same titles agree): `ApuAlloc(&va, &apu, size, alignment, flags)`, @@ -27,6 +63,7 @@ use std::ffi::c_void; use std::sync::Mutex; use std::time::{Duration, Instant}; +use crate::hle::{opus, xaudio2}; use crate::util::{HRESULT, S_OK}; const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; @@ -38,6 +75,109 @@ const XAPU_NO_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; /// one audio frame: 128 samples at 48 kHz const FRAME: Duration = Duration::from_micros(2667); +// --------------------------------------------------------------------------------------- +// XCL_TRACE_APU=1: what the title sends the audio processor and the decoder +// --------------------------------------------------------------------------------------- + +/// `XCL_TRACE_APU` set (not "0"): log the commands, their structures and buffers +fn trace_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_APU").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +/// Per kind of command: how many came, when the first and the last did (for the call frequency), +/// and how many were logged in full. +#[derive(Default)] +struct TraceKind { + count: u64, + logged: u32, + first: Option, + last_report: Option, + since_report: u64, +} + +/// the first commands of each kind are logged in full, then one line per second and kind +struct Tracer { + kinds: Vec<(&'static str, u32, TraceKind)>, +} + +static TRACER: Mutex = Mutex::new(Tracer { kinds: Vec::new() }); +/// commands of one kind logged in full +const TRACE_FULL: u32 = 24; + +/// true: log this command in full; false: tracing is off, or the command is only counted (a rate line +/// is logged here when due) +fn trace_command(origin: &'static str, kind: u32) -> bool { + if !trace_on() { + return false; + } + let now = Instant::now(); + let mut t = TRACER.lock().unwrap(); + let i = match t.kinds.iter().position(|k| k.0 == origin && k.1 == kind) { + Some(i) => i, + None => { + t.kinds.push((origin, kind, TraceKind::default())); + t.kinds.len() - 1 + } + }; + let k = &mut t.kinds[i].2; + k.count += 1; + k.since_report += 1; + k.first.get_or_insert(now); + if k.logged < TRACE_FULL { + k.logged += 1; + return true; + } + match k.last_report { + None => k.last_report = Some(now), + Some(r) if now.duration_since(r) >= Duration::from_secs(5) => { + let rate = k.since_report as f64 / now.duration_since(r).as_secs_f64(); + crate::xlog_info!("apu-trace: {origin} command {kind:#x}: {} so far, {rate:.1}/s", k.count); + k.last_report = Some(now); + k.since_report = 0; + } + _ => {} + } + false +} + +/// the return addresses of the call into the decoder's queue (`module+offset`), for the first +/// commands of a kind: where in the title's code it comes from +unsafe fn trace_callers(kind: u32) { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + static LOGGED: Mutex> = Mutex::new(Vec::new()); + { + let mut l = LOGGED.lock().unwrap(); + if l.iter().filter(|&&k| k == kind).count() >= 2 { + return; + } + l.push(kind); + } + let mut frames = [std::ptr::null_mut::(); 8]; + let n = RtlCaptureStackBackTrace(1, frames.len() as u32, frames.as_mut_ptr(), std::ptr::null_mut()); + let list: Vec = frames[..n as usize].iter().map(|&f| crate::modules::describe_address(f as usize)).collect(); + crate::xlog_info!("apu-trace: command {kind:#x} called from {}", list.join(" < ")); +} + +/// the bytes of an xapu command as the title sends them: its own structure, not a fixed size (a +/// command is 24 B for most kinds; reading more would run into whatever the title has behind it) +fn command_len(kind: u32) -> usize { + match kind { + XAPU_ACTIVATE => std::mem::size_of::(), + XAPU_PROCESS => std::mem::size_of::(), + _ => std::mem::size_of::(), + } +} + +/// up to `n` bytes at `p`, in hex (null: "null") +unsafe fn hex(p: *const c_void, n: usize) -> String { + if p.is_null() { + return "null".into(); + } + let b = std::slice::from_raw_parts(p as *const u8, n); + b.iter().map(|x| format!("{x:02x}")).collect::>().join("") +} + // --------------------------------------------------------------------------------------- // memory the audio processor addresses (32-bit APU addresses) // --------------------------------------------------------------------------------------- @@ -175,6 +315,9 @@ pub unsafe extern "system" fn ApuAlloc(va: *mut *mut c_void, apu: *mut u32, size if !apu.is_null() { *apu = a; } + if trace_command("ApuAlloc", 0) { + crate::xlog_info!("apu-trace: ApuAlloc({size:#x}, align {alignment:#x}, flags {_flags:#x}) -> va {p:#x} apu {a:#x}"); + } S_OK } @@ -208,6 +351,9 @@ pub unsafe extern "system" fn ApuMapVirtualAddress(apu: *mut u32, va: *mut c_voi return E_OUTOFMEMORY; }; *apu = a; + if trace_command("ApuMapVirtualAddress", 0) { + crate::xlog_info!("apu-trace: ApuMapVirtualAddress({va:p}, {size:#x}) -> apu {a:#x}"); + } S_OK } @@ -415,7 +561,11 @@ unsafe extern "system" fn hal_disconnect(h: *mut Hal) -> HRESULT { S_OK } -unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, _frame: u32, _data: *const c_void, _size: u32) -> HRESULT { +unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, frame: u32, data: *const c_void, size: u32) -> HRESULT { + if trace_command("acphal", kind) { + let dump = if data.is_null() || size == 0 { "none".to_string() } else { hex(data, (size as usize).min(96)) }; + crate::xlog_info!("apu-trace: acphal command {kind:#x} id {id:#x} frame {frame} data {data:p} size {size}: {dump}"); + } static SEEN: Mutex> = Mutex::new(Vec::new()); { let mut s = SEEN.lock().unwrap(); @@ -437,14 +587,22 @@ unsafe extern "system" fn hal_pop(h: *mut Hal, m: *mut Message) -> bool { } match (*h).channel.lock().unwrap().pop(Instant::now()) { Some(x) => { + if trace_command("acphal-pop", x.kind) { + let (kind, value, id) = (x.kind, x.value, x.id); + crate::xlog_info!("apu-trace: acphal PopMessage -> kind {kind:#x} value {value:#x} id {id:#x}"); + } *m = x; true } - None => false, + None => { + trace_command("acphal-pop", 0xFFFF_FFFF); + false + } } } unsafe extern "system" fn hal_count(h: *mut Hal) -> u32 { + trace_command("acphal-count", 0); (*h).channel.lock().unwrap().count(Instant::now()) } @@ -537,11 +695,22 @@ pub struct XApuConnectOutput { } const XAPU_ACTIVATE: u32 = 1; +const XAPU_DEACTIVATE: u32 = 2; const XAPU_PROCESS: u32 = 3; +/// What one decoder stream holds between commands. +struct XApuStream { + /// 1 or 2 (what Activate asked for) + channels: u32, + /// the Opus decoder of the stream (made by the first Activate; none: no decoder in this process) + decoder: Option, + /// between Activate and Deactivate; the decoder is kept across them and reset by the next Activate + active: bool, +} + struct XApu { results: Mutex>, - channels: Mutex>, + channels: Mutex>, data: usize, ready: usize, frames_per_output: u32, @@ -602,15 +771,88 @@ where clear_out(); return E_OUTOFMEMORY; } - channels.resize(n_streams, 2); + channels.resize_with(n_streams, || XApuStream { channels: 2, decoder: None, active: false }); let x = Box::new(XApu { results: Mutex::new(VecDeque::new()), channels: Mutex::new(channels), data, ready, frames_per_output: i.frames_per_output }); std::ptr::write_unaligned(output, XApuConnectOutput { data: data as *mut c_void, ready: ready as *mut c_void }); *handle = Box::into_raw(x) as *mut c_void; let (process, streams) = (i.process, i.streams); - crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – it answers with silence"); + if trace_on() { + let (data_bytes, per_stream, frames, options) = (i.data_bytes, i.commands_per_stream, i.frames_per_output, i.options); + crate::xlog_info!("apu-trace: XApuConnect: data {data_bytes:#x} B at {data:#x}, {per_stream} commands per stream, {frames} frames per output, options {options:#x}"); + } + crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – Opus packets are decoded (silence without an Opus decoder)"); S_OK } +/// The Opus decoder of a stream Activate (re)started. None when the process has no decoder (logged once). +fn new_decoder(stream: u32, channels: u32) -> Option { + static WARNED: std::sync::Once = std::sync::Once::new(); + match opus::Decoder::new(channels as u16, 48_000, &[]) { + Ok(d) => Some(d), + Err(e) => { + WARNED.call_once(|| crate::xlog_warn!("xapu: no Opus decoder ({e}) – the decoder answers with silence")); + crate::xlog_debug!("xapu: stream {stream} without decoder"); + None + } + } +} + +/// Decodes a Process command's input (an Opus packet) into `out` (float32 samples, `channels` interleaved): +/// `first_frame` frames of what the decoder produces are skipped, the rest fills `out` (what is not +/// produced stays silent). Returns the frames written (None: nothing was decoded). +unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mut [f32]) -> Option { + let (input, input_bytes, first_frame) = (p.input, p.input_bytes, p.first_frame); + if !s.active { + return None; + } + let dec = s.decoder.as_mut()?; + if input.is_null() || input_bytes == 0 { + return None; + } + let packet = std::slice::from_raw_parts(input as *const u8, input_bytes as usize); + let mut pcm: Vec = Vec::with_capacity(960 * 2); + let ch = s.channels as usize; + match dec.decode_packet(packet, &mut pcm) { + Ok(frames) if frames > 0 => { + let skip = (first_frame as usize).min(frames); + let produced = (frames - skip).min(out.len() / ch); + let mut nonzero = 0u64; + for (o, &v) in out.iter_mut().zip(pcm[skip * ch..(skip + produced) * ch].iter()) { + *o = v as f32 / 32768.0; + nonzero += (v != 0) as u64; + } + xaudio2::note_console_decode(1, 0, produced as u64, nonzero); + Some(produced) + } + other => { + xaudio2::note_console_decode(0, 1, 0, 0); + if trace_on() { + crate::xlog_info!("apu-trace: stream {stream}: {input_bytes} B did not decode ({other:?})"); + } + None + } + } +} + +/// Every 5 s while the decoder works: what it decoded (the log is what a run that is cut short +/// leaves; report.json is written at the start). +fn report_progress() { + static LAST: Mutex> = Mutex::new(None); + let now = Instant::now(); + { + let mut l = LAST.lock().unwrap(); + match *l { + Some(t) if now.duration_since(t) < Duration::from_secs(5) => return, + _ => *l = Some(now), + } + } + let a = xaudio2::stats(); + crate::xlog_info!( + "xapu: {} Opus packets decoded ({} errors), {} frames, {} non-zero samples", + a.xapu_packets_decoded, a.xapu_decode_errors, a.xapu_frames, a.xapu_nonzero_samples + ); +} + /// XApuConnect(&input, &output, &handle) pub unsafe extern "system" fn XApuConnect(input: *const XApuConnectInput, output: *mut XApuConnectOutput, handle: *mut *mut c_void) -> HRESULT { use windows_sys::Win32::System::Threading::CreateEventW; @@ -637,7 +879,8 @@ pub unsafe extern "system" fn XApuDisconnect(handle: *mut c_void) -> HRESULT { } /// XApuEnqueueCommand(handle, &command, &results waiting): done at once – a Process command -/// with silence of the length asked for +/// decodes its Opus packet into the output buffer (silence of the length asked for where there is +/// nothing to decode) pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: *const XApuCommand, count: *mut u32) -> HRESULT { use windows_sys::Win32::System::Threading::SetEvent; if handle.is_null() || command.is_null() { @@ -645,20 +888,58 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * } let x = &*(handle as *const XApu); let c = std::ptr::read_unaligned(command); + if trace_command("xapu", c.kind) { + let (kind, stream, seq, opts, ctx) = (c.kind, c.stream, c.sequence, c.options, c.context); + crate::xlog_info!("apu-trace: xapu command {kind:#x} stream {stream} seq {seq} options {opts:#x} context {ctx:p}: {}", hex(command as *const c_void, command_len(kind))); + trace_callers(kind); + if kind == XAPU_PROCESS { + let p = std::ptr::read_unaligned(command as *const XApuProcess); + let (ramp, pitch, first, frames, ib, input, ob, output) = (p.ramp, p.pitch, p.first_frame, p.frames, p.input_bytes, p.input, p.output_bytes, p.output); + crate::xlog_info!( + "apu-trace: process ramp {ramp} pitch {pitch} first_frame {first} frames {frames} input {ib} B at {input:p} output {ob} B at {output:p}; input starts {}", + hex(input, (ib as usize).min(512)) + ); + } + } let mut r = XApuResult { id: c, state: 0, state_data: 0, time: 0, error: S_OK, frames: 0, output_bytes: 0, output: std::ptr::null_mut(), pitch: 1.0, input_bytes: 0, input: std::ptr::null_mut() }; { let mut ch = x.channels.lock().unwrap(); - let s = if (c.stream as usize) < ch.len() { c.stream as usize } else { 0 }; + // a stream the connection does not have: no decoder, no state; a Process answers with silence + // of the length asked for, with the channel count of the first stream (if any; else stereo) + let known = (c.stream as usize) < ch.len(); if c.kind == XAPU_ACTIVATE { let n = std::ptr::read_unaligned(command as *const XApuActivate).channels; - ch[s] = if n == 1 { 1 } else { 2 }; + let channels = if n == 1 { 1 } else { 2 }; + if let Some(s) = ch.get_mut(c.stream as usize) { + match s.decoder.as_mut() { + // the stream started again with the same layout: its decoder is reset, not + // rebuilt (on Windows a new decoder is a new Media Foundation transform) + Some(d) if s.channels == channels => d.flush(), + _ => s.decoder = new_decoder(c.stream, channels), + } + s.channels = channels; + s.active = true; + } + } else if c.kind == XAPU_DEACTIVATE { + if let Some(s) = ch.get_mut(c.stream as usize) { + s.active = false; + } } else if c.kind == XAPU_PROCESS { let p = std::ptr::read_unaligned(command as *const XApuProcess); - let frame_bytes = ch[s] * 4; + let channels = if known { ch[c.stream as usize].channels } else { ch.first().map_or(2, |s| s.channels) }; + let frame_bytes = channels * 4; let asked = if p.frames != 0 { p.frames } else { x.frames_per_output }; - let frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); + let mut frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); if !p.output.is_null() && frames != 0 { - std::ptr::write_bytes(p.output as *mut u8, 0, (frames * frame_bytes) as usize); + // decoded here, then copied byte by byte: the title's buffer is not known to be 4-byte aligned + let mut out = vec![0.0f32; (frames * channels) as usize]; + // decoded: the frames after first_frame; not decoded: silence of the length asked for + if known { + if let Some(n) = decode_into(&mut ch[c.stream as usize], c.stream, &p, &mut out) { + frames = n as u32; + } + } + std::ptr::copy_nonoverlapping(out.as_ptr() as *const u8, p.output as *mut u8, out.len() * 4); } // output ready, more input wanted r.state = 1 | 2; @@ -668,6 +949,7 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * r.pitch = p.pitch; r.input_bytes = p.input_bytes; r.input = p.input; + report_progress(); } } let n = { @@ -689,6 +971,7 @@ pub unsafe extern "system" fn XApuDequeueResult(handle: *mut c_void, result: *mu if handle.is_null() || result.is_null() { return E_INVALIDARG; } + trace_command("xapu-dequeue", 0); match (*(handle as *const XApu)).results.lock().unwrap().pop_front() { Some(r) => { std::ptr::write_unaligned(result, r); @@ -747,7 +1030,10 @@ pub unsafe extern "system" fn XDspDisconnect(handle: *mut c_void) -> HRESULT { S_OK } -pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { + if trace_command("dsp", 0xA0) { + crate::xlog_info!("apu-trace: XDspActivate({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { E_INVALIDARG } else { @@ -763,8 +1049,11 @@ pub unsafe extern "system" fn XDspDeactivate(handle: *mut c_void, _a: usize, _b: } } -pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { static FIRST: std::sync::Once = std::sync::Once::new(); + if trace_command("dsp", 0x5C) { + crate::xlog_info!("apu-trace: XDspSubmitCommand({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { return E_INVALIDARG; } diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index 22baea9ec..fae020df1 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -171,6 +171,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { // --------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct AudioStats { pub engines: u64, pub engine_errors: u64, @@ -197,6 +198,12 @@ pub struct AudioStats { pub source_voice_errors: u64, /// console-only flags we dropped, e.g. "XAudio2Create:0x1" pub dropped_flags: Vec, + /// the console's decoder (xapu, `hle::acphal`): Opus packets decoded, packets that failed (silence + /// went out), frames produced, samples that are not 0 + pub xapu_packets_decoded: u64, + pub xapu_decode_errors: u64, + pub xapu_frames: u64, + pub xapu_nonzero_samples: u64, } static ENGINES: AtomicU64 = AtomicU64::new(0); @@ -236,6 +243,10 @@ pub fn stats() -> AudioStats { buffers_silenced: SILENCED.load(Ordering::Relaxed), source_voice_errors: SOURCE_ERRORS.load(Ordering::Relaxed), dropped_flags: DROPPED.lock().map(|d| d.clone()).unwrap_or_default(), + xapu_packets_decoded: PCM_PACKETS.load(Ordering::Relaxed), + xapu_decode_errors: PCM_PACKET_ERRORS.load(Ordering::Relaxed), + xapu_frames: PCM_DECODED_FRAMES.load(Ordering::Relaxed), + xapu_nonzero_samples: PCM_NONZERO.load(Ordering::Relaxed), } } @@ -1168,6 +1179,24 @@ unsafe extern "system" fn destroy_voice(this: *mut c_void) { } } +// --------------------------------------------------------------------------------------- +// the console audio processor's decoder (hle::acphal): what it did, for report.json +// --------------------------------------------------------------------------------------- + +static PCM_DECODED_FRAMES: AtomicU64 = AtomicU64::new(0); +static PCM_NONZERO: AtomicU64 = AtomicU64::new(0); +static PCM_PACKETS: AtomicU64 = AtomicU64::new(0); +static PCM_PACKET_ERRORS: AtomicU64 = AtomicU64::new(0); + +/// What the console decoder (xapu) did: `packets` Opus packets decoded to `frames` frames of which +/// `nonzero` samples are not 0, `errors` packets that did not decode (silence went out). +pub fn note_console_decode(packets: u64, errors: u64, frames: u64, nonzero: u64) { + PCM_PACKETS.fetch_add(packets, Ordering::Relaxed); + PCM_PACKET_ERRORS.fetch_add(errors, Ordering::Relaxed); + PCM_DECODED_FRAMES.fetch_add(frames, Ordering::Relaxed); + PCM_NONZERO.fetch_add(nonzero, Ordering::Relaxed); +} + #[cfg(test)] mod tests { use super::*;