Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ cargo build --profile diag -p xtp --features diagnostics # target\diag\xtp.exe
| `XTP_DXIL_CENSUS=<file>` | (every build) appends one line per translated shader module to the file: its instructions by kind as translated and as written, and whether the clean-up passes were kept |
| `XTP_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) |
| `XTP_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input |
| `XTP_APU_DUMP=<dir>` | saves the first 32 Opus streams' packets (up to 256 packets per stream) as `.opuscap` files outside the repository for reference comparison via `XTP_SAMPLE_OPUS` |
| `XTP_DSP_DUMP=<absolute dir>` | 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 |
Expand Down
147 changes: 141 additions & 6 deletions crates/xtp-hle/src/modules/apu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,134 @@ pub struct Connection {
state: Mutex<State>,
}

/// Maximum number of Opus streams captured under `XTP_APU_DUMP`.
#[cfg(feature = "diagnostics")]
const MAX_DUMP_STREAMS: u32 = 32;

/// Maximum number of Opus packets appended per captured stream.
#[cfg(feature = "diagnostics")]
const MAX_DUMP_PACKETS: u32 = 256;

/// Magic header for `.opuscap` packet capture files (`"XOPU"` + `u16` channels + `u16` 0).
pub const CAPTURE_MAGIC: [u8; 4] = *b"XOPU";

/// Creates (or truncates) `path` and writes the 8-byte `"XOPU"` header for
/// `channels`.
pub fn create_capture_file(path: &std::path::Path, channels: u16) -> std::io::Result<()> {
use std::io::Write;
let mut file = std::fs::File::create(path)?;
file.write_all(&CAPTURE_MAGIC)?;
file.write_all(&channels.to_le_bytes())?;
file.write_all(&0u16.to_le_bytes())?;
Ok(())
}

/// Appends one length-prefixed Opus packet to `path`, creating the 8-byte
/// `XOPU` header first if the file does not exist yet.
pub fn append_capture_packet(
path: &std::path::Path,
channels: u16,
packet: &[u8],
) -> std::io::Result<()> {
use std::io::Write;
if !path.exists() {
create_capture_file(path, channels)?;
}
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
let len = u32::try_from(packet.len())
.map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "packet too large"))?;
file.write_all(&len.to_le_bytes())?;
file.write_all(packet)?;
Ok(())
}

/// Parses a `.opuscap` file written by [`append_capture_packet`] into
/// `(channels, packets)`.
pub fn read_capture_file(path: &std::path::Path) -> std::io::Result<(u16, Vec<Vec<u8>>)> {
let data = std::fs::read(path)?;
if data.len() < 8 || data[..4] != CAPTURE_MAGIC {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"not an XOPU capture file",
));
}
let channels = u16::from_le_bytes([data[4], data[5]]);
if !(1..=2).contains(&channels) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("unsupported channel count {channels}"),
));
}
let mut packets = Vec::new();
let mut pos = 8;
while pos + 4 <= data.len() {
let len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
pos += 4;
if pos + len > data.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"truncated Opus packet in capture file",
));
}
packets.push(data[pos..pos + len].to_vec());
pos += len;
}
Ok((channels, packets))
}

/// `XTP_APU_DUMP=<dir>`: saves the Opus packets queued on the first 32
/// streams (up to 256 packets per stream) into `<n>-s<stream>-<ch>ch.opuscap`,
/// for offline comparison against Windows' Opus MFT.
#[cfg(feature = "diagnostics")]
struct StreamDump {
path: std::path::PathBuf,
channels: u16,
written: u32,
}

#[cfg(feature = "diagnostics")]
impl StreamDump {
fn open(stream: usize, channels: u16) -> Option<Self> {
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let dir = std::path::PathBuf::from(std::env::var_os("XTP_APU_DUMP")?);
let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if n >= MAX_DUMP_STREAMS {
return None;
}
if let Err(e) = xtp_core::ensure_outside_repo(&dir) {
tracing::warn!(%e, "XTP_APU_DUMP refuses to write inside the repository");
return None;
}
if std::fs::create_dir_all(&dir).is_err() {
return None;
}
let path = dir.join(format!("{n:02}-s{stream}-{channels}ch.opuscap"));
create_capture_file(&path, channels).ok()?;
Some(Self {
path,
channels,
written: 0,
})
}

fn record(&mut self, packet: &[u8]) {
if self.written >= MAX_DUMP_PACKETS {
return;
}
if append_capture_packet(&self.path, self.channels, packet).is_ok() {
self.written += 1;
}
}
}

struct StreamSlot {
decoder: OpusDecoder,
#[cfg(feature = "diagnostics")]
dump: Option<StreamDump>,
}

struct State {
streams: Vec<Option<OpusDecoder>>,
streams: Vec<Option<StreamSlot>>,
/// Results not yet dequeued, per stream.
queued: Vec<u32>,
results: VecDeque<ApuResult>,
Expand Down Expand Up @@ -274,7 +400,11 @@ pub extern "system" fn XApuEnqueueCommand(
} else {
match OpusDecoder::new(48_000, channels as usize) {
Ok(d) if (1..=2).contains(&channels) => {
*decoder = Some(d);
*decoder = Some(StreamSlot {
decoder: d,
#[cfg(feature = "diagnostics")]
dump: StreamDump::open(stream, channels as u16),
});
S_OK
}
_ => E_INVALIDARG,
Expand All @@ -283,16 +413,16 @@ pub extern "system" fn XApuEnqueueCommand(
}
DEACTIVATE => *decoder = None,
RESET => {
if let Some(d) = decoder {
let _ = d.reset_state();
if let Some(slot) = decoder {
let _ = slot.decoder.reset_state();
}
}
NOTIFY => {}
PROCESS => {
// SAFETY: a process command is this struct.
let command = unsafe { command.cast::<Process>().read_unaligned() };
match decoder {
Some(d) => process(d, connection.options, &command, &mut result),
Some(slot) => process(slot, connection.options, &command, &mut result),
None => result.error = INVALID_STREAM,
}
}
Expand All @@ -314,7 +444,8 @@ pub extern "system" fn XApuEnqueueCommand(

/// Decodes one packet into the command's output buffer, keeping the frames
/// from `first_frame` on, at most `frame_count` of them.
fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) {
fn process(slot: &mut StreamSlot, options: u32, command: &Process, result: &mut ApuResult) {
let decoder = &mut slot.decoder;
let channels = decoder.channels();
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
Expand All @@ -327,6 +458,10 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &
}
// SAFETY: the title's packet in its connection memory.
let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
#[cfg(feature = "diagnostics")]
if let Some(dump) = &mut slot.dump {
dump.record(packet);
}
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) {
Ok(n) => n,
Expand Down
Loading