A GameCube/Wii emulator and debugger written in Rust.
fifo player
Laylee6e25c7c78d5
diff --git a/Cargo.lock b/Cargo.lockindex 200ee12..a4eec6d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1587,6 +1587,10 @@ dependencies = ["unicode-xid",]+[[package]]+name = "dff"+version = "0.1.0"+[[package]]name = "digest"version = "0.10.7"@@ -2030,6 +2034,21 @@ dependencies = ["bytemuck",]+[[package]]+name = "fifoplayer"+version = "0.1.0"+dependencies = [+ "backend-wgpu",+ "clap",+ "dff",+ "gecko",+ "pollster",+ "tracing",+ "tracing-subscriber",+ "wgpu",+ "winit 0.30.13",+]+[[package]]name = "find-msvc-tools"version = "0.1.9"@@ -2276,6 +2295,7 @@ dependencies = ["cranelift-native","crc32fast","crossbeam-channel",+ "dff","disasm","glam 0.32.1","hotpath",diff --git a/Cargo.toml b/Cargo.tomlindex 6264dd5..3bfa8c1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,6 +11,8 @@ members = ["crates/scripting","crates/dbglib","crates/debugger",+ "crates/dff",+ "crates/fifoplayer","crates/mcp",# Stuff we rarely usediff --git a/crates/backend-wgpu/src/capture.rs b/crates/backend-wgpu/src/capture.rsindex dad8fdc..ed271d9 100644--- a/crates/backend-wgpu/src/capture.rs+++ b/crates/backend-wgpu/src/capture.rs@@ -145,7 +145,7 @@ pub fn save_png_async(path: PathBuf, frame: CapturedFrame, force_opaque: bool) {.ok();}-fn write_png(path: &Path, mut frame: CapturedFrame, force_opaque: bool) -> std::io::Result<()> {+pub fn write_png(path: &Path, mut frame: CapturedFrame, force_opaque: bool) -> std::io::Result<()> {if force_opaque {for px in frame.rgba.chunks_exact_mut(4) {px[3] = 255;diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rsindex a1bc40d..7376c62 100644--- a/crates/backend-wgpu/src/sink.rs+++ b/crates/backend-wgpu/src/sink.rs@@ -33,6 +33,24 @@ pub enum TargetAspect {Ratio(f32),}+impl TargetAspect {+ pub fn from_arg(arg: &str, is_wii: bool) -> Self {+ match arg {+ "auto" => {+ if is_wii {+ TargetAspect::Ratio(16.0 / 9.0)+ } else {+ TargetAspect::Ratio(4.0 / 3.0)+ }+ }+ "4:3" => TargetAspect::Ratio(4.0 / 3.0),+ "16:9" => TargetAspect::Ratio(16.0 / 9.0),+ "stretch" => TargetAspect::Stretch,+ other => panic!("--aspect must be auto|4:3|16:9|stretch, got {other:?}"),+ }+ }+}+#[cfg(not(target_arch = "wasm32"))]pub struct ThreadedSink {work_tx: crossbeam_channel::Sender<WorkerCommand>,@@ -255,7 +273,7 @@ impl RenderSink for InlineSink {&action,&mut self.scratch,);-+if let GxAction::Draw(boxed) = action {self.recycled_draw_data.push(boxed);}diff --git a/crates/dbglib/src/windows.rs b/crates/dbglib/src/windows.rsindex 4d1de8a..53b516e 100644--- a/crates/dbglib/src/windows.rs+++ b/crates/dbglib/src/windows.rs@@ -6,6 +6,7 @@ pub mod cpu;pub mod dsp;pub mod dvd;pub mod exi;+pub mod fifo;pub mod gx;pub mod irq;pub mod lua;diff --git a/crates/dbglib/src/windows/fifo.rs b/crates/dbglib/src/windows/fifo.rsnew file mode 100644index 0000000..473b6fa--- /dev/null+++ b/crates/dbglib/src/windows/fifo.rs@@ -0,0 +1,91 @@+use egui::Context;+use egui_phosphor::regular as icons;+use gecko::flipper::gx::recorder::{FifoRecorder, RecorderState};++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum FifoRecorderAction {+ Start,+ Stop,+ Cancel,+}++fn human_bytes(bytes: u64) -> String {+ if bytes >= 1024 * 1024 {+ format!("{:.1} MiB", bytes as f64 / (1024.0 * 1024.0))+ } else if bytes >= 1024 {+ format!("{:.1} KiB", bytes as f64 / 1024.0)+ } else {+ format!("{bytes} B")+ }+}++pub fn show_fifo_recorder(+ ctx: &Context,+ open: &mut bool,+ recorder: Option<&FifoRecorder>,+ path_input: &mut String,+ last_result: &str,+ action: &mut Option<FifoRecorderAction>,+) {+ egui::Window::new("FIFO Recorder")+ .open(open)+ .resizable(false)+ .default_size(egui::vec2(240.0, 0.0))+ .show(ctx, |ui| {+ ui.set_min_width(220.0);+ let btn_size = egui::vec2(ui.available_width(), 0.0);++ match recorder {+ None => {+ ui.horizontal(|ui| {+ ui.label("Output:");+ egui::TextEdit::singleline(path_input)+ .desired_width(160.0)+ .font(egui::TextStyle::Monospace)+ .show(ui);+ });++ if ui+ .add_enabled(+ !path_input.trim().is_empty(),+ egui::Button::new(format!("{} Record", icons::RECORD)).min_size(btn_size),+ )+ .clicked()+ {+ *action = Some(FifoRecorderAction::Start);+ }+ ui.label(egui::RichText::new("Starts at the next presented frame").small().weak());+ }+ Some(rec) => {+ let state_label = match rec.state() {+ RecorderState::Waiting => "waiting for a frame",+ RecorderState::Recording => "recording",+ RecorderState::Done => "finishing",+ };+ ui.label(format!("{} {state_label}", icons::RECORD));+ ui.label(format!("frames: {}", rec.frames_recorded()));+ ui.label(format!("stream: {}", human_bytes(rec.fifo_bytes())));+ ui.label(format!("memory: {}", human_bytes(rec.update_bytes())));++ ui.separator();+ if ui+ .add(egui::Button::new(format!("{} Stop & Save", icons::STOP)).min_size(btn_size))+ .clicked()+ {+ *action = Some(FifoRecorderAction::Stop);+ }+ if ui+ .add(egui::Button::new(format!("{} Cancel", icons::TRASH)).min_size(btn_size))+ .clicked()+ {+ *action = Some(FifoRecorderAction::Cancel);+ }+ }+ }++ if !last_result.is_empty() {+ ui.separator();+ ui.label(egui::RichText::new(last_result).small());+ }+ });+}diff --git a/crates/debugger/src/debugger.rs b/crates/debugger/src/debugger.rsindex 6324ee3..8181c6f 100644--- a/crates/debugger/src/debugger.rs+++ b/crates/debugger/src/debugger.rs@@ -23,6 +23,7 @@ pub struct DebuggerUi {pub show_lua: bool,pub show_breakpoints: bool,pub show_about: bool,+ pub show_fifo_recorder: bool,pub memory_base: u32,pub memory_addr_input: String,pub run_until_addr_input: String,@@ -33,6 +34,9 @@ pub struct DebuggerUi {pub lua_load_pending: bool,pub gx_invalidate_requested: bool,pub gx_dump_requested: bool,+ pub fifo_path_input: String,+ pub fifo_last_result: String,+ pub fifo_action: Option<dbglib::windows::fifo::FifoRecorderAction>,}impl Default for DebuggerUi {@@ -52,6 +56,7 @@ impl Default for DebuggerUi {show_lua: false,show_breakpoints: false,show_about: true,+ show_fifo_recorder: false,memory_base: 0x8000_0000,memory_addr_input: "80000000".to_string(),run_until_addr_input: String::new(),@@ -62,6 +67,9 @@ impl Default for DebuggerUi {lua_load_pending: false,gx_invalidate_requested: false,gx_dump_requested: false,+ fifo_path_input: "fifo_dump.dff".to_string(),+ fifo_last_result: String::new(),+ fifo_action: None,}}}diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex bc79335..b9b321d 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -404,22 +404,6 @@ fn initial_window_size(target_aspect: TargetAspect) -> (u32, u32) {}}-fn resolve_aspect(arg: &str, is_wii: bool) -> TargetAspect {- match arg {- "auto" => {- if is_wii {- TargetAspect::Ratio(16.0 / 9.0)- } else {- TargetAspect::Ratio(4.0 / 3.0)- }- }- "4:3" => TargetAspect::Ratio(4.0 / 3.0),- "16:9" => TargetAspect::Ratio(16.0 / 9.0),- "stretch" => TargetAspect::Stretch,- other => panic!("--aspect must be auto|4:3|16:9|stretch, got {other:?}"),- }-}-fn main() {let env_filter = tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"))@@ -527,7 +511,7 @@ fn main() {let surface_format = wgpu::TextureFormat::Bgra8Unorm;- let target_aspect = resolve_aspect(&args.aspect, matches!(emulator, EmulatorVariant::Wii(_)));+ let target_aspect = TargetAspect::from_arg(&args.aspect, matches!(emulator, EmulatorVariant::Wii(_)));let (renderer, sink) =backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format, target_aspect);diff --git a/crates/debugger/src/render.rs b/crates/debugger/src/render.rsindex 841b14a..6737e72 100644--- a/crates/debugger/src/render.rs+++ b/crates/debugger/src/render.rs@@ -201,6 +201,7 @@ impl RenderState {ui.checkbox(&mut debugger_ui.show_irqs, "IRQ");ui.checkbox(&mut debugger_ui.show_controls, "Controls");ui.checkbox(&mut debugger_ui.show_breakpoints, "Breakpoints");+ ui.checkbox(&mut debugger_ui.show_fifo_recorder, "FIFO Recorder");ui.checkbox(&mut debugger_ui.show_lua, "Lua");});@@ -303,6 +304,18 @@ impl RenderState {&mut debugger_ui.breakpoint_addr_input,);}+ if debugger_ui.show_fifo_recorder {+ let mut action = None;+ dbglib::windows::fifo::show_fifo_recorder(+ &ctx,+ &mut debugger_ui.show_fifo_recorder,+ gx.recorder.as_deref(),+ &mut debugger_ui.fifo_path_input,+ &debugger_ui.fifo_last_result,+ &mut action,+ );+ debugger_ui.fifo_action = debugger_ui.fifo_action.or(action);+ }if debugger_ui.show_about {dbglib::windows::about::show_about(&ctx, &mut debugger_ui.show_about);}@@ -326,6 +339,43 @@ impl RenderState {}});+ match debugger_ui.fifo_action.take() {+ Some(dbglib::windows::fifo::FifoRecorderAction::Start) => {+ emulator.gx.recorder = Some(Box::new(gecko::flipper::gx::recorder::FifoRecorder::new()));+ debugger_ui.fifo_last_result = "recording until stopped".to_string();+ }+ Some(dbglib::windows::fifo::FifoRecorderAction::Stop) => {+ if let Some(rec) = emulator.gx.recorder.as_deref_mut() {+ rec.request_stop();+ }+ }+ Some(dbglib::windows::fifo::FifoRecorderAction::Cancel) => {+ emulator.gx.recorder = None;+ debugger_ui.fifo_last_result = "recording cancelled".to_string();+ }+ None => {}+ }++ if emulator+ .gx+ .recorder+ .as_deref()+ .is_some_and(|r| r.state() == gecko::flipper::gx::recorder::RecorderState::Done)+ {+ let rec = emulator.gx.recorder.take().unwrap();+ let file = rec.into_file();+ let frame_count = file.frames.len();+ if frame_count == 0 {+ debugger_ui.fifo_last_result = "no frames recorded, nothing saved".to_string();+ } else {+ let path = std::path::PathBuf::from(debugger_ui.fifo_path_input.trim());+ debugger_ui.fifo_last_result = match file.save(&path) {+ Ok(()) => format!("saved {frame_count} frames to {}", path.display()),+ Err(e) => format!("save failed: {e}"),+ };+ }+ }+if std::mem::take(&mut debugger_ui.gx_invalidate_requested) {emulator.gx.texture_hashes.clear();emulator.render_sink.exec(gecko::host::GxAction::InvalidateCaches);diff --git a/crates/dff/Cargo.toml b/crates/dff/Cargo.tomlnew file mode 100644index 0000000..37043c9--- /dev/null+++ b/crates/dff/Cargo.toml@@ -0,0 +1,6 @@+[package]+name = "dff"+version = "0.1.0"+edition = "2024"++[dependencies]diff --git a/crates/dff/src/lib.rs b/crates/dff/src/lib.rsnew file mode 100644index 0000000..937021a--- /dev/null+++ b/crates/dff/src/lib.rs@@ -0,0 +1,376 @@+use std::io;+use std::path::Path;++pub const FILE_ID: u32 = 0x0d01_f1f0;+pub const VERSION_NUMBER: u32 = 6;+pub const MIN_LOADER_VERSION: u32 = 1;++pub const BP_MEM_SIZE: usize = 256;+pub const CP_MEM_SIZE: usize = 256;+pub const XF_MEM_SIZE: usize = 4096;+pub const XF_REGS_SIZE: usize = 88;+pub const TEX_MEM_SIZE: usize = 1024 * 1024;++pub const MEM1_SIZE_RETAIL: u32 = 0x0180_0000;+pub const MEM2_SIZE_RETAIL: u32 = 0x0400_0000;++const FLAG_IS_WII: u32 = 1;+const HEADER_SIZE: usize = 128;+const FRAME_INFO_SIZE: usize = 64;+const MEMORY_UPDATE_SIZE: usize = 24;+const DEFAULT_GAME_ID: &str = "00000000";++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum MemoryUpdateType {+ TextureMap = 0x01,+ XfData = 0x02,+ VertexStream = 0x04,+ Tmem = 0x08,+}++impl MemoryUpdateType {+ fn from_raw(raw: u8) -> Self {+ match raw {+ 0x02 => MemoryUpdateType::XfData,+ 0x04 => MemoryUpdateType::VertexStream,+ 0x08 => MemoryUpdateType::Tmem,+ _ => MemoryUpdateType::TextureMap,+ }+ }+}++#[derive(Clone, Debug)]+pub struct MemoryUpdate {+ pub fifo_position: u32,+ pub address: u32,+ pub kind: MemoryUpdateType,+ pub data: Vec<u8>,+}++#[derive(Clone, Default, Debug)]+pub struct Frame {+ pub fifo_data: Vec<u8>,+ pub fifo_start: u32,+ pub fifo_end: u32,+ pub memory_updates: Vec<MemoryUpdate>,+}++pub struct DffFile {+ pub bp_mem: Vec<u32>,+ pub cp_mem: Vec<u32>,+ pub xf_mem: Vec<u32>,+ pub xf_regs: Vec<u32>,+ pub tex_mem: Vec<u8>,+ pub is_wii: bool,+ pub mem1_size: u32,+ pub mem2_size: u32,+ pub version: u32,+ pub game_id: String,+ pub frames: Vec<Frame>,+}++impl Default for DffFile {+ fn default() -> Self {+ DffFile {+ bp_mem: vec![0; BP_MEM_SIZE],+ cp_mem: vec![0; CP_MEM_SIZE],+ xf_mem: vec![0; XF_MEM_SIZE],+ xf_regs: vec![0; XF_REGS_SIZE],+ tex_mem: vec![0; TEX_MEM_SIZE],+ is_wii: false,+ mem1_size: MEM1_SIZE_RETAIL,+ mem2_size: MEM2_SIZE_RETAIL,+ version: VERSION_NUMBER,+ game_id: DEFAULT_GAME_ID.to_string(),+ frames: Vec::new(),+ }+ }+}++#[derive(Debug)]+pub enum DffError {+ Io(io::Error),+ BadMagic(u32),+ UnsupportedVersion(u32),+ Truncated,+}++impl std::fmt::Display for DffError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ DffError::Io(e) => write!(f, "io error: {e}"),+ DffError::BadMagic(m) => write!(f, "bad DFF magic {m:#010x}, expected {FILE_ID:#010x}"),+ DffError::UnsupportedVersion(v) => {+ write!(f, "DFF min loader version {v} exceeds supported {VERSION_NUMBER}")+ }+ DffError::Truncated => write!(f, "DFF file truncated"),+ }+ }+}++impl std::error::Error for DffError {}++impl From<io::Error> for DffError {+ fn from(e: io::Error) -> Self {+ DffError::Io(e)+ }+}++impl DffFile {+ pub fn save(&self, path: &Path) -> Result<(), DffError> {+ std::fs::write(path, self.to_bytes())?;+ Ok(())+ }++ pub fn load(path: &Path) -> Result<Self, DffError> {+ let bytes = std::fs::read(path)?;+ Self::from_bytes(&bytes)+ }++ pub fn to_bytes(&self) -> Vec<u8> {+ let frame_list_offset = HEADER_SIZE as u64;+ let mut out = vec![0u8; HEADER_SIZE + self.frames.len() * FRAME_INFO_SIZE];++ let bp_mem_offset = self::append_u32_slice(&mut out, &self.bp_mem, BP_MEM_SIZE);+ let cp_mem_offset = self::append_u32_slice(&mut out, &self.cp_mem, CP_MEM_SIZE);+ let xf_mem_offset = self::append_u32_slice(&mut out, &self.xf_mem, XF_MEM_SIZE);+ let xf_regs_offset = self::append_u32_slice(&mut out, &self.xf_regs, XF_REGS_SIZE);++ let tex_mem_offset = out.len() as u64;+ let n = self.tex_mem.len().min(TEX_MEM_SIZE);+ out.extend_from_slice(&self.tex_mem[..n]);+ out.resize(tex_mem_offset as usize + TEX_MEM_SIZE, 0);++ for (i, frame) in self.frames.iter().enumerate() {+ let fifo_data_offset = out.len() as u64;+ out.extend_from_slice(&frame.fifo_data);++ let updates_offset = out.len() as u64;+ out.resize(out.len() + frame.memory_updates.len() * MEMORY_UPDATE_SIZE, 0);++ for (j, update) in frame.memory_updates.iter().enumerate() {+ let data_offset = out.len() as u64;+ out.extend_from_slice(&update.data);++ let entry = updates_offset as usize + j * MEMORY_UPDATE_SIZE;+ out[entry..entry + 4].copy_from_slice(&update.fifo_position.to_le_bytes());+ out[entry + 4..entry + 8].copy_from_slice(&update.address.to_le_bytes());+ out[entry + 8..entry + 16].copy_from_slice(&data_offset.to_le_bytes());+ out[entry + 16..entry + 20].copy_from_slice(&(update.data.len() as u32).to_le_bytes());+ out[entry + 20] = update.kind as u8;+ }++ let entry = frame_list_offset as usize + i * FRAME_INFO_SIZE;+ out[entry..entry + 8].copy_from_slice(&fifo_data_offset.to_le_bytes());+ out[entry + 8..entry + 12].copy_from_slice(&(frame.fifo_data.len() as u32).to_le_bytes());+ out[entry + 12..entry + 16].copy_from_slice(&frame.fifo_start.to_le_bytes());+ out[entry + 16..entry + 20].copy_from_slice(&frame.fifo_end.to_le_bytes());+ out[entry + 20..entry + 28].copy_from_slice(&updates_offset.to_le_bytes());+ out[entry + 28..entry + 32].copy_from_slice(&(frame.memory_updates.len() as u32).to_le_bytes());+ }++ let mut h = HeaderWriter::new(&mut out);+ h.u32(FILE_ID);+ h.u32(VERSION_NUMBER);+ h.u32(MIN_LOADER_VERSION);+ h.u64(bp_mem_offset);+ h.u32(BP_MEM_SIZE as u32);+ h.u64(cp_mem_offset);+ h.u32(CP_MEM_SIZE as u32);+ h.u64(xf_mem_offset);+ h.u32(XF_MEM_SIZE as u32);+ h.u64(xf_regs_offset);+ h.u32(XF_REGS_SIZE as u32);+ h.u64(frame_list_offset);+ h.u32(self.frames.len() as u32);+ h.u32(if self.is_wii { FLAG_IS_WII } else { 0 });+ h.u64(tex_mem_offset);+ h.u32(TEX_MEM_SIZE as u32);+ h.u32(self.mem1_size);+ h.u32(self.mem2_size);+ h.game_id(&self.game_id);++ out+ }++ pub fn from_bytes(bytes: &[u8]) -> Result<Self, DffError> {+ let mut r = Reader { bytes, pos: 0 };++ let magic = r.u32()?;+ if magic != FILE_ID {+ return Err(DffError::BadMagic(magic));+ }++ let version = r.u32()?;+ let min_loader_version = r.u32()?;+ if min_loader_version > VERSION_NUMBER {+ return Err(DffError::UnsupportedVersion(min_loader_version));+ }++ let bp_mem_offset = r.u64()?;+ let bp_mem_size = r.u32()? as usize;+ let cp_mem_offset = r.u64()?;+ let cp_mem_size = r.u32()? as usize;+ let xf_mem_offset = r.u64()?;+ let xf_mem_size = r.u32()? as usize;+ let xf_regs_offset = r.u64()?;+ let xf_regs_size = r.u32()? as usize;+ let frame_list_offset = r.u64()?;+ let frame_count = r.u32()?;+ let flags = r.u32()?;+ let tex_mem_offset = r.u64()?;+ let tex_mem_size = r.u32()? as usize;+ let mem1_size = r.u32()?;+ let mem2_size = r.u32()?;+ let game_id_raw = r.bytes(8)?;++ let mut file = DffFile {+ is_wii: flags & FLAG_IS_WII != 0,+ version,+ ..DffFile::default()+ };++ if version >= 5 {+ file.mem1_size = mem1_size;+ file.mem2_size = mem2_size;+ }++ if version >= 6 {+ let len = game_id_raw.iter().position(|&b| b == 0).unwrap_or(8);+ file.game_id = String::from_utf8_lossy(&game_id_raw[..len]).into_owned();+ }++ self::read_u32_section(bytes, bp_mem_offset, bp_mem_size, &mut file.bp_mem)?;+ self::read_u32_section(bytes, cp_mem_offset, cp_mem_size, &mut file.cp_mem)?;+ self::read_u32_section(bytes, xf_mem_offset, xf_mem_size, &mut file.xf_mem)?;+ self::read_u32_section(bytes, xf_regs_offset, xf_regs_size, &mut file.xf_regs)?;++ if version >= 4 {+ let n = tex_mem_size.min(TEX_MEM_SIZE);+ let src = self::slice_at(bytes, tex_mem_offset, n)?;+ file.tex_mem[..n].copy_from_slice(src);+ }++ for i in 0..frame_count as usize {+ let entry = frame_list_offset as usize + i * FRAME_INFO_SIZE;+ let mut fr = Reader {+ bytes: self::slice_at(bytes, entry as u64, FRAME_INFO_SIZE)?,+ pos: 0,+ };+ let fifo_data_offset = fr.u64()?;+ let fifo_data_size = fr.u32()? as usize;+ let fifo_start = fr.u32()?;+ let fifo_end = fr.u32()?;+ let updates_offset = fr.u64()?;+ let num_updates = fr.u32()?;++ let mut frame = Frame {+ fifo_data: self::slice_at(bytes, fifo_data_offset, fifo_data_size)?.to_vec(),+ fifo_start,+ fifo_end,+ memory_updates: Vec::with_capacity(num_updates as usize),+ };++ for j in 0..num_updates as usize {+ let entry = updates_offset as usize + j * MEMORY_UPDATE_SIZE;+ let mut ur = Reader {+ bytes: self::slice_at(bytes, entry as u64, MEMORY_UPDATE_SIZE)?,+ pos: 0,+ };+ let fifo_position = ur.u32()?;+ let address = ur.u32()?;+ let data_offset = ur.u64()?;+ let data_size = ur.u32()? as usize;+ let kind = MemoryUpdateType::from_raw(ur.bytes(1)?[0]);++ frame.memory_updates.push(MemoryUpdate {+ fifo_position,+ address,+ kind,+ data: self::slice_at(bytes, data_offset, data_size)?.to_vec(),+ });+ }++ file.frames.push(frame);+ }++ Ok(file)+ }+}++fn append_u32_slice(out: &mut Vec<u8>, values: &[u32], count: usize) -> u64 {+ let offset = out.len() as u64;+ for i in 0..count {+ let v = values.get(i).copied().unwrap_or(0);+ out.extend_from_slice(&v.to_le_bytes());+ }+ offset+}++fn read_u32_section(bytes: &[u8], offset: u64, count: usize, dst: &mut [u32]) -> Result<(), DffError> {+ let n = count.min(dst.len());+ let src = self::slice_at(bytes, offset, n * 4)?;+ for (i, chunk) in src.chunks_exact(4).enumerate() {+ dst[i] = u32::from_le_bytes(chunk.try_into().unwrap());+ }+ Ok(())+}++fn slice_at(bytes: &[u8], offset: u64, len: usize) -> Result<&[u8], DffError> {+ let start = offset as usize;+ bytes.get(start..start + len).ok_or(DffError::Truncated)+}++struct HeaderWriter<'a> {+ out: &'a mut [u8],+ pos: usize,+}++impl<'a> HeaderWriter<'a> {+ fn new(out: &'a mut [u8]) -> Self {+ HeaderWriter { out, pos: 0 }+ }++ fn u32(&mut self, v: u32) {+ self.out[self.pos..self.pos + 4].copy_from_slice(&v.to_le_bytes());+ self.pos += 4;+ }++ fn u64(&mut self, v: u64) {+ self.out[self.pos..self.pos + 8].copy_from_slice(&v.to_le_bytes());+ self.pos += 8;+ }++ fn game_id(&mut self, id: &str) {+ let id = if id.len() > 8 || !id.is_ascii() {+ DEFAULT_GAME_ID+ } else {+ id+ };++ let bytes = id.as_bytes();+ self.out[self.pos..self.pos + bytes.len()].copy_from_slice(bytes);+ self.pos += 8;+ }+}++struct Reader<'a> {+ bytes: &'a [u8],+ pos: usize,+}++impl<'a> Reader<'a> {+ fn bytes(&mut self, n: usize) -> Result<&'a [u8], DffError> {+ let s = self.bytes.get(self.pos..self.pos + n).ok_or(DffError::Truncated)?;+ self.pos += n;+ Ok(s)+ }++ fn u32(&mut self) -> Result<u32, DffError> {+ Ok(u32::from_le_bytes(self.bytes(4)?.try_into().unwrap()))+ }++ fn u64(&mut self) -> Result<u64, DffError> {+ Ok(u64::from_le_bytes(self.bytes(8)?.try_into().unwrap()))+ }+}diff --git a/crates/fifoplayer/Cargo.toml b/crates/fifoplayer/Cargo.tomlnew file mode 100644index 0000000..90709c9--- /dev/null+++ b/crates/fifoplayer/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "fifoplayer"+version = "0.1.0"+edition = "2024"++[dependencies]+dff = { path = "../dff" }+gecko = { path = "../gecko" }+backend-wgpu = { path = "../backend-wgpu" }+clap = { version = "4.6.1", features = ["derive"] }+pollster = "0.4.0"+tracing = "0.1.44"+tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }+wgpu = "29.0.3"+winit = "0.30.13"diff --git a/crates/fifoplayer/src/main.rs b/crates/fifoplayer/src/main.rsnew file mode 100644index 0000000..16d0053--- /dev/null+++ b/crates/fifoplayer/src/main.rs@@ -0,0 +1,297 @@+mod playback;++use backend_wgpu::sink::{InlineSink, TargetAspect};+use clap::Parser;+use gecko::system::{GC, WII};+use std::path::PathBuf;+use std::sync::Arc;+use winit::application::ApplicationHandler;+use winit::event::WindowEvent;+use winit::event_loop::{ActiveEventLoop, EventLoop};+use winit::window::{Window, WindowId};++use crate::playback::{Playback, PlayerSink};++#[derive(Parser)]+#[command(about = "FIFO player (compatible with Dolphin)")]+struct Args {+ /// Path to the .dff FIFO log+ file: PathBuf,++ /// First frame of the playback range+ #[arg(long, default_value_t = 0)]+ start: usize,++ /// Last frame of the playback range (inclusive, default: last)+ #[arg(long)]+ end: Option<usize>,++ /// Play the range once instead of looping (windowed mode)+ #[arg(long)]+ once: bool,++ /// Headless: play up to --end once, write the presented XFB as PNG, exit+ #[arg(long)]+ screenshot: Option<PathBuf>,++ /// Display aspect ratio: auto (16:9 Wii / 4:3 GC), 4:3, 16:9, stretch+ #[arg(long, default_value = "auto")]+ aspect: String,+}++fn main() {+ let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"))+ .add_directive("cranelift_jit=warn".parse().unwrap())+ .add_directive("cranelift_codegen=warn".parse().unwrap())+ .add_directive("cranelift_frontend=warn".parse().unwrap())+ .add_directive("regalloc2=warn".parse().unwrap())+ .add_directive("wgpu_core=warn".parse().unwrap())+ .add_directive("wgpu_hal=warn".parse().unwrap())+ .add_directive("naga=warn".parse().unwrap());+ tracing_subscriber::fmt()+ .with_env_filter(env_filter)+ .without_time()+ .init();++ let args = Args::parse();++ let mut file = dff::DffFile::load(&args.file).unwrap_or_else(|e| {+ eprintln!("failed to load {}: {e}", args.file.display());+ std::process::exit(1);+ });+ if file.frames.is_empty() {+ eprintln!("{}: no frames", args.file.display());+ std::process::exit(1);+ }++ for frame in &mut file.frames {+ frame.memory_updates.sort_by_key(|u| u.fifo_position);+ }++ eprintln!(+ "{}: {} [{}] {} frames, version {}",+ args.file.display(),+ file.game_id,+ if file.is_wii { "Wii" } else { "GC" },+ file.frames.len(),+ file.version,+ );++ if file.is_wii {+ self::run::<WII>(file, args);+ } else {+ self::run::<GC>(file, args);+ }+}++fn run<const SYSTEM: gecko::SystemId>(file: dff::DffFile, args: Args) {+ let last = file.frames.len() - 1;+ let start = args.start.min(last);+ let end = args.end.unwrap_or(last).clamp(start, last);++ if let Some(ref out) = args.screenshot {+ self::run_headless::<SYSTEM>(&file, start, end, out);+ } else {+ self::run_windowed::<SYSTEM>(file, start, end, args.once, &args.aspect);+ }+}++fn init_wgpu() -> (wgpu::Instance, wgpu::Adapter, wgpu::Device, wgpu::Queue) {+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {+ backends: wgpu::Backends::all(),+ ..wgpu::InstanceDescriptor::new_without_display_handle()+ });+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::default(),+ compatible_surface: None,+ force_fallback_adapter: false,+ }))+ .expect("no compatible wgpu adapter");+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))+ .expect("failed to acquire wgpu device");+ (instance, adapter, device, queue)+}++fn run_headless<const SYSTEM: gecko::SystemId>(file: &dff::DffFile, start: usize, end: usize, out: &PathBuf) {+ let (_instance, _adapter, device, queue) = self::init_wgpu();++ let (gx, sink) = InlineSink::new(device.clone(), queue.clone(), wgpu::TextureFormat::Rgba8Unorm);+ let mut sink = PlayerSink::new(Box::new(sink));++ let mut playback = Playback::<SYSTEM>::new();+ playback.load_state(file, &mut sink);++ let mut presented = 0usize;+ for frame in &file.frames[start..=end] {+ if playback.play_frame(frame, &mut sink) {+ presented += 1;+ }+ }+ eprintln!("played frames {start}..={end}, {presented} presents");++ let _ = device.poll(wgpu::PollType::Wait {+ submission_index: None,+ timeout: None,+ });++ let g = gx.lock().unwrap();+ let captured = backend_wgpu::capture::capture_texture(&device, &queue, &g.xfb_texture).expect("XFB capture failed");+ backend_wgpu::capture::write_png(out, captured, true).expect("failed to write PNG");+ eprintln!("wrote {}", out.display());+}++struct WindowedApp<const SYSTEM: gecko::SystemId> {+ file: dff::DffFile,+ playback: Playback<SYSTEM>,+ sink: PlayerSink,+ start: usize,+ end: usize,+ once: bool,+ frame_idx: usize,+ finished: bool,+ window: Option<Arc<Window>>,+ surface: Option<(wgpu::Surface<'static>, wgpu::SurfaceConfiguration)>,+ renderer: backend_wgpu::sink::Renderer,+ instance: wgpu::Instance,+ adapter: wgpu::Adapter,+ device: wgpu::Device,+ queue: wgpu::Queue,+ surface_format: wgpu::TextureFormat,+}++impl<const SYSTEM: gecko::SystemId> WindowedApp<SYSTEM> {+ fn step(&mut self) {+ if self.finished {+ return;+ }+ self.playback+ .play_frame(&self.file.frames[self.frame_idx], &mut self.sink);+ if self.frame_idx >= self.end {+ if self.once {+ self.finished = true;+ } else {+ self.frame_idx = self.start;+ self.playback.load_state(&self.file, &mut self.sink);+ }+ } else {+ self.frame_idx += 1;+ }+ }+}++impl<const SYSTEM: gecko::SystemId> ApplicationHandler for WindowedApp<SYSTEM> {+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {+ let window = Arc::new(+ event_loop+ .create_window(+ Window::default_attributes()+ .with_title("gecko FIFO player")+ .with_inner_size(winit::dpi::PhysicalSize::new(1280, 960)),+ )+ .unwrap(),+ );++ let surface = self.instance.create_surface(window.clone()).unwrap();+ let actual = window.inner_size();+ let (sw, sh) =+ backend_wgpu::sink::snap_size_to_aspect((actual.width, actual.height), self.renderer.target_aspect());+ if (sw, sh) != (actual.width, actual.height) {+ let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(sw, sh));+ }+ let surface_caps = surface.get_capabilities(&self.adapter);+ let surface_config = wgpu::SurfaceConfiguration {+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ format: self.surface_format,+ width: sw.max(1),+ height: sh.max(1),+ present_mode: wgpu::PresentMode::Fifo,+ alpha_mode: surface_caps.alpha_modes[0],+ view_formats: vec![],+ desired_maximum_frame_latency: 2,+ };+ surface.configure(&self.device, &surface_config);++ window.request_redraw();+ self.window = Some(window);+ self.surface = Some((surface, surface_config));+ }++ fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {+ match event {+ WindowEvent::CloseRequested => event_loop.exit(),+ WindowEvent::Resized(size) => {+ if let (Some((surface, config)), Some(window)) = (&mut self.surface, &self.window) {+ if size.width == 0 || size.height == 0 {+ return;+ }+ let (sw, sh) = backend_wgpu::sink::snap_size_to_aspect(+ (size.width, size.height),+ self.renderer.target_aspect(),+ );+ if (sw, sh) != (size.width, size.height) {+ let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(sw, sh));+ }+ config.width = sw;+ config.height = sh;+ surface.configure(&self.device, config);+ }+ }+ WindowEvent::RedrawRequested => {+ self.step();++ let Some((surface, config)) = &self.surface else { return };+ let frame = match surface.get_current_texture() {+ wgpu::CurrentSurfaceTexture::Success(f) | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,+ status => {+ eprintln!("surface error: {status:?}");+ return;+ }+ };+ let view = frame.texture.create_view(&Default::default());+ self.renderer.blit(&self.queue, &view, (config.width, config.height));+ frame.present();++ if let Some(window) = &self.window {+ window.request_redraw();+ }+ }+ _ => {}+ }+ }+}++fn run_windowed<const SYSTEM: gecko::SystemId>(file: dff::DffFile, start: usize, end: usize, once: bool, aspect: &str) {+ let (instance, adapter, device, queue) = self::init_wgpu();++ let surface_format = wgpu::TextureFormat::Bgra8Unorm;+ let target_aspect = TargetAspect::from_arg(aspect, file.is_wii);+ let (renderer, sink) =+ backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format, target_aspect);++ let mut player_sink = PlayerSink::new(Box::new(sink));+ let mut playback = Playback::<SYSTEM>::new();+ playback.load_state(&file, &mut player_sink);++ let mut app = WindowedApp::<SYSTEM> {+ file,+ playback,+ sink: player_sink,+ start,+ end,+ once,+ frame_idx: start,+ finished: false,+ window: None,+ surface: None,+ renderer,+ instance,+ adapter,+ device,+ queue,+ surface_format,+ };++ let event_loop = EventLoop::new().unwrap();+ event_loop.run_app(&mut app).unwrap();+}diff --git a/crates/fifoplayer/src/playback.rs b/crates/fifoplayer/src/playback.rsnew file mode 100644index 0000000..39ee569--- /dev/null+++ b/crates/fifoplayer/src/playback.rs@@ -0,0 +1,207 @@+use gecko::flipper::gx::constants::{BP_REG_SIZE, CP_REG_SIZE};+use gecko::flipper::gx::{GraphicsProcessor, texture};+use gecko::host::{DrawData, DrawVertex, GxAction, RenderSink, XfbPart};+use gecko::mmio::{Mmio, RamViewMut};+use gecko::system::SystemId;++const BP_RESTORE_SKIP: &[usize] = &[0x45, 0x47, 0x48, 0x52, 0x65, 0xFE];++pub struct PlayerSink {+ inner: Box<dyn RenderSink>,+ xfb_heights: Vec<(u32, u32)>,+}++impl PlayerSink {+ pub fn new(inner: Box<dyn RenderSink>) -> Self {+ PlayerSink {+ inner,+ xfb_heights: Vec::new(),+ }+ }+}++impl RenderSink for PlayerSink {+ fn exec(&mut self, action: GxAction) {+ if let GxAction::CopyXfb { id, dst_h, .. } = &action {+ self.xfb_heights.push((*id, *dst_h));+ }+ self.inner.exec(action);+ }++ fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex> {+ self.inner.vertex_scratch()+ }++ fn flush_efb_copies(&mut self, ram: &mut RamViewMut<'_>) {+ self.inner.flush_efb_copies(ram);+ }++ fn take_draw_data(&mut self) -> Box<DrawData> {+ self.inner.take_draw_data()+ }+}++pub struct Playback<const SYSTEM: SystemId> {+ pub gx: GraphicsProcessor,+ pub mmio: Mmio<SYSTEM>,+}++impl<const SYSTEM: SystemId> Playback<SYSTEM> {+ pub fn new() -> Self {+ Playback {+ gx: GraphicsProcessor::new(),+ mmio: Mmio::new(),+ }+ }++ pub fn load_state(&mut self, file: &dff::DffFile, sink: &mut PlayerSink) {+ for (i, entry) in self.gx.palette_mem.iter_mut().enumerate() {+ let off = i * 2;+ if off + 2 > file.tex_mem.len() {+ break;+ }++ *entry = u16::from_be_bytes([file.tex_mem[off], file.tex_mem[off + 1]]);+ }++ let mut stream: Vec<u8> = Vec::with_capacity(32 * 1024);++ for (i, val) in file.cp_mem.iter().enumerate().take(CP_REG_SIZE) {+ stream.push(0x08);+ stream.push(i as u8);+ stream.extend_from_slice(&val.to_be_bytes());+ }++ let xf_all: Vec<u32> = file.xf_mem.iter().chain(file.xf_regs.iter()).copied().collect();+ for start in (0..xf_all.len()).step_by(16) {+ let n = 16.min(xf_all.len() - start);++ stream.push(0x10);+ stream.extend_from_slice(&((n - 1) as u16).to_be_bytes());+ stream.extend_from_slice(&(start as u16).to_be_bytes());++ for val in &xf_all[start..start + n] {+ stream.extend_from_slice(&val.to_be_bytes());+ }+ }++ for (i, val) in file.bp_mem.iter().enumerate().take(BP_REG_SIZE) {+ if BP_RESTORE_SKIP.contains(&i) {+ continue;+ }++ stream.push(0x61);+ stream.push(i as u8);++ let v = val & 0x00ff_ffff;+ stream.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8, v as u8]);+ }++ self.feed(&stream, sink);+ }++ fn feed(&mut self, bytes: &[u8], sink: &mut PlayerSink) {+ self.gx.fifo.extend_from_slice(bytes);+ self.gx.drain_fifo(&mut self.mmio, sink);+ }++ pub fn play_frame(&mut self, frame: &dff::Frame, sink: &mut PlayerSink) -> bool {+ let mut pos = 0usize;++ for update in &frame.memory_updates {+ let p = (update.fifo_position as usize).min(frame.fifo_data.len());+ if p > pos {+ self.feed(&frame.fifo_data[pos..p], sink);+ pos = p;+ }++ self.apply_update(update, sink);+ }++ if pos < frame.fifo_data.len() {+ self.feed(&frame.fifo_data[pos..], sink);+ }++ self.present(sink)+ }++ fn apply_update(&mut self, update: &dff::MemoryUpdate, sink: &mut PlayerSink) {+ {+ let mut ram = self.mmio.ram_view_mut();+ match ram.slice_mut(update.address as usize, update.data.len()) {+ Some(dst) => dst.copy_from_slice(&update.data),+ None => {+ tracing::warn!(+ addr = format!("{:#010X}", update.address),+ len = update.data.len(),+ "memory update outside RAM, skipping"+ );+ return;+ }+ }+ }++ if update.kind == dff::MemoryUpdateType::TextureMap && self.update_overlaps_bound_texture(update) {+ let view = self.mmio.ram_view();+ self.gx.refresh_bound_textures(sink, &view);+ }+ }++ fn update_overlaps_bound_texture(&self, update: &dff::MemoryUpdate) -> bool {+ let a = update.address as usize;+ let a_end = a + update.data.len();+ self.gx.cur_textures.iter().flatten().any(|desc| {+ let t = desc.ram_addr;+ let t_end = t + texture::raw_data_size(desc.width, desc.height, desc.format);+ a < t_end && t < a_end+ })+ }++ fn present(&mut self, sink: &mut PlayerSink) -> bool {+ let heights = std::mem::take(&mut sink.xfb_heights);+ if self.gx.xfb_copies.is_empty() {+ return false;+ }++ let bytes_per_row = self.gx.xfb_copies[0].dest_stride.max(2);+ let stride_px = bytes_per_row / 2;+ let min_base = self.gx.xfb_copies.iter().map(|c| c.dest_addr).min().unwrap();++ let mut parts: Vec<XfbPart> = Vec::new();+ let mut frame_h = 0u32;+ for copy in &self.gx.xfb_copies {+ let delta_px = (copy.dest_addr - min_base) / 2;+ let offset_x = delta_px % stride_px;+ let offset_y = delta_px / stride_px;+ if offset_x != 0 {+ continue;+ }+ let dst_h = heights+ .iter()+ .rev()+ .find(|(id, _)| *id == copy.dest_addr)+ .map(|(_, h)| *h)+ .unwrap_or(copy.src_h);+ frame_h = frame_h.max(offset_y + dst_h);+ if !parts.iter().any(|p| p.id == copy.dest_addr) {+ parts.push(XfbPart {+ id: copy.dest_addr,+ offset_x: 0,+ offset_y,+ });+ }+ }+ self.gx.xfb_copies.clear();++ if parts.is_empty() || frame_h == 0 {+ return false;+ }+ sink.exec(GxAction::PresentXfb {+ width: stride_px,+ height: frame_h,+ parts,+ });++ true+ }+}diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.tomlindex 445c59d..a8d07e5 100644--- a/crates/gecko/Cargo.toml+++ b/crates/gecko/Cargo.toml@@ -32,6 +32,7 @@ chipi-build = "0.9.1"[dependencies]chapa = "0.1.2"+dff = { path = "../dff" }tracing = { version = "0.1.44", features = ["release_max_level_off"] }image = { path = "../image", default-features = false }disasm = { path = "../disasm" }diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex 59cede8..bae9c83 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -5,6 +5,7 @@ pub mod fifo;#[cfg(feature = "jit")]pub mod jit;pub mod math;+pub mod recorder;pub mod regs;pub mod tev;mod texgen;@@ -34,6 +35,9 @@ pub struct GraphicsProcessor {pub fifo: Vec<u8>,pub dl_scratch: Vec<u8>,+ // FIFO recording stuff+ pub recorder: Option<Box<recorder::FifoRecorder>>,+// Current GX state to snapshot into a Draw action laterpub cur_textures: [Option<draw::TextureDescriptor>; 8],// Per-texture-slot TLUT binding (tmem offset + palette pixel format),@@ -131,6 +135,7 @@ impl GraphicsProcessor {xf_mem: vec![0; XF_MEM_SIZE],fifo: Vec::with_capacity(256),dl_scratch: Vec::with_capacity(4096),+ recorder: None,projection: Matrix4::default(),cur_textures: Default::default(),cur_tluts: [draw::TlutRef::default(); 8],@@ -195,6 +200,17 @@ pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {return;}+ if sys.gx.recorder.is_some() {+ let mut rec = sys.gx.recorder.take().unwrap();+ rec.on_frame_boundary(+ &sys.gx,+ sys.cp.fifo_base(),+ sys.cp.fifo_end(),+ SYSTEM == crate::system::WII,+ );+ sys.gx.recorder = Some(rec);+ }+#[cfg(feature = "gx-stats")]{sys.gx.stats.xfb_presents += 1;diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex 3431971..d704074 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -1,4 +1,5 @@use super::constants::*;+use super::recorder::MemoryUpdateType;use super::regs::*;use super::{GraphicsProcessor, draw, texture};use crate::host::{GxAction, RenderSink, TextureKey};@@ -187,6 +188,7 @@ impl GraphicsProcessor {if idx == BP_PE_DONE && (val & BP_PE_DONE_FINISH_BIT) != 0 {self.raise_interrupt = true;renderer.flush_efb_copies(ram);+ self.sync_recorder_efb_shadow(ram);}// PE token (0x47): store token value only@@ -194,6 +196,7 @@ impl GraphicsProcessor {self.pending_token = (val & 0xFFFF) as u16;self.token_dirty = true;renderer.flush_efb_copies(ram);+ self.sync_recorder_efb_shadow(ram);}// PE token interrupt (0x48): store token value + raise interrupt@@ -203,6 +206,7 @@ impl GraphicsProcessor {self.token_dirty = true;self.raise_token_interrupt = true;renderer.flush_efb_copies(ram);+ self.sync_recorder_efb_shadow(ram);}// Scissor registers (BP 0x20 = TL, 0x21 = BR, 0x59 = OFFSET).@@ -226,21 +230,10 @@ impl GraphicsProcessor {}fn snapshot_texture(&mut self, renderer: &mut dyn RenderSink, ram: &RamView<'_>, slot: usize, image3_val: u32) {- let image0_reg = if slot < 4 {- BP_TX_SETIMAGE0_I0 + slot- } else {- BP_TX_SETIMAGE0_I4 + (slot - 4)- };-- let image0 = TxSetImage0::from_raw(self.bp_regs[image0_reg]);+ let image0 =+ TxSetImage0::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETIMAGE0_I0, BP_TX_SETIMAGE0_I4, slot)]);let image3 = TxSetImage3::from_raw(image3_val);-- let mode0_reg = if slot < 4 {- BP_TX_SETMODE0_I0 + slot- } else {- BP_TX_SETMODE0_I4 + (slot - 4)- };- let mode0 = TxSetMode0::from_raw(self.bp_regs[mode0_reg]);+ let mode0 = TxSetMode0::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4, slot)]);let width = (image0.width() + 1) as u32;let height = (image0.height() + 1) as u32;@@ -277,6 +270,12 @@ impl GraphicsProcessor {let raw_size = texture::raw_data_size(width, height, format);let tex_slice = ram.slice(ram_addr, raw_size);+ if tex_slice.is_some()+ && let Some(rec) = self.recorder.as_deref_mut()+ {+ rec.use_memory(ram, ram_addr as u32, raw_size, MemoryUpdateType::TextureMap);+ }+let changed = match tex_slice {Some(tex) => self::texture_data_changed(&mut self.texture_hashes, tex, cache_id, palette, tlut, format),None => {@@ -336,6 +335,17 @@ impl GraphicsProcessor {});}+ pub fn refresh_bound_textures(&mut self, renderer: &mut dyn RenderSink, ram: &RamView<'_>) {+ for slot in 0..self.cur_textures.len() {+ if self.cur_textures[slot].is_none() {+ continue;+ }++ let image3_val = self.bp_regs[self::tx_slot_reg(BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, slot)];+ self.snapshot_texture(renderer, ram, slot, image3_val);+ }+ }+/// If the slot currently binds a paletted texture, rerun the snapshot/// pipeline so `texture_data_changed` rehashes the (now possibly fresh)/// palette bytes + TLUT format and decodes a new RGBA if anything moved.@@ -346,12 +356,7 @@ impl GraphicsProcessor {if !desc.format.is_paletted() {return;}- let image3_reg = if slot < 4 {- BP_TX_SETIMAGE3_I0 + slot- } else {- BP_TX_SETIMAGE3_I4 + (slot - 4)- };- let image3_val = self.bp_regs[image3_reg];+ let image3_val = self.bp_regs[self::tx_slot_reg(BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, slot)];self.snapshot_texture(renderer, ram, slot, image3_val);}@@ -489,6 +494,11 @@ impl GraphicsProcessor {dest_stride,src_h,});++ if let Some(rec) = self.recorder.as_deref_mut() {+ rec.note_xfb_copy();+ }+renderer.exec(GxAction::CopyXfb {id: dest_addr,src_x,@@ -515,6 +525,26 @@ impl GraphicsProcessor {let z_update = self.cur_zmode.update_enable();let depth_copy = self.cur_pe_control.pixel_format().is_depth_only();++ if let Some(rec) = self.recorder.as_deref_mut()+ && rec.is_recording()+ {+ let resolved = if depth_copy {+ texture::CopyFormat::from_u8_depth(copy_format)+ } else {+ texture::CopyFormat::from_u8_color(copy_format)+ };+ if let Some(fmt) = resolved {+ let (w, h) = if half { (src_w / 2, src_h / 2) } else { (src_w, src_h) };+ let row_bytes = texture::encoded_row_bytes(w, fmt);+ let row_count = texture::encoded_row_count(h, fmt);++ if row_count > 0 {+ let len = (row_count - 1) * dest_stride as usize + row_bytes;+ rec.note_efb_copy(dest_addr as u32, len);+ }+ }+ }renderer.exec(GxAction::CopyEfbToTexture {dest_addr,src_x,@@ -542,6 +572,14 @@ impl GraphicsProcessor {}}+ fn sync_recorder_efb_shadow(&mut self, ram: &RamViewMut<'_>) {+ if let Some(rec) = self.recorder.as_deref_mut()+ && rec.is_recording()+ {+ rec.flush_efb_shadow(&ram.as_view());+ }+ }+fn recompute_scissor(&mut self) {let tl = SuScisRect::from_raw(self.bp_regs[BP_SU_SCIS_TL]);let br = SuScisRect::from_raw(self.bp_regs[BP_SU_SCIS_BR]);@@ -579,6 +617,13 @@ impl GraphicsProcessor {}}+/// Texture slot to BP register index: slots 0-3 live at `base_i0`, slots 4-7+/// at `base_i4` (TX_SETMODE*/TX_SETIMAGE*/TX_SETTLUT all share this layout).+#[inline(always)]+fn tx_slot_reg(base_i0: usize, base_i4: usize, slot: usize) -> usize {+ if slot < 4 { base_i0 + slot } else { base_i4 + (slot - 4) }+}+fn slot_palette(palette_mem: &[u16], tmem_offset: u16) -> &[u16] {let base = (tmem_offset as usize) * TLUT_ENTRIES_PER_UNIT;palette_mem.get(base..).unwrap_or(&[])@@ -675,6 +720,12 @@ impl GraphicsProcessor {);return;};++ // FIFO recorder: capture the palette's source RAM so the replayed+ // LOADTLUT reads the same bytes.+ if let Some(rec) = self.recorder.as_deref_mut() {+ rec.use_memory(ram, ram_base as u32, byte_count, MemoryUpdateType::Tmem);+ }if dst_base.saturating_add(entries) > self.palette_mem.len() {tracing::warn!(dst_base,diff --git a/crates/gecko/src/flipper/gx/fifo.rs b/crates/gecko/src/flipper/gx/fifo.rsindex 9089d22..529f1e5 100644--- a/crates/gecko/src/flipper/gx/fifo.rs+++ b/crates/gecko/src/flipper/gx/fifo.rs@@ -34,6 +34,7 @@ fn drain_buf<const SYSTEM: SystemId>(}let cmd = fifo[pos];+ let cmd_start = pos;match cmd {NOP_CMD | INV_VTX_CACHE_CMD => {@@ -159,6 +160,12 @@ fn drain_buf<const SYSTEM: SystemId>(pos += 1;}}++ if let Some(rec) = gp.recorder.as_deref_mut()+ && cmd != CALL_DL_CMD+ {+ rec.record_command(&fifo[cmd_start..pos]);+ }}posdiff --git a/crates/gecko/src/flipper/gx/recorder.rs b/crates/gecko/src/flipper/gx/recorder.rsnew file mode 100644index 0000000..482aa8b--- /dev/null+++ b/crates/gecko/src/flipper/gx/recorder.rs@@ -0,0 +1,233 @@+use super::GraphicsProcessor;+use super::constants::{BP_REG_SIZE, CP_REG_SIZE};+use crate::mmio::RamView;+use crate::mmio::constants::MEM2_BASE;+pub use dff::MemoryUpdateType;+use dff::{DffFile, Frame, MemoryUpdate};++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum RecorderState {+ Waiting,+ Recording,+ Done,+}++pub struct FifoRecorder {+ state: RecorderState,+ frames_recorded: u32,+ file: DffFile,+ cur_frame: Frame,+ shadow_mem1: Vec<u8>,+ shadow_mem2: Vec<u8>,+ pending_efb_ranges: Vec<(u32, usize)>,+ seen_draw_textures: rustc_hash::FxHashSet<(u32, usize)>,+ xfb_copy_in_flight: bool,+ last_xfb_copy_end: Option<usize>,+ total_fifo_bytes: u64,+ total_update_bytes: u64,+}++impl FifoRecorder {+ pub fn new() -> Self {+ FifoRecorder {+ state: RecorderState::Waiting,+ frames_recorded: 0,+ file: DffFile::default(),+ cur_frame: Frame::default(),+ shadow_mem1: Vec::new(),+ shadow_mem2: Vec::new(),+ pending_efb_ranges: Vec::new(),+ seen_draw_textures: rustc_hash::FxHashSet::default(),+ xfb_copy_in_flight: false,+ last_xfb_copy_end: None,+ total_fifo_bytes: 0,+ total_update_bytes: 0,+ }+ }++ pub fn state(&self) -> RecorderState {+ self.state+ }++ pub fn frames_recorded(&self) -> u32 {+ self.frames_recorded+ }++ pub fn fifo_bytes(&self) -> u64 {+ self.total_fifo_bytes+ }++ pub fn update_bytes(&self) -> u64 {+ self.total_update_bytes+ }++ pub fn request_stop(&mut self) {+ self.state = RecorderState::Done;+ }++ pub fn into_file(self) -> DffFile {+ self.file+ }++ #[inline(always)]+ pub fn is_recording(&self) -> bool {+ self.state == RecorderState::Recording+ }++ #[inline]+ pub fn record_command(&mut self, bytes: &[u8]) {+ if self.is_recording() {+ self.cur_frame.fifo_data.extend_from_slice(bytes);+ self.total_fifo_bytes += bytes.len() as u64;++ if self.xfb_copy_in_flight {+ self.xfb_copy_in_flight = false;+ self.last_xfb_copy_end = Some(self.cur_frame.fifo_data.len());+ }+ }+ }++ pub fn note_xfb_copy(&mut self) {+ if self.is_recording() {+ self.xfb_copy_in_flight = true;+ }+ }++ pub fn use_memory(&mut self, ram: &RamView<'_>, addr: u32, len: usize, kind: MemoryUpdateType) {+ if !self.is_recording() || len == 0 {+ return;+ }++ let Some(cur) = ram.slice(addr as usize, len) else {+ return;+ };+ let Some(shadow) = self::shadow_range(&mut self.shadow_mem1, &mut self.shadow_mem2, ram, addr, len) else {+ return;+ };++ if shadow != cur {+ shadow.copy_from_slice(cur);++ self.total_update_bytes += len as u64;+ self.cur_frame.memory_updates.push(MemoryUpdate {+ fifo_position: self.cur_frame.fifo_data.len() as u32,+ address: addr,+ kind,+ data: cur.to_vec(),+ });+ }+ }++ pub fn use_draw_texture(&mut self, ram: &RamView<'_>, addr: u32, len: usize) {+ if !self.is_recording() || !self.seen_draw_textures.insert((addr, len)) {+ return;+ }+ self.use_memory(ram, addr, len, MemoryUpdateType::TextureMap);+ }++ pub fn note_efb_copy(&mut self, addr: u32, len: usize) {+ if self.is_recording() && len != 0 {+ self.pending_efb_ranges.push((addr, len));+ }+ }++ pub fn flush_efb_shadow(&mut self, ram: &RamView<'_>) {+ while let Some((addr, len)) = self.pending_efb_ranges.pop() {+ let Some(cur) = ram.slice(addr as usize, len) else {+ continue;+ };++ if let Some(shadow) = self::shadow_range(&mut self.shadow_mem1, &mut self.shadow_mem2, ram, addr, len) {+ shadow.copy_from_slice(cur);+ }+ }+ }++ pub fn on_frame_boundary(&mut self, gp: &GraphicsProcessor, fifo_start: u32, fifo_end: u32, is_wii: bool) {+ match self.state {+ RecorderState::Waiting => {+ self.snapshot_state(gp, is_wii);+ self.state = RecorderState::Recording;+ }+ RecorderState::Recording => {+ let Some(end) = self.last_xfb_copy_end.take() else {+ return;+ };+ self.seen_draw_textures.clear();++ let mut frame = std::mem::take(&mut self.cur_frame);+ let tail_data = frame.fifo_data.split_off(end);+ let split = frame+ .memory_updates+ .partition_point(|u| (u.fifo_position as usize) < end);+ let tail_updates = frame+ .memory_updates+ .split_off(split)+ .into_iter()+ .map(|mut u| {+ u.fifo_position -= end as u32;+ u+ })+ .collect();+ self.cur_frame = Frame {+ fifo_data: tail_data,+ fifo_start: 0,+ fifo_end: 0,+ memory_updates: tail_updates,+ };++ frame.fifo_start = fifo_start;+ frame.fifo_end = fifo_end;++ self.file.frames.push(frame);+ self.frames_recorded += 1;+ }+ RecorderState::Done => {}+ }+ }++ fn snapshot_state(&mut self, gp: &GraphicsProcessor, is_wii: bool) {+ self.file.is_wii = is_wii;+ self.file.bp_mem[..BP_REG_SIZE].copy_from_slice(&gp.bp_regs[..BP_REG_SIZE]);+ self.file.cp_mem[..CP_REG_SIZE].copy_from_slice(&gp.cp_regs[..CP_REG_SIZE]);+ self.file.xf_mem.copy_from_slice(&gp.xf_mem[..dff::XF_MEM_SIZE]);+ let regs = &gp.xf_mem[dff::XF_MEM_SIZE..dff::XF_MEM_SIZE + dff::XF_REGS_SIZE];+ self.file.xf_regs.copy_from_slice(regs);++ for (i, entry) in gp.palette_mem.iter().enumerate() {+ let off = i * 2;+ if off + 2 > self.file.tex_mem.len() {+ break;+ }++ self.file.tex_mem[off..off + 2].copy_from_slice(&entry.to_be_bytes());+ }+ }+}++fn shadow_range<'a>(+ shadow_mem1: &'a mut Vec<u8>,+ shadow_mem2: &'a mut Vec<u8>,+ ram: &RamView<'_>,+ addr: u32,+ len: usize,+) -> Option<&'a mut [u8]> {+ let addr = addr as usize;++ if addr < ram.mem1.len() {+ if shadow_mem1.len() != ram.mem1.len() {+ shadow_mem1.resize(ram.mem1.len(), 0);+ }++ shadow_mem1.get_mut(addr..addr + len)+ } else if addr >= MEM2_BASE as usize {+ if shadow_mem2.len() != ram.mem2.len() {+ shadow_mem2.resize(ram.mem2.len(), 0);+ }++ let off = addr - MEM2_BASE as usize;+ shadow_mem2.get_mut(off..off + len)+ } else {+ None+ }+}diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rsindex 78af7a5..aa2ea5e 100644--- a/crates/gecko/src/flipper/gx/vertex.rs+++ b/crates/gecko/src/flipper/gx/vertex.rs@@ -69,6 +69,17 @@ impl GraphicsProcessor {let vertex_count = data.len() / vf.vertex_stride;+ if let Some(rec) = self.recorder.as_deref_mut()+ && rec.is_recording()+ {+ let view = mmio.ram_view();+ self::record_draw_arrays(rec, &view, &vf, data, vertex_count);+ for desc in self.cur_textures.iter().flatten() {+ let len = super::texture::raw_data_size(desc.width, desc.height, desc.format);+ rec.use_draw_texture(&view, desc.ram_addr as u32, len);+ }+ }+#[cfg(feature = "gx-stats")]{self.stats.draw_calls += 1;@@ -570,6 +581,115 @@ impl GraphicsProcessor {}}+fn record_draw_arrays(+ rec: &mut super::recorder::FifoRecorder,+ ram: &RamView<'_>,+ vf: &VertexFormat,+ data: &[u8],+ vertex_count: usize,+) {+ let attr_stream_size = |attr: AttributeType, direct_size: usize| -> usize {+ match attr {+ AttributeType::Direct => direct_size,+ AttributeType::Index8 => 1,+ AttributeType::Index16 => 2,+ AttributeType::None => 0,+ }+ };++ let mut offset = 0usize;+ offset += vf.has_pnmtxidx as usize;+ for has in vf.has_tex_mtx_idx {+ offset += has as usize;+ }++ let mut scan = |offset: usize, attr: AttributeType, base: usize, stride: usize, data_size: usize| {+ self::scan_indexed_component(+ rec,+ ram,+ data,+ vf.vertex_stride,+ vertex_count,+ offset,+ attr,+ base,+ stride,+ data_size,+ );+ };++ scan(offset, vf.pos_attr, vf.pos_base, vf.pos_stride, vf.pos_data_size);+ offset += attr_stream_size(vf.pos_attr, vf.pos_data_size);++ scan(offset, vf.nrm_attr, vf.nrm_base_addr, vf.nrm_stride, vf.nrm_data_size);+ offset += vf.vat_a.nrm_stream_size(vf.nrm_attr);++ scan(offset, vf.clr0_attr, vf.clr0_base, vf.clr0_stride, vf.clr0_data_size);+ offset += attr_stream_size(vf.clr0_attr, vf.clr0_data_size);++ scan(offset, vf.clr1_attr, vf.clr1_base, vf.clr1_stride, vf.clr1_data_size);+ offset += attr_stream_size(vf.clr1_attr, vf.clr1_data_size);++ for tc in 0..8 {+ scan(+ offset,+ vf.tex_attrs[tc],+ vf.tex_bases[tc],+ vf.tex_strides[tc],+ vf.tex_data_sizes[tc],+ );+ offset += attr_stream_size(vf.tex_attrs[tc], vf.tex_data_sizes[tc]);+ }+}++#[allow(clippy::too_many_arguments)]+fn scan_indexed_component(+ rec: &mut super::recorder::FifoRecorder,+ ram: &RamView<'_>,+ data: &[u8],+ vertex_stride: usize,+ vertex_count: usize,+ offset: usize,+ attr: AttributeType,+ base: usize,+ stride: usize,+ data_size: usize,+) {+ let idx_size = match attr {+ AttributeType::Index8 => 1,+ AttributeType::Index16 => 2,+ _ => return,+ };++ // All-ones indices skip the vertex on real hardware.+ let mut max_index: Option<usize> = None;+ for v in 0..vertex_count {+ let p = v * vertex_stride + offset;+ if p + idx_size > data.len() {+ break;+ }+ let index = if idx_size == 1 {+ match data[p] {+ 0xFF => continue,+ i => i as usize,+ }+ } else {+ match u16::from_be_bytes([data[p], data[p + 1]]) {+ 0xFFFF => continue,+ i => i as usize,+ }+ };+ if max_index.is_none_or(|m| index > m) {+ max_index = Some(index);+ }+ }++ if let Some(max) = max_index {+ let len = stride * max + data_size;+ rec.use_memory(ram, base as u32, len, super::recorder::MemoryUpdateType::VertexStream);+ }+}+fn read_index(cur: &mut Cursor<&[u8]>, attr: AttributeType) -> usize {match attr {AttributeType::Index8 => {diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rsindex 7448a86..b3783b6 100644--- a/crates/gecko/src/flipper/gx/xf.rs+++ b/crates/gecko/src/flipper/gx/xf.rs@@ -176,6 +176,11 @@ impl GraphicsProcessor {);return;};++ if let Some(rec) = self.recorder.as_deref_mut() {+ rec.use_memory(ram, src_addr as u32, n * 4, super::recorder::MemoryUpdateType::XfData);+ }+for i in 0..n {let off = i * 4;let val = u32::from_be_bytes([src[off], src[off + 1], src[off + 2], src[off + 3]]);diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex 2ca2f99..ee11c9e 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -170,22 +170,11 @@ struct Args {/// Force interpreter dispatch for CPU/DSP/Vertex (default: JIT)#[arg(long)]interpreter: bool,-}-fn resolve_aspect(arg: &str, system: SystemId) -> TargetAspect {- match arg {- "auto" => {- if system == system::WII {- TargetAspect::Ratio(16.0 / 9.0)- } else {- TargetAspect::Ratio(4.0 / 3.0)- }- }- "4:3" => TargetAspect::Ratio(4.0 / 3.0),- "16:9" => TargetAspect::Ratio(16.0 / 9.0),- "stretch" => TargetAspect::Stretch,- other => panic!("--aspect must be auto|4:3|16:9|stretch, got {other:?}"),- }+ /// Record a Dolphin-compatible .dff FIFO dump to this path, from the+ /// first presented frame until the app exits+ #[arg(long)]+ fifo_record: Option<String>,}fn main() {@@ -327,7 +316,7 @@ fn run<const SYSTEM: SystemId>(args: &Args,game_id: Option<String>,) {- let target_aspect = resolve_aspect(&args.aspect, SYSTEM);+ let target_aspect = TargetAspect::from_arg(&args.aspect, SYSTEM == system::WII);let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {backends: wgpu::Backends::all(),..wgpu::InstanceDescriptor::new_without_display_handle()@@ -414,11 +403,20 @@ fn run<const SYSTEM: SystemId>(let start_gate = Arc::new(AtomicBool::new(!args.wait));let emu_start_gate = start_gate.clone();let emu_shutdown = shutdown_requested.clone();+ let fifo_record = args.fifo_record.clone();drop(proxy);let emu_handle = std::thread::Builder::new().name("emu".into()).spawn(move || {- thread::emu_thread::<SYSTEM>(emulator, emu_input, game_id, throttle, emu_start_gate, emu_shutdown)+ thread::emu_thread::<SYSTEM>(+ emulator,+ emu_input,+ game_id,+ throttle,+ emu_start_gate,+ emu_shutdown,+ fifo_record,+ )}).expect("failed to spawn emulator thread");diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rsindex 7b73f49..3b69e3e 100644--- a/crates/tinyapp/src/thread.rs+++ b/crates/tinyapp/src/thread.rs@@ -1,4 +1,5 @@use gecko::HostInput;+use gecko::flipper::gx::recorder::FifoRecorder;use gecko::system::{System, SystemId};use spin_sleep::SpinSleeper;use std::sync::atomic::{AtomicBool, Ordering};@@ -12,6 +13,7 @@ pub fn emu_thread<const SYSTEM: SystemId>(throttle: bool,start_gate: Arc<AtomicBool>,shutdown: Arc<AtomicBool>,+ fifo_record: Option<String>,) {let sleeper = SpinSleeper::default();let throttle_step = Duration::from_micros(5);@@ -23,6 +25,11 @@ pub fn emu_thread<const SYSTEM: SystemId>(sleeper.sleep(Duration::from_millis(10));}+ if fifo_record.is_some() {+ tracing::info!("FIFO recorder started, recording until shutdown");+ emulator.gx.recorder = Some(Box::new(FifoRecorder::new()));+ }+while !shutdown.load(Ordering::Relaxed) {while throttle && emulator.audio_sink.should_throttle() {if shutdown.load(Ordering::Relaxed) {@@ -36,6 +43,21 @@ pub fn emu_thread<const SYSTEM: SystemId>(emulator.run_until_vsync();}+ if let Some(path) = fifo_record+ && let Some(rec) = emulator.gx.recorder.take()+ {+ let file = rec.into_file();+ let frame_count = file.frames.len();+ if frame_count == 0 {+ tracing::warn!("nothing to save");+ } else {+ match file.save(std::path::Path::new(&path)) {+ Ok(()) => tracing::info!(frames = frame_count, path = path.as_str(), "FIFO dump saved"),+ Err(err) => tracing::error!(%err, "FIFO dump save failed"),+ }+ }+ }+if let Some(game_id) = game_id.as_deref() {match emulator.save_jit_cache(game_id) {Ok((ppc, dsp, vtx)) => {