// SPDX-License-Identifier: MIT //! The lockstep gate's Rust side: this board, traced slice by slice (`scripts/a5200_trace.py` //! writes the same lines from the reference; `scripts/lockstep.py` compares them). //! //! a5200-trace ROM --slices N [--machine KEY] [--mapping M] [--plug N] //! [--press FRAME:KEY:FRAMES[:PORT]]... [--stick FRAME:X:Y[:PORT]]... //! [--trak FRAME:VX:VY[:PORT]]... [--audio] [--detail SLICE] //! [--save-at SLICE] [--save-mid SLICE:WHERE]... [--bios FILE] //! [--ram ADDR:FILE]... --out FILE //! //! A slice is one frame: `Console::run_frames(1)` (the controllers' `frame()`, then the board //! up to ANTIC's line 0, cycle 0). The inputs follow the reference's `scripts/scripted_run.py` //! exactly, with frame numbers counted from 1 (slice i is frame i + 1): before each frame every //! pad's keys, trigger and upper button become the presses active in it, and sticks and //! trak-balls change at their frame. Each line: the CPU's registers, board time and frame //! count, ANTIC's position, the board's counters, a CRC-32 of every bus cycle of the slice //! (packed little-endian u64 `cycle << 27 | kind << 24 | address << 8 | value`; kind 0 CPU //! read, 1 CPU write, 2 ANTIC DMA, 3 WSYNC-repeated read, 4 refresh with address 0), and a //! CRC-32 of the frame buffer. `--audio`: a `media::AudioTap` is attached and each line ends //! with `snd=CRC/COUNT` of the slice's samples. `--save-at K`: before slice K the console's //! state is saved, loaded into a fresh console, and the run goes on there (the reference //! ignores it: its trace runs uninterrupted). `--save-mid K:WHERE` (repeatable): the same round //! trip inside a frame, at the save points of a5200-python's tests/test_state.py (cf82d44): //! WHERE is a cycle count past slice K's frame boundary (`cycle-N`, 0 = at the boundary, after //! the frame's inputs were applied), or the first instruction boundary from slice K on at which //! a condition holds: `wsync-pending` (ANTIC's WSYNC stall armed), `irq-edge-unsynced` (POKEY's //! /IRQ has changed but the CPU's line has not yet followed), `irq-held` (/IRQ low with the I //! flag set), `nmi-pending` (the CPU holds an NMI not yet taken). A point never reached is an //! error. The bus log, the slice's line and the audio tap carry across the round trip, so the //! lines must equal the reference's uninterrupted ones. `--bios FILE` and `--ram ADDR:FILE` //! (hex address) build the synthetic case of the reference's tests/test_state.py //! (`scripts/busy_case.py`), as `scripts/a5200_trace.py` does. use std::cell::RefCell; use std::io::Write; use std::path::PathBuf; use std::rc::Rc; use a5200::antic::ANTIC; use a5200::board::Running; use a5200::cartridge::{load_cartridge, Cart, Source}; use a5200::media::AudioTap; use a5200::state; use a5200::{machine_by_name, Console}; struct Press { frame: u64, key: String, length: u64, port: usize, } struct Change { frame: u64, a: f64, b: f64, port: usize, } fn port_of(rest: &[&str]) -> usize { rest.first() .map(|p| p.parse::().unwrap() - 1) .unwrap_or(0) } fn parse_change(item: &str) -> Change { let parts: Vec<&str> = item.split(':').collect(); Change { frame: parts[0].parse().unwrap(), a: parts[1].parse().unwrap(), b: parts[2].parse().unwrap(), port: port_of(&parts[3..]), } } fn attach(console: &mut Console, log: &Rc>>) { let sink = Rc::clone(log); console.board_mut().bus_observers.push(Box::new( move |kind: char, address: i32, value: u8, cycle: u64, _antic: &ANTIC| { let (code, address) = match kind { 'R' => (0u64, address), 'W' => (1, address), 'D' if address < 0 => (4, 0), 'D' => (2, address), _ => (3, address), }; sink.borrow_mut() .push(cycle << 27 | code << 24 | (address as u64 & 0xFFFF) << 8 | value as u64); }, )); } /// A save point inside a frame (`--save-mid`). enum Where { Cycles(u64), When(fn(&a5200::Cpu) -> bool), } fn parse_where(text: &str) -> Where { if let Some(n) = text.strip_prefix("cycle-") { return Where::Cycles(n.parse().expect("cycle-N")); } Where::When(match text { "wsync-pending" => |cpu| cpu.bus.antic.wsync_at >= 0, "irq-edge-unsynced" => |cpu| cpu.bus._irq_next != cpu.bus._irq_line, "irq-held" => |cpu| cpu.bus._irq_line && cpu.p & 0x04 != 0, "nmi-pending" => |cpu| Running::capture_state(cpu).non_maskable_interrupt_pending, _ => panic!("unknown save point {text}"), }) } /// Save the console's state, load it into a fresh console (through bytes), move the audio tap /// and the bus log across, and go on there. fn round_trip( console: &mut Console, cart: &Cart, bios: &Option>, log: &Rc>>, ) { let machine = console.machine; let saved = state::to_bytes(&state::snapshot(console)); let audio_tap = console.board_mut().audio.take(); let mut fresh = Console::new(cart.clone(), machine, bios.clone(), None).unwrap(); state::restore(&mut fresh, &state::from_bytes(&saved).unwrap()).unwrap(); fresh.board_mut().audio = audio_tap; attach(&mut fresh, log); *console = fresh; } fn main() { let args: Vec = std::env::args().skip(1).collect(); let mut rom: Option = None; let mut slices = 0u64; let mut machine = "a5200".to_string(); let mut mapping: Option = None; let mut plug = 2usize; let mut presses = Vec::new(); let mut sticks = Vec::new(); let mut traks = Vec::new(); let mut audio = false; let mut detail: i64 = -1; let mut save_at: i64 = -1; let mut save_mid: Vec<(u64, Where)> = Vec::new(); let mut bios: Option> = None; let mut ram: Vec<(usize, Vec)> = Vec::new(); let mut out: Option = None; let mut i = 0; while i < args.len() { let a = args[i].as_str(); let mut value = || { i += 1; args[i].clone() }; match a { "--slices" => slices = value().parse().unwrap(), "--machine" => machine = value(), "--mapping" => mapping = Some(value()), "--plug" => plug = value().parse().unwrap(), "--press" => { let item = value(); let parts: Vec<&str> = item.split(':').collect(); presses.push(Press { frame: parts[0].parse().unwrap(), key: parts[1].to_string(), length: parts[2].parse().unwrap(), port: port_of(&parts[3..]), }); } "--stick" => sticks.push(parse_change(&value())), "--trak" => traks.push(parse_change(&value())), "--audio" => audio = true, "--detail" => detail = value().parse().unwrap(), "--save-at" => save_at = value().parse().unwrap(), "--bios" => bios = Some(std::fs::read(value()).expect("--bios FILE")), "--ram" => { let item = value(); let (address, path) = item.split_once(':').expect("--ram ADDR:FILE"); let address = usize::from_str_radix(address, 16).unwrap(); ram.push((address, std::fs::read(path).expect("--ram ADDR:FILE"))); } "--save-mid" => { let item = value(); let (slice, at) = item.split_once(':').expect("--save-mid K:WHERE"); save_mid.push((slice.parse().unwrap(), parse_where(at))); } "--out" => out = Some(PathBuf::from(value())), _ if a.starts_with("--") => panic!("unknown option {a}"), _ => rom = Some(PathBuf::from(a)), } i += 1; } let rom = rom.expect("a cartridge"); let out = out.expect("--out"); let machine = machine_by_name(&machine).expect("a machine row"); let cart = load_cartridge(Source::Path(&rom), mapping.as_deref(), None).unwrap_or_else(|e| { eprintln!("{e}"); std::process::exit(2) }); let mut console = Console::new(cart.clone(), machine, bios.clone(), None).unwrap_or_else(|e| { eprintln!("{e}"); std::process::exit(2) }); for (address, data) in &ram { console.board_mut().ram[*address..*address + data.len()].copy_from_slice(data); } if audio { console.board_mut().audio = Some(AudioTap::new(machine.cycle_hz(), 44100, 8)); } let log: Rc>> = Rc::default(); attach(&mut console, &log); { let mut pads = console.controllers.pads.borrow_mut(); let n = plug.min(pads.len()); for pad in pads.iter_mut().take(n) { pad.plugged = true; } } let mut file = std::io::BufWriter::new(std::fs::File::create(&out).unwrap()); for index in 0..slices { if index as i64 == save_at { round_trip(&mut console, &cart, &bios, &log); } let frame = index + 1; { let mut pads = console.controllers.pads.borrow_mut(); for (port, pad) in pads.iter_mut().enumerate() { let mine: Vec<&Press> = presses .iter() .filter(|p| p.port == port && p.frame <= frame && frame < p.frame + p.length) .collect(); pad.keys = mine .iter() .filter(|p| p.key != "trigger" && p.key != "top") .map(|p| p.key.clone()) .collect(); pad.trigger = mine.iter().any(|p| p.key == "trigger"); pad.top = mine.iter().any(|p| p.key == "top"); } let count = pads.len(); for s in &sticks { if s.frame == frame && s.port < count { pads[s.port].x = s.a; pads[s.port].y = s.b; } } for t in &traks { if t.frame == frame && t.port < count { pads[t.port].trakball = true; pads[t.port].vx = t.a; pads[t.port].vy = t.b; } } } // `console.run_frames(1)`, stepped by hand so a save can fall inside the frame. console.controllers.frame(&mut console.cpu.bus); let start = console.board().cycles; let target = console.board().frames + 1; let mut first = true; loop { // The earliest pending save point of this slice or an earlier one. let due = save_mid.iter().position(|(slice, at)| { *slice <= index && match at { Where::Cycles(n) => console.board().cycles >= start + n, Where::When(cond) => !first && cond(&console.cpu), } }); if let Some(k) = due { save_mid.remove(k); round_trip(&mut console, &cart, &bios, &log); continue; } if console.board().frames >= target { break; } console.cpu.step(); first = false; } let records = std::mem::take(&mut *log.borrow_mut()); let mut bytes = Vec::with_capacity(records.len() * 8); for r in &records { bytes.extend_from_slice(&r.to_le_bytes()); } let bus = if records.is_empty() { 0 } else { crc32fast::hash(&bytes) }; let cpu = &console.cpu; let board = &cpu.bus; let pic = crc32fast::hash(&board.frame); write!( file, "{index} cyc={} fr={} pc={:04x} a={:02x} x={:02x} y={:02x} s={:02x} p={:02x} \ jam={} v={} h={} halt={} stall={} lost={} db={:02x} irq={} bus={bus:08x}/{} pic={pic:08x}", board.cycles, board.frames, cpu.pc, cpu.a, cpu.x, cpu.y, cpu.s, cpu.p, cpu.halted() as u8, board.antic.vcount, board.antic.hcount, board.halted_cycles, board.stalled_cycles, board.nmis_lost, board.data_bus, board._irq_line as u8, records.len(), ) .unwrap(); if audio { let samples = std::mem::take(&mut console.board_mut().audio.as_mut().unwrap().samples); write!( file, " snd={:08x}/{}", crc32fast::hash(&samples), samples.len() / 2 ) .unwrap(); } writeln!(file).unwrap(); if index as i64 == detail { for r in &records { let kind = ["r", "w", "d", "s", "f"][((r >> 24) & 7) as usize]; writeln!( file, " {} {kind} {:04x} {:02x}", r >> 27, (r >> 8) & 0xFFFF, r & 0xFF ) .unwrap(); } } } file.flush().unwrap(); }