// SPDX-License-Identifier: MIT //! One cart of a library sweep (`scripts/sweep.py` runs it over the sets): boot through //! the real boot ROM, run a fixed number of 266,667-tick slices (1/60 s, the lockstep //! gate's slice, so a suspect can be rerun on both boards with `scripts/lockstep.py` and //! the same input file), and print one JSON line describing what happened. //! //! lynx-sweep CART --slices N [--input FILE] [--machine lynx1|lynx2] //! [--png-at SLICE:FILE ...] //! //! A host tool, not part of the transcription: it only reads the board's state between //! slices (picture, frame counter, CPU registers) and never changes behaviour. //! //! Recorded: whether the cart loaded (and the loader's message if not), what the loader //! decided (kind, boot path, block size, rotation, EEPROM), whether the board booted; per //! slice the CRC-32 of the finished picture (the frame buffer) and whether it is blank //! (fewer than two colours, or one colour on 99.5 % of the pixels or more); from those //! the first non-blank slice, the first slice of a held picture (unchanged and non-blank //! for 60 slices), the slice from which the picture stays non-blank to the end, the //! number of distinct pictures and the last slice the picture changed; at the end the //! picture CRC, the display frame count and period, the CPU registers, and over the last //! 300 slices the distinct slice-end PCs and how many display frames were finished. //! A Rust panic inside the board is caught and reported. use std::collections::{BTreeMap, HashSet}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::PathBuf; use serde_json::{json, Value}; use lynx::cart::load_path; use lynx::picture::save; use lynx::run::boot; use lynx::{machine_named, Lynx}; const SLICE_TICKS: i64 = 266_667; const HOLD: usize = 60; const TAIL: usize = 300; fn button(name: &str) -> u8 { match name { "up" => 0x80, "down" => 0x40, "left" => 0x20, "right" => 0x10, "opt1" => 0x08, "opt2" => 0x04, "b" => 0x02, "a" => 0x01, _ => panic!("unknown button {name}"), } } /// The input file format of `lynx-trace` (slice, then the buttons held from it on). fn read_inputs(path: &Option) -> BTreeMap> { let mut out = BTreeMap::new(); if let Some(path) = path { let text = std::fs::read_to_string(path).expect("input file"); for line in text.lines() { let words: Vec<&str> = line.split('#').next().unwrap().split_whitespace().collect(); if let Some((first, rest)) = words.split_first() { out.insert( first.parse().expect("slice"), rest.iter() .filter(|w| **w != "-") .map(|w| w.to_string()) .collect(), ); } } } out } /// Blank: fewer than two colours, or one colour covering 99.5 % of the pixels or more. fn blank(rgb: &[u8]) -> (bool, usize) { let mut counts: BTreeMap<[u8; 3], usize> = BTreeMap::new(); for p in rgb.chunks_exact(3) { *counts.entry([p[0], p[1], p[2]]).or_default() += 1; } let pixels = rgb.len() / 3; let top = counts.values().copied().max().unwrap_or(0); (counts.len() < 2 || top * 1000 >= pixels * 995, counts.len()) } fn main() { let mut args = std::env::args().skip(1); let mut cart: Option = None; let mut slices = 0usize; let mut machine = "lynx2".to_string(); let mut input: Option = None; let mut pngs: BTreeMap = BTreeMap::new(); while let Some(a) = args.next() { match a.as_str() { "--slices" => slices = args.next().unwrap().parse().unwrap(), "--machine" => machine = args.next().unwrap(), "--input" => input = Some(args.next().unwrap().into()), "--png-at" => { let v = args.next().unwrap(); let (s, f) = v.split_once(':').expect("--png-at SLICE:FILE"); pngs.insert(s.parse().unwrap(), f.into()); } _ if cart.is_none() && !a.starts_with("--") => cart = Some(a.into()), _ => panic!("unknown argument {a}"), } } let cart = cart.expect("a cart"); let mut report = serde_json::Map::new(); report.insert( "file".into(), json!(cart.file_name().unwrap().to_string_lossy()), ); let finish = |report: serde_json::Map| { println!("{}", Value::Object(report)); }; let description = match load_path(&cart, None) { Ok(d) => d, Err(e) => { report.insert("loaded".into(), json!(false)); report.insert("load_error".into(), json!(e.to_string())); return finish(report); } }; report.insert("loaded".into(), json!(true)); report.insert("kind".into(), json!(description.kind)); report.insert("boot".into(), json!(description.boot)); report.insert("bank0_block".into(), json!(description.bank0_block)); report.insert("bank1_block".into(), json!(description.bank1_block)); report.insert("rotation".into(), json!(description.rotation)); report.insert( "eeprom".into(), json!(description.eeprom.as_ref().map(|(t, o)| format!("{t}:{o}"))), ); report.insert("crc32".into(), json!(description.crc32)); report.insert("payload_bytes".into(), json!(description.payload.len())); report.insert("warnings".into(), json!(description.warnings)); let machine = machine_named(&machine).expect("a machine row"); let mut board: Lynx = match catch_unwind(AssertUnwindSafe(|| boot(&description, machine))) { Ok(Ok(b)) => b, Ok(Err(e)) => { report.insert("boot_error".into(), json!(e)); return finish(report); } Err(_) => { report.insert("boot_error".into(), json!("panic while booting")); return finish(report); } }; let inputs = read_inputs(&input); let mut pics: Vec = Vec::with_capacity(slices); let mut blanks: Vec = Vec::with_capacity(slices); let mut tail_pcs: HashSet = HashSet::new(); let mut tail_frames_from = 0u64; let mut panicked: Option = None; let mut colours_at_end = 0usize; for index in 0..slices { if let Some(names) = inputs.get(&index) { let mut keys = 0u8; for name in names { if name != "pause" { keys |= button(name); } } let suzy = &mut board.hw_mut().suzy; suzy.joystick = keys; suzy.switches = (suzy.switches & !1) | names.iter().any(|n| n == "pause") as u8; } let end = (index as i64 + 1) * SLICE_TICKS; let ran = catch_unwind(AssertUnwindSafe(|| { while board.tick() < end { board.step(); } })); if let Err(e) = ran { let message = e .downcast_ref::() .cloned() .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())) .unwrap_or_else(|| "panic".into()); panicked = Some(format!("slice {index}: {message}")); break; } let display = &board.hw().mikey.display; pics.push(crc32fast::hash(&display.frame)); let rgb = display.rgb(); let (b, colours) = blank(&rgb); blanks.push(b); colours_at_end = colours; if index + TAIL == slices { tail_frames_from = display.frames; } if index + TAIL >= slices { tail_pcs.insert(board.cpu.pc); } if let Some(path) = pngs.get(&(index + 1)) { save(path, &rgb, &description.rotation).expect("write the PNG"); } } let run = pics.len(); let first_nonblank = blanks.iter().position(|b| !b); let mut first_held = None; let mut streak = 0usize; for i in 0..run { if !blanks[i] && i > 0 && pics[i] == pics[i - 1] { streak += 1; } else { streak = if blanks[i] { 0 } else { 1 }; } if streak >= HOLD && first_held.is_none() { first_held = Some(i + 1 - HOLD); } } let nonblank_from = if run > 0 && !blanks[run - 1] { Some(blanks.iter().rposition(|b| *b).map_or(0, |i| i + 1)) } else { None }; let distinct: HashSet = pics.iter().copied().collect(); let last_change = (1..run).rev().find(|&i| pics[i] != pics[i - 1]); let hw = board.hw(); let cpu = &board.cpu; report.insert("booted".into(), json!(true)); report.insert("slices".into(), json!(run)); report.insert("panic".into(), json!(panicked)); report.insert("first_nonblank".into(), json!(first_nonblank)); report.insert("first_held".into(), json!(first_held)); report.insert("nonblank_from".into(), json!(nonblank_from)); report.insert( "blank_slices".into(), json!(blanks.iter().filter(|b| **b).count()), ); report.insert("distinct_pictures".into(), json!(distinct.len())); report.insert("last_change".into(), json!(last_change)); report.insert("final_blank".into(), json!(blanks.last().copied())); report.insert("final_colours".into(), json!(colours_at_end)); report.insert( "final_pic".into(), json!(pics.last().map(|p| format!("{p:08x}"))), ); report.insert("frames".into(), json!(hw.mikey.display.frames)); report.insert("frame_period".into(), json!(hw.mikey.display.frame_period)); report.insert( "tail_frames".into(), json!(hw.mikey.display.frames.saturating_sub(tail_frames_from)), ); let mut pcs: Vec = tail_pcs.into_iter().collect(); pcs.sort(); report.insert("tail_distinct_pcs".into(), json!(pcs.len())); report.insert( "tail_pcs".into(), json!(pcs .iter() .take(8) .map(|p| format!("{p:04x}")) .collect::>()), ); report.insert( "cpu".into(), json!(format!( "pc={:04x} a={:02x} x={:02x} y={:02x} s={:02x} p={:02x} stopped={} waiting={}", cpu.pc, cpu.a, cpu.x, cpu.y, cpu.s, cpu.p, cpu.stopped, cpu.waiting )), ); report.insert( "ram_crc".into(), json!(format!("{:08x}", crc32fast::hash(&hw.ram))), ); finish(report); }