pcenginecd_rust/
trace.rs

1//! The lockstep gate's side of this crate: how a traced CD machine is built from a command
2//! line, and a frame's line.
3//!
4//! Not a module of the reference: its counterpart is `scripts/pcecd_trace.py`, which builds
5//! the reference's `PcEngineCd` from the same arguments. A line is the base gate's
6//! (`pcengine_rust::trace::frame_line`: the CPU bus log, the picture, the mixed audio and the
7//! CPU state, digested) plus `cmd=N:SHA1`, the drive's command log of the frame. `roundtrip`
8//! and `runahead` are the base crate's save-state checks over this machine (theirs build a
9//! plain board).
10
11use pcengine_rust::machine::{PC_ENGINE, TURBOGRAFX_16};
12use pcengine_rust::pads::{self, Pad2};
13use pcengine_rust::sockets::ResetKind;
14use pcengine_rust::system::System;
15use pcengine_rust::trace::{held, parse_press, Press};
16use sha1::{Digest, Sha1};
17
18use crate::board::{unit, CdSwitches, PcEngineCd};
19use crate::disc::Disc;
20
21/// The command line shared by `pcecd-trace`, `pcecd-state-roundtrip`, `pcecd-bench` and
22/// `scripts/pcecd_trace.py`.
23#[derive(Clone, Debug)]
24pub struct Setup {
25    /// the System Card image, or a card of our own
26    pub card: Vec<u8>,
27    /// a `.cue` (the disc is opened again for every machine built)
28    pub disc: Option<String>,
29    pub arcade: bool,
30    pub frames: i64,
31    pub presses: Vec<Press>,
32    pub machine: String,
33    pub super_system_card: Option<bool>,
34    pub region_us: bool,
35    pub bram: Option<Vec<u8>>,
36    pub switches: CdSwitches,
37    /// `Board::reset` of this kind before the frame with this count of completed frames
38    pub resets: Vec<(i64, ResetKind)>,
39    pub detail: Option<i64>,
40    pub out: Option<String>,
41    /// Arguments this parser does not know (a binary's own).
42    pub rest: Vec<String>,
43}
44
45fn integer(text: &str) -> Result<i64, String> {
46    let parsed = match text.strip_prefix("0x") {
47        Some(hex) => i64::from_str_radix(hex, 16),
48        None => text.parse(),
49    };
50    parsed.map_err(|_| format!("not a number: {text}"))
51}
52
53fn real(text: &str) -> Result<f64, String> {
54    text.parse().map_err(|_| format!("not a number: {text}"))
55}
56
57fn flag(text: &str) -> bool {
58    matches!(text.to_lowercase().as_str(), "true" | "1")
59}
60
61fn list<const N: usize>(text: &str) -> Result<[i64; N], String> {
62    let values: Vec<i64> = text.split(',').map(integer).collect::<Result<_, _>>()?;
63    values
64        .try_into()
65        .map_err(|_| format!("{N} numbers, not {text}"))
66}
67
68/// One named switch by the reference's spelling, `WHERE.NAME=VALUE` (`scsi.SEEK_SCALE=2.0`).
69pub fn set_switch(switches: &mut CdSwitches, spec: &str) -> Result<(), String> {
70    let (target, text) = spec
71        .split_once('=')
72        .ok_or_else(|| format!("--switch WHERE.NAME=VALUE, not {spec}"))?;
73    let s = switches;
74    match target {
75        "scsi.SEL_TO_COMMAND_PHASE" => s.scsi.sel_to_command_phase = integer(text)?,
76        "scsi.NEXT_COMMAND_BYTE_REQ" => s.scsi.next_command_byte_req = integer(text)?,
77        "scsi.TEST_UNIT_READY" => s.scsi.test_unit_ready = integer(text)?,
78        "scsi.TOC_ANSWER" => s.scsi.toc_answer = integer(text)?,
79        "scsi.SUBQ_ANSWER" => s.scsi.subq_answer = integer(text)?,
80        "scsi.DONE_STATUS" => s.scsi.done_status = integer(text)?,
81        "scsi.ABORT_TO_COMMAND" => s.scsi.abort_to_command = integer(text)?,
82        "scsi.ACK_CLEAR" => s.scsi.ack_clear = integer(text)?,
83        "scsi.SECTOR_CLOCKS" => s.scsi.sector_clocks = integer(text)?,
84        "scsi.REREAD_PENALTY_MS" => s.scsi.reread_penalty_ms = integer(text)?,
85        "scsi.SEEK_SCALE" => s.scsi.seek_scale = real(text)?,
86        "scsi.TOC_ANSWER_BYTES" => s.scsi.toc_answer_bytes = list::<3>(text)?.map(|n| n as usize),
87        "unit.CHANNEL_LATCH_GUARD" => s.unit.channel_latch_guard = integer(text)?,
88        "unit.DMA_BYTE_CLOCKS" => s.unit.dma_byte_clocks = integer(text)?,
89        "cdda.FADE_SLOW_SECONDS" => s.fader.fade_slow_seconds = real(text)?,
90        "cdda.FADE_FAST_SECONDS" => s.fader.fade_fast_seconds = real(text)?,
91        "cdda.PCETECH_SLOW_SECONDS" => s.fader.pcetech_slow_seconds = real(text)?,
92        "cdda.PCETECH_FAST_SECONDS" => s.fader.pcetech_fast_seconds = real(text)?,
93        "cdda.PCETECH_FADE" => s.fader.pcetech_fade = flag(text),
94        "cdda.SUBQ_STATUS" => s.subq_status = Some(list::<4>(text)?.map(|n| n as u8)),
95        "adpcm.BASE_HZ" => s.adpcm.base_hz = real(text)?,
96        "adpcm.READ_CLOCKS" => s.adpcm.read_clocks = integer(text)?,
97        "adpcm.WRITE_CLOCKS" => s.adpcm.write_clocks = integer(text)?,
98        "adpcm.SATURATE" => s.adpcm.saturate = flag(text),
99        "adpcm.OUTPUT_SCALE" => s.adpcm.output_scale = integer(text)? as i32,
100        "adpcm.END_ON_WRITE_AT_ZERO" => s.adpcm.end_on_write_at_zero = flag(text),
101        "arcade.UNMAPPED_READ" => s.arcade.unmapped_read = integer(text)? as u8,
102        "arcade.SHIFT_READ_MASK" => s.arcade.shift_read_mask = integer(text)? as u8,
103        "arcade.TRIGGER_REG_READ" => s.arcade.trigger_reg_read = integer(text)? as u8,
104        "arcade.POWER_ON_RAM_BYTE" => s.arcade.power_on_ram_byte = integer(text)? as u8,
105        "arcade.RESET_CLEARS_REGISTERS" => s.arcade.reset_clears_registers = flag(text),
106        _ => return Err(format!("no switch {target}")),
107    }
108    Ok(())
109}
110
111#[cfg(not(target_arch = "wasm32"))]
112fn open_disc(path: &str) -> Result<Disc, String> {
113    Disc::from_cue_path(path)
114}
115
116/// The gate's command line names files; a page hands `PcEngineCd` a `Disc` of its own.
117#[cfg(target_arch = "wasm32")]
118fn open_disc(path: &str) -> Result<Disc, String> {
119    Err(format!("{path}: no filesystem here"))
120}
121
122impl Setup {
123    /// `CARD [--disc CUE] [--arcade] [--frames N] [--press SPEC]... [--machine pce|tg16]
124    /// [--super yes|no] [--region-us] [--bram FILE] [--switch WHERE.NAME=VALUE]...
125    /// [--reset FRAME:button|power]... [--detail FRAME] [--out FILE]`
126    pub fn parse(args: &[String]) -> Result<Setup, String> {
127        let mut setup = Setup {
128            card: Vec::new(),
129            disc: None,
130            arcade: false,
131            frames: 60,
132            presses: Vec::new(),
133            machine: "pce".to_string(),
134            super_system_card: None,
135            region_us: false,
136            bram: None,
137            switches: CdSwitches::default(),
138            resets: Vec::new(),
139            detail: None,
140            out: None,
141            rest: Vec::new(),
142        };
143        let mut path = None;
144        let mut iter = args.iter();
145        let file = |path: &String| std::fs::read(path).map_err(|error| format!("{path}: {error}"));
146        while let Some(arg) = iter.next() {
147            let mut value = || iter.next().ok_or_else(|| format!("{arg} needs a value"));
148            match arg.as_str() {
149                "--disc" => setup.disc = Some(value()?.clone()),
150                "--arcade" => setup.arcade = true,
151                "--frames" => setup.frames = integer(value()?)?,
152                "--press" => setup.presses.push(parse_press(value()?)?),
153                "--machine" => setup.machine = value()?.clone(),
154                "--super" => setup.super_system_card = Some(value()? == "yes"),
155                "--region-us" => setup.region_us = true,
156                "--bram" => setup.bram = Some(file(value()?)?),
157                "--switch" => set_switch(&mut setup.switches, value()?)?,
158                "--reset" => {
159                    let text = value()?;
160                    let (frame, kind) = text
161                        .split_once(':')
162                        .ok_or_else(|| format!("--reset FRAME:button|power, not {text}"))?;
163                    let kind = match kind {
164                        "button" => ResetKind::Button,
165                        "power" => ResetKind::PowerOn,
166                        _ => return Err(format!("--reset FRAME:button|power, not {text}")),
167                    };
168                    setup.resets.push((integer(frame)?, kind));
169                }
170                "--detail" => setup.detail = Some(integer(value()?)?),
171                "--out" => setup.out = Some(value()?.clone()),
172                _ if path.is_none() && !arg.starts_with("--") => path = Some(arg.clone()),
173                _ => setup.rest.push(arg.clone()),
174            }
175        }
176        setup.card = file(&path.ok_or("no System Card image given")?)?;
177        Ok(setup)
178    }
179
180    /// One more machine, built the same way each time, the drive's command log recorded.
181    pub fn build(&self) -> Result<System, String> {
182        let disc = match &self.disc {
183            Some(path) => Some(open_disc(path)?),
184            None => None,
185        };
186        let mut machine = PcEngineCd::new(&self.card, disc);
187        machine.super_system_card = self.super_system_card;
188        machine.region_us = self.region_us;
189        machine.bram = self.bram.clone();
190        machine.arcade_card = self.arcade;
191        machine.switches = self.switches;
192        machine.board.machine = match self.machine.as_str() {
193            "pce" => PC_ENGINE,
194            "tg16" => TURBOGRAFX_16,
195            other => return Err(format!("no machine {other}: pce or tg16")),
196        };
197        machine.board.pad = Some(Box::new(Pad2::new()));
198        let mut system = machine.build()?;
199        if let Some(unit) = unit(system.board_mut()) {
200            unit.bus.record_log = true;
201        }
202        Ok(system)
203    }
204
205    /// Before a frame runs: hold the buttons of the presses, and reset if this frame asks.
206    pub fn before_frame(&self, system: &mut System) {
207        let frame = system.frame();
208        system
209            .board_mut()
210            .set_pressed(0, held(&self.presses, frame));
211        for &(at, kind) in &self.resets {
212            if at == frame {
213                system.board_mut().reset(kind);
214            }
215        }
216    }
217}
218
219/// The line of the frame that just ran: the base gate's, then the drive's commands.
220pub fn frame_line(system: &mut System) -> String {
221    let line = pcengine_rust::trace::frame_line(system);
222    let mut commands = Sha1::new();
223    let mut count = 0;
224    if let Some(unit) = unit(system.board_mut()) {
225        count = unit.bus.log.len();
226        for (at, text) in unit.bus.log.drain(..) {
227            commands.update(format!("{at} {text}\n"));
228        }
229    }
230    let digest: String = commands
231        .finalize()
232        .iter()
233        .map(|byte| format!("{byte:02x}"))
234        .collect();
235    format!("{line} cmd={count}:{digest}")
236}
237
238/// Run `frames` frames with the setup's presses and resets; a line a frame.
239pub fn run_frames(setup: &Setup, system: &mut System, frames: i64) -> Vec<String> {
240    (0..frames)
241        .map(|_| {
242            setup.before_frame(system);
243            system.run_frame();
244            frame_line(system)
245        })
246        .collect()
247}
248
249fn started(setup: &Setup) -> Result<System, String> {
250    let mut system = setup.build()?;
251    system.board_mut().bus_log = Some(Vec::new());
252    Ok(system)
253}
254
255fn settle(system: &mut System) {
256    if let Some(log) = system.board_mut().bus_log.as_mut() {
257        log.clear();
258    }
259    system.board_mut().take_audio();
260    if let Some(unit) = unit(system.board_mut()) {
261        unit.bus.log.clear();
262    }
263}
264
265/// Save states, proven complete (the base crate's `trace::roundtrip`, the reference's
266/// `scripts/cd_state.py`): power on, run to frame `at` plus `extra` instructions, save, then
267/// build a second machine the same way (it opens the disc itself), load the state into it, and
268/// run both to frame `to`. Every frame after the save must be the same on both, by the gate's
269/// own lines. A third run loads the state into a machine that has run elsewhere first; and
270/// the loaded machine, saved at once, must give the same bytes back.
271pub fn roundtrip(setup: &Setup, at: i64, to: i64, extra: i64) -> Result<String, String> {
272    use pcengine_rust::state::{load_state, save_state};
273    let mut first = started(setup)?;
274    run_frames(setup, &mut first, at);
275    for _ in 0..extra {
276        first.step();
277    }
278    let state = save_state(&first);
279    settle(&mut first);
280    let expected = run_frames(setup, &mut first, to - at);
281    for (label, warm) in [
282        ("a fresh machine", 0),
283        ("a machine that had run", 1.max(at / 2)),
284    ] {
285        let mut second = started(setup)?;
286        run_frames(setup, &mut second, warm);
287        load_state(&mut second, &state).map_err(|error| format!("{label}: {error}"))?;
288        if save_state(&second) != state {
289            return Err(format!(
290                "{label}: saved again at once, the state is not the same bytes"
291            ));
292        }
293        settle(&mut second);
294        let got = run_frames(setup, &mut second, to - at);
295        for (n, (a, b)) in expected.iter().zip(&got).enumerate() {
296            if a != b {
297                return Err(format!(
298                    "{label}: differs in frame {} after the save\n  expected {a}\n  got      {b}",
299                    n + 1
300                ));
301            }
302        }
303    }
304    Ok(format!(
305        "{} bytes; {} frames after the save equal, twice",
306        state.len(),
307        to - at
308    ))
309}
310
311/// The snapshot pair in a run-ahead pass (the base crate's `trace::runahead`): every frame is
312/// run, a snapshot taken, `ahead` more frames run with other buttons held, and the snapshot put
313/// back. Each frame's line, and the state at the end, must equal a plain run's.
314pub fn runahead(setup: &Setup, from: i64, frames: i64, ahead: i64) -> Result<String, String> {
315    use pcengine_rust::state::{load_snapshot, save_snapshot, save_state};
316    let mut plain = started(setup)?;
317    run_frames(setup, &mut plain, from);
318    let expected = run_frames(setup, &mut plain, frames);
319    let mut system = started(setup)?;
320    run_frames(setup, &mut system, from);
321    let mut bytes = 0;
322    for (n, wanted) in expected.iter().enumerate() {
323        setup.before_frame(&mut system);
324        system.run_frame();
325        let line = frame_line(&mut system);
326        if &line != wanted {
327            return Err(format!(
328                "frame {} differs after a snapshot was put back\n  expected {wanted}\n  got      {line}",
329                n + 1
330            ));
331        }
332        let snapshot = save_snapshot(&system);
333        bytes = snapshot.len();
334        for _ in 0..ahead {
335            system
336                .board_mut()
337                .set_pressed(0, pads::RUN | pads::I | pads::RIGHT);
338            system.run_frame();
339        }
340        load_snapshot(&mut system, &snapshot)?;
341        settle_logs(&mut system);
342    }
343    if save_state(&system) != save_state(&plain) {
344        return Err("the end state is not the plain run's".to_string());
345    }
346    Ok(format!(
347        "{frames} frames from {from}, {ahead} ahead of each, equal to the plain run; a snapshot is {bytes} bytes"
348    ))
349}
350
351fn settle_logs(system: &mut System) {
352    if let Some(log) = system.board_mut().bus_log.as_mut() {
353        log.clear();
354    }
355    if let Some(unit) = unit(system.board_mut()) {
356        unit.bus.log.clear();
357    }
358}