diff --git a/Cargo.lock b/Cargo.lock index a4cd9106..06c205fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -870,6 +870,7 @@ dependencies = [ "windows", "windows-core", "windows-sys", + "xtp-core", "xtp-formats", "xtp-gpu", "xtp-loader", diff --git a/README.md b/README.md index 22b979d7..23d5468b 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,7 @@ cargo build --profile diag -p xtp --features diagnostics # target\diag\xtp.exe | `XTP_SHADER_LOOP_BUDGET=` | (every build) a lane of a translated shader leaves, as at the loop limit, once it has gone back `n` times in all of its loops together instead of 1048576 (2^20; loops inside loops multiply their own limits); `0` turns the budget off (own shader cache entries) | | `XTP_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `XTP_XMA_DUMP=` | saves the first 32 XMA voices' context and input | +| `XTP_DSP_DUMP=` | captures the first 32 DSP streams per process outside the repository. Each numbered stream directory holds `params.txt`, `ir.f32le` (omitted if unreadable or over 4 MiB), and the first four commands' buffers and gains as raw little-endian floats. On Windows, compare `.output-before.f32le` with `.output.f32le` to see how the command changed its destination. Disconnect waits for pending writes. | | `XTP_WATCHDOG_HOOK=1` | every build: keeps the title's own watchdog from ending it after about 30 s without progress (slow world frames), and logs a warning (at most every 30 s) when it would have; a real deadlock then hangs for ever, with no `crashes.log` entry; known builds only, otherwise a warning and nothing patched | | `XTP_TITLE_ASSERTS=continue` | every build: where the title's own assertion would end it because an entry of its archive store could not be made (`int3` at title+0x23d8f03; the entry's header was not read, docs/analysis/archive-null.md), it takes the title's own path for a null object instead, and logs how many times (at once, then at most every 10 s) and a census of that store; hides the failure, it does not fix it; known builds only, otherwise a warning and nothing patched | | `XTP_XMEM_LEDGER=1` | every build: counts what the title asks of XMem by category (`XMemAlloc` by allocator id and memory type, committed resources included, the share our `XMemAllocDefault` serves, physical pages, virtual reserves, commits and frees, the budget reported) and logs each category that changed every 10 s: calls, failures, frees, live and peak bytes, bytes asked in all | diff --git a/crates/xtp-hle/Cargo.toml b/crates/xtp-hle/Cargo.toml index 5fd30a2c..c15b737a 100644 --- a/crates/xtp-hle/Cargo.toml +++ b/crates/xtp-hle/Cargo.toml @@ -8,6 +8,8 @@ license.workspace = true publish.workspace = true [dependencies] +xtp-core = { workspace = true, optional = true } +tempfile = { workspace = true, optional = true } xtp-gpu.workspace = true xtp-loader.workspace = true xtp-pe.workspace = true @@ -44,12 +46,15 @@ windows = { workspace = true, features = [ windows-core = { workspace = true, optional = true } [dev-dependencies] +xtp-core.workspace = true tempfile.workspace = true xtp-testkit.workspace = true [features] # Debugging switches (scripted keys and the like). diagnostics = [ + "dep:xtp-core", + "dep:tempfile", "xtp-gpu/diagnostics", "xtp-loader/diagnostics", "windows/Win32_Media_Audio", diff --git a/crates/xtp-hle/src/modules/dsp.rs b/crates/xtp-hle/src/modules/dsp.rs index 87c456ae..258526e7 100644 --- a/crates/xtp-hle/src/modules/dsp.rs +++ b/crates/xtp-hle/src/modules/dsp.rs @@ -24,6 +24,9 @@ use super::xasync::E_INVALIDARG; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; +#[cfg(any(test, feature = "diagnostics"))] +mod capture; + const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; @@ -35,6 +38,8 @@ const NOT_FOR_CONVOLUTION: u32 = 4; pub struct Dsp { max_streams: u32, active: Mutex, + #[cfg(any(test, feature = "diagnostics"))] + capture: Option, } /// What activation describes. @@ -62,6 +67,8 @@ pub struct Stream { frames: u32, channels: u32, status: Box, + #[cfg(any(test, feature = "diagnostics"))] + capture: Option, } /// One block of work. @@ -102,6 +109,8 @@ pub extern "system" fn XDspConnectWithMaximumStreamLimit( let dsp = Box::new(Dsp { max_streams, active: Mutex::new(0), + #[cfg(any(test, feature = "diagnostics"))] + capture: capture::Connection::open(ir_seconds, max_channels), }); // SAFETY: checked non-null. unsafe { out.write(Box::into_raw(dsp)) }; @@ -155,11 +164,11 @@ pub extern "system" fn XDspActivate( channels, "audio DSP stream activated" ); + // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. + let connection = unsafe { &*dsp }; { - // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. - let dsp = unsafe { &*dsp }; - let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); - if *active >= dsp.max_streams { + let mut active = connection.active.lock().unwrap_or_else(|e| e.into_inner()); + if *active >= connection.max_streams { return E_OUTOFMEMORY; } *active += 1; @@ -168,6 +177,11 @@ pub extern "system" fn XDspActivate( dsp, frames: desc.frames, channels: desc.channels, + #[cfg(any(test, feature = "diagnostics"))] + capture: connection.capture.as_ref().and_then(|capture| { + // SAFETY: the descriptor supplies the IR for the duration of activation. + unsafe { capture.activate(desc) } + }), status: Box::new(Status { submitted: 0, completed: 0, @@ -206,11 +220,21 @@ pub extern "system" fn XDspSubmitCommand( } // SAFETY: a stream from `XDspActivate`, the title's command. let (stream, command) = unsafe { (&mut *stream, &*command) }; + let samples = (stream.frames * stream.channels) as usize; + #[cfg(any(test, feature = "diagnostics"))] + let mut block = stream.capture.as_mut().and_then(|capture| { + // SAFETY: the caller supplies the input until completion. + unsafe { capture.begin_block(command, samples) } + }); if !command.output.is_null() { - let samples = (stream.frames * stream.channels) as usize; // SAFETY: the title's output buffer holds one block of the stream. unsafe { std::ptr::write_bytes(command.output, 0, samples) }; } + #[cfg(any(test, feature = "diagnostics"))] + if let Some(block) = &mut block { + // SAFETY: copy the initialized output before publishing completion. + block.output = unsafe { capture::copy_samples(command.output, samples) }; + } let status = &mut *stream.status; let next = status.submitted.wrapping_add(1); // SAFETY: the status block is read by title code on other threads. @@ -223,6 +247,10 @@ pub extern "system" fn XDspSubmitCommand( // SAFETY: optional out parameter. unsafe { ticket.write(next) }; } + #[cfg(any(test, feature = "diagnostics"))] + if let Some(block) = block { + block.enqueue(); + } S_OK } diff --git a/crates/xtp-hle/src/modules/dsp/capture.rs b/crates/xtp-hle/src/modules/dsp/capture.rs new file mode 100644 index 00000000..5f2b049d --- /dev/null +++ b/crates/xtp-hle/src/modules/dsp/capture.rs @@ -0,0 +1,436 @@ +//! Opt-in local captures of the DSP's stream format and first commands. + +use std::fs; +use std::io::{self, Write}; +use std::ops::Range; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, OnceLock, mpsc}; + +use super::{Command, StreamDesc}; + +const MAX_STREAMS: usize = 32; +const MAX_IR_BYTES: usize = 4 * 1024 * 1024; + +// At most 32 IRs and four command snapshots per stream can be queued +// in the process. Sending never waits for space or for the filesystem. +struct Writer { + jobs: mpsc::Sender>, + root: PathBuf, + streams: AtomicUsize, +} + +impl Writer { + fn open(root: PathBuf) -> io::Result { + if !root.is_absolute() { + return Err(io::Error::other("XTP_DSP_DUMP needs an absolute directory")); + } + xtp_core::ensure_outside_repo(&root).map_err(io::Error::other)?; + fs::create_dir_all(&root)?; + let root = fs::canonicalize(root)?; + let (jobs, queue) = mpsc::channel::>(); + std::thread::Builder::new() + .name("xtp DSP capture".into()) + .spawn(move || { + for job in queue { + job(); + } + })?; + Ok(Self { + jobs, + root, + streams: AtomicUsize::new(0), + }) + } + + fn submit(&self, job: impl FnOnce() -> io::Result<()> + Send + 'static) { + let _ = self.jobs.send(Box::new(move || { + if let Err(error) = job() { + tracing::warn!(%error, "could not write DSP capture"); + } + })); + } +} + +pub(super) struct Connection { + writer: &'static Writer, + ir_seconds: u32, + max_channels: u32, +} + +impl Connection { + pub(super) fn open(ir_seconds: u32, max_channels: u32) -> Option { + static WRITER: OnceLock> = OnceLock::new(); + let writer = WRITER + .get_or_init(|| { + let root = std::env::var_os("XTP_DSP_DUMP").filter(|s| !s.is_empty())?; + Writer::open(root.into()) + .inspect_err(|error| { + tracing::warn!(%error, "could not start DSP capture"); + }) + .ok() + }) + .as_ref()?; + Some(Self { + writer, + ir_seconds, + max_channels, + }) + } + + pub(super) unsafe fn activate(&self, desc: &StreamDesc) -> Option { + let writer = self.writer; + let id = writer + .streams + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| { + (n < MAX_STREAMS).then_some(n + 1) + }) + .ok()?; + let (kind, options, frames, channels, ir_floats) = ( + desc.kind, + desc.options, + desc.frames, + desc.channels, + desc.ir_floats, + ); + let params = format!( + "kind={kind}\noptions={options}\nframes={frames}\nchannels={channels}\nir_floats={ir_floats}\nir_seconds={}\nmax_channels={}\n", + self.ir_seconds, self.max_channels + ); + let oversized = ir_floats as usize > MAX_IR_BYTES / size_of::(); + let ir = if oversized { + None + } else { + // SAFETY: the descriptor supplies the IR during activation. + unsafe { copy_samples(desc.ir, ir_floats as usize) } + }; + let dir = Arc::new(OnceLock::new()); + let destination = Arc::clone(&dir); + writer.submit(move || { + if ir.is_none() { + tracing::warn!( + id, + ir_floats, + oversized, + "omitting unavailable DSP impulse response" + ); + } + let tmp = tempfile::Builder::new() + .prefix(&format!("stream-{id:03}-")) + .tempdir_in(&writer.root)?; + write_file(tmp.path(), "params.txt", Some(params.as_bytes()))?; + write_file(tmp.path(), "ir.f32le", ir.as_deref())?; + let path = tmp.keep(); + tracing::info!(id, path = %path.display(), "captured DSP stream"); + let _ = destination.set(path); + Ok(()) + }); + Some(Capture { + writer, + dir, + blocks: 0..4, + }) + } +} + +impl Drop for Connection { + fn drop(&mut self) { + // Flush work queued before disconnect, outside the command completion path. + let (done, wait) = mpsc::channel(); + self.writer.submit(move || { + let _ = done.send(()); + Ok(()) + }); + let _ = wait.recv(); + } +} + +pub(super) struct Capture { + writer: &'static Writer, + dir: Arc>, + blocks: Range, +} + +impl Capture { + pub(super) unsafe fn begin_block( + &mut self, + command: &Command, + samples: usize, + ) -> Option { + Some(Block { + n: self.blocks.next()?, + writer: self.writer, + dir: Arc::clone(&self.dir), + gains: command.gains, + // SAFETY: the input holds one block and may alias the output. + input: unsafe { copy_samples(command.input, samples) }, + #[cfg(windows)] + // SAFETY: on Windows the kernel copies bytes into initialized storage. + // The destination might never have been initialized as Rust floats. + output_before: unsafe { copy_samples(command.output, samples) }, + output: None, + }) + } +} + +pub(super) struct Block { + n: u8, + writer: &'static Writer, + dir: Arc>, + gains: [f32; 2], + input: Option>, + #[cfg(windows)] + output_before: Option>, + pub(super) output: Option>, +} + +impl Block { + pub(super) fn enqueue(self) { + self.writer.submit(move || { + let Some(dir) = self.dir.get() else { + return Ok(()); + }; + let n = self.n; + let gains = self.gains.map(f32::to_le_bytes).concat(); + for (side, data) in [ + ("input", self.input.as_deref()), + #[cfg(windows)] + ("output-before", self.output_before.as_deref()), + ("output", self.output.as_deref()), + ("gains", Some(gains.as_slice())), + ] { + write_file(dir, &format!("block-{n}.{side}.f32le"), data)?; + } + Ok(()) + }); + } +} + +fn write_file(dir: &Path, name: &str, data: Option<&[u8]>) -> io::Result<()> { + if let Some(data) = data { + let mut file = tempfile::NamedTempFile::new_in(dir)?; + file.write_all(data)?; + file.persist_noclobber(dir.join(name))?; + } + Ok(()) +} + +/// Caller bounds the count. Non-Windows callers must supply a readable buffer. +pub(super) unsafe fn copy_samples(data: *const f32, samples: usize) -> Option> { + if samples == 0 { + return Some(Vec::new()); + } + if data.is_null() { + return None; + } + let bytes = samples.checked_mul(size_of::())?; + #[cfg(windows)] + { + let mut copy = vec![0; bytes]; + xtp_loader::read_title_memory(data as usize, &mut copy).then_some(copy) + } + #[cfg(not(windows))] + // SAFETY: the caller supplies the stated buffer. XTP targets little-endian x64. + unsafe { + Some(std::slice::from_raw_parts(data.cast::(), bytes).to_vec()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::dsp::*; + use std::ptr; + + fn submit_in_place(capturing: bool) { + let mut base = vec![0u8; 0x10000]; + let (mut dsp, mut status, mut stream) = (ptr::null_mut(), ptr::null(), ptr::null_mut()); + for id in 1..=if capturing { MAX_STREAMS + 1 } else { 2 } { + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + base.len() as u32, + 1, + 1, + 2, + &mut dsp + ), + S_OK + ); + let pause = if capturing && id == 1 { + let (resume, wait) = mpsc::channel(); + // SAFETY: connect returned a live DSP. Hold its writer until submission returns. + unsafe { (*dsp).capture.as_ref().unwrap() } + .writer + .submit(move || { + let _ = wait.recv_timeout(std::time::Duration::from_secs(10)); + Ok(()) + }); + Some(resume) + } else { + None + }; + let mut ir = if id == 4 { + vec![0.25; MAX_IR_BYTES / size_of::()] + } else { + vec![-0.0, id as f32, -0.25] + }; + let desc = StreamDesc { + kind: CONVOLUTION, + options: 2, + frames: 512, + channels: 2, + ir_floats: if id == 3 { u32::MAX } else { ir.len() as u32 }, + // Windows validates the range through the kernel before copying. + ir: if cfg!(windows) && id == 5 { + ptr::dangling() + } else { + ir.as_ptr() + }, + }; + assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); + // SAFETY: activation returned a live stream. + let has_capture = unsafe { (*stream).capture.is_some() }; + assert_eq!(has_capture, capturing && id <= MAX_STREAMS); + ir.fill(0.0); + for n in 0..if id <= 2 { 5 } else { 0 } { + let mut block = [n as f32 + 0.5; 1024]; + let input = [-1.0; 1024]; + let command = Command { + gains: [0.25, -0.5], + input: if id == 1 { + block.as_ptr() + } else { + input.as_ptr() + }, + output: block.as_mut_ptr(), + reserved: 0, + }; + let mut ticket = 0; + assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK); + assert_eq!(ticket, n + 1); + // SAFETY: the live stream owns this status until deactivation. + assert_eq!(unsafe { (*status).completed }, ticket); + assert_eq!(block, [0.0; 1024]); + } + if let Some(resume) = pause { + let dump = std::env::var_os("XTP_DSP_DUMP").unwrap(); + assert_eq!(fs::read_dir(dump).unwrap().count(), 0); + resume.send(()).unwrap(); + } + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } + } + + #[test] + fn opt_in_stream_capture() { + const CHILD: &str = "XTP_TEST_DSP_CAPTURE_CHILD"; + if let Ok(mode) = std::env::var(CHILD) { + submit_in_place(mode == "on"); + return; + } + // Each child gets its own environment, so other DSP tests can run in parallel. + let tmp = tempfile::tempdir().unwrap(); + let run = |destination: Option<&Path>, mode: &str| { + let mut cmd = std::process::Command::new(std::env::current_exe().unwrap()); + cmd.current_dir(tmp.path()) + .env(CHILD, mode) + .env_remove("XTP_DSP_DUMP") + .args([ + "--exact", + "modules::dsp::capture::tests::opt_in_stream_capture", + ]); + if let Some(path) = destination { + cmd.env("XTP_DSP_DUMP", path); + } + let output = cmd.output().unwrap(); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + }; + run(None, "off"); + run(Some(Path::new("")), "off"); + run(Some(Path::new("relative")), "off"); + assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 0); + + let repo = tmp.path().join("repo"); + fs::create_dir(&repo).unwrap(); + fs::write(repo.join(".xtp-root"), []).unwrap(); + run(Some(&repo.join("dump")), "off"); + assert!(!repo.join("dump").exists()); + fs::write(tmp.path().join("file"), []).unwrap(); + run(Some(&tmp.path().join("file/dump")), "off"); + + let dump = tmp.path().join("dump"); + run(Some(&dump), "on"); + assert_eq!(fs::read_dir(&dump).unwrap().count(), MAX_STREAMS); + let mut dirs = fs::read_dir(dump) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect::>(); + dirs.sort(); + for (id, dir) in dirs.iter().enumerate() { + assert!( + dir.file_name() + .unwrap() + .to_str() + .unwrap() + .starts_with(&format!("stream-{id:03}-")) + ); + if id == 2 || (cfg!(windows) && id == 4) { + assert!(dir.join("params.txt").is_file()); + assert!(!dir.join("ir.f32le").exists()); + continue; + } + if id >= 3 { + if id == 3 { + assert_eq!( + fs::metadata(dir.join("ir.f32le")).unwrap().len(), + MAX_IR_BYTES as u64 + ); + } + continue; + } + assert_eq!( + fs::read_to_string(dir.join("params.txt")).unwrap(), + "kind=1\noptions=2\nframes=512\nchannels=2\nir_floats=3\nir_seconds=1\nmax_channels=2\n" + ); + assert_eq!( + fs::read(dir.join("ir.f32le")).unwrap(), + [-0.0, (id + 1) as f32, -0.25] + .map(f32::to_le_bytes) + .concat() + ); + for n in 0..4 { + let before = n as f32 + 0.5; + assert_eq!( + fs::read(dir.join(format!("block-{n}.input.f32le"))).unwrap(), + (if id == 0 { before } else { -1.0 }) + .to_le_bytes() + .repeat(1024) + ); + #[cfg(windows)] + assert_eq!( + fs::read(dir.join(format!("block-{n}.output-before.f32le"))).unwrap(), + before.to_le_bytes().repeat(1024) + ); + assert_eq!( + fs::read(dir.join(format!("block-{n}.output.f32le"))).unwrap(), + vec![0; 1024 * 4] + ); + assert_eq!( + fs::read(dir.join(format!("block-{n}.gains.f32le"))).unwrap(), + [0.25f32, -0.5].map(f32::to_le_bytes).concat() + ); + } + assert_eq!( + fs::read_dir(dir).unwrap().count(), + if cfg!(windows) { 18 } else { 14 } + ); + } + } +} diff --git a/crates/xtp-loader/src/crash.rs b/crates/xtp-loader/src/crash.rs index 5880fa61..e5f129ab 100644 --- a/crates/xtp-loader/src/crash.rs +++ b/crates/xtp-loader/src/crash.rs @@ -540,9 +540,9 @@ const MAX_CATCHABLE_TYPES: usize = 32; const MAX_STRING: usize = 256; static FIRST_CHANCE: AtomicUsize = AtomicUsize::new(0); -/// Copies exception-controlled memory through the kernel. Unlike a direct -/// dereference, this reports free, reserved, no-access and guard pages. -fn read_memory(address: usize, dst: &mut [u8]) -> bool { +/// Copies readable memory in the current process through the kernel. Returns +/// false for unmapped, reserved, no-access or guard pages. +pub fn read_memory(address: usize, dst: &mut [u8]) -> bool { if dst.is_empty() { return true; } diff --git a/crates/xtp-loader/src/lib.rs b/crates/xtp-loader/src/lib.rs index 80feb4c6..3f13cb85 100644 --- a/crates/xtp-loader/src/lib.rs +++ b/crates/xtp-loader/src/lib.rs @@ -55,7 +55,8 @@ pub use census::Census; pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ - locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, + locate, log_crash, log_crashes_to, note_title_output, read_memory as read_title_memory, + report_crashes, report_unhandled, }; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; diff --git a/docs/analysis/hle.md b/docs/analysis/hle.md index e27e3217..5c0dba53 100644 --- a/docs/analysis/hle.md +++ b/docs/analysis/hle.md @@ -193,7 +193,7 @@ Legend: ✔ implemented and tested, ◐ partial, ✘ missing, — not needed. | DSP convolution (reverb) | ✘ silent, IR layout unknown | ✘ | 1 / 1 | **New work** (A2, A3) | | XAudio2 | host pass-through | wrapped: Opus/XMA voices, console flags dropped | — / 9 | Keep XTP (Bink's voices are PCM; see Q6) | | Media Foundation | host + local-only resolver | host + device manager helper | 2 / 3 | Keep XTP | -| Capture for diagnosis | ✔ `XTP_AUDIO_CAPTURE`, `XTP_XMA_DUMP` | ◐ `XCL_TRACE_APU` | — | Keep XTP | +| Capture for diagnosis | ✔ `XTP_AUDIO_CAPTURE`, `XTP_XMA_DUMP`, `XTP_DSP_DUMP` | ◐ `XCL_TRACE_APU` | — | Keep XTP | ### 4.4 Input @@ -443,9 +443,10 @@ shows the title calls them. - **Depends on:** K1 showing a gain. ### A2. Capture the DSP's impulse responses — S -- **Goal:** `XTP_DSP_DUMP=` saves each activated stream's parameters, - impulse-response block and a few input/output blocks, to work out the - partitioned frequency-domain layout offline. +- **Diagnostic:** Set `XTP_DSP_DUMP` to an absolute directory outside the repository. + The first 32 streams per process record connection and stream parameters, an + impulse response up to 4 MiB and four commands' gains and input/output blocks + for offline study of the partitioned frequency-domain layout. - **Files:** `crates/xtp-hle/src/modules/dsp.rs`. - **xcl ref:** `hle/acphal.rs` XDsp functions (`XDspConnectWithMaximumStreamLimit`, `XDspActivate`: argument meaning as observed).