pcengine_rust/
trace.rs

1//! The lockstep gate's side of this board: per-frame digests of everything the gate compares,
2//! in the spelling `scripts/pce_trace.py` writes for the reference.
3//!
4//! Not a module of the reference: its counterpart there is `scripts/state_roundtrip.py`'s
5//! `observe` and `digest` and `scripts/presses.py`. A frame's line holds the frame counter, the
6//! master clock, the count and SHA-1 of the CPU bus log (`Board::bus_log`: physical address,
7//! value, kind, master clock of every cycle), the SHA-1 of the picture (`capture.last_frame`:
8//! the rows as little-endian u16, then the dividers), the count and SHA-1 of the mixed audio
9//! (`take_audio`, little-endian i16 pairs) and the CPU's whole `CpuState`.
10
11use huc6280::CpuState;
12use sha1::{Digest, Sha1};
13
14use crate::pads;
15use crate::system::System;
16
17fn hex(digest: &[u8]) -> String {
18    digest.iter().map(|byte| format!("{byte:02x}")).collect()
19}
20
21fn option(value: Option<bool>) -> &'static str {
22    match value {
23        None => "-",
24        Some(false) => "0",
25        Some(true) => "1",
26    }
27}
28
29/// Every field of the CPU's state, in `CpuState`'s order.
30pub fn cpu_text(s: &CpuState) -> String {
31    let mpr: String = s.mpr.iter().map(|byte| format!("{byte:02x}")).collect();
32    format!(
33        "{:02x},{:02x},{:02x},{:02x},{:04x},{:02x},{},{},{:02x},{}{}{},{},{}{}{}{},{},{},{},{}",
34        s.a,
35        s.x,
36        s.y,
37        s.s,
38        s.pc,
39        s.p,
40        mpr,
41        s.high_speed as u8,
42        s.mpr_latch,
43        s.irq1 as u8,
44        s.irq2 as u8,
45        s.tiq as u8,
46        s.irq_disable,
47        s.halted as u8,
48        s.reset_pending as u8,
49        s.maskable_interrupt_pending as u8,
50        s.non_maskable_interrupt_pending as u8,
51        option(s.polled_i),
52        option(s.polled_maskable_interrupt),
53        option(s.polled_non_maskable_interrupt),
54        s.skipped_poll as u8,
55    )
56}
57
58/// The line of the frame that just ran. Empties the bus log and takes the audio.
59pub fn frame_line(system: &mut System) -> String {
60    let cpu = cpu_text(&system.cpu.capture_state());
61    let frame = system.frame();
62    let board = system.board_mut();
63    let mut bus = Sha1::new();
64    let mut cycles = 0;
65    if let Some(log) = board.bus_log.as_mut() {
66        cycles = log.len();
67        for word in log.iter() {
68            bus.update(word.to_le_bytes());
69        }
70        log.clear();
71    }
72    let picture = match board.capture.last_frame.as_ref() {
73        None => "-".to_string(),
74        Some(picture) => {
75            let mut out = Sha1::new();
76            for row in &picture.rows {
77                for value in row {
78                    out.update(value.to_le_bytes());
79                }
80            }
81            out.update(&picture.dividers);
82            format!("{}:{}", picture.number, hex(&out.finalize()))
83        }
84    };
85    let samples = board.take_audio();
86    let mut audio = Sha1::new();
87    for (left, right) in &samples {
88        audio.update(left.to_le_bytes());
89        audio.update(right.to_le_bytes());
90    }
91    format!(
92        "{} mclk={} bus={}:{} pic={} audio={}:{} cpu={}",
93        frame,
94        board.mclk,
95        cycles,
96        hex(&bus.finalize()),
97        picture,
98        samples.len(),
99        hex(&audio.finalize()),
100        cpu
101    )
102}
103
104/// The per-cycle lines of `Board::bus_detail` (the gate's narrowing mode), emptied.
105pub fn detail_lines(system: &mut System) -> Vec<String> {
106    let Some(detail) = system.board_mut().bus_detail.as_mut() else {
107        return Vec::new();
108    };
109    detail
110        .drain(..)
111        .map(|(kind, address, value, mclk)| match kind {
112            0 => format!("r {address:06x} {value:02x} {mclk}"),
113            1 => format!("w {address:06x} {value:02x} {mclk}"),
114            _ => format!("i {mclk}"),
115        })
116        .collect()
117}
118
119/// A press `BUTTONS@FRAME+HOLD` (the reference's `scripts/presses.py`): the buttons, joined
120/// with `-`, are held while the count of completed frames is in FRAME .. FRAME+HOLD-1.
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct Press {
123    pub mask: u16,
124    pub start: i64,
125    pub hold: i64,
126}
127
128pub fn parse_press(spec: &str) -> Result<Press, String> {
129    let bad = || format!("bad press {spec:?}: BUTTONS@FRAME+HOLD");
130    let (buttons, when) = spec.split_once('@').ok_or_else(bad)?;
131    let (start, hold) = match when.split_once('+') {
132        Some((start, hold)) => (start, hold),
133        None => (when, "1"),
134    };
135    let mut mask = 0;
136    for name in buttons.to_lowercase().split('-') {
137        mask |= match name {
138            "up" => pads::UP,
139            "down" => pads::DOWN,
140            "left" => pads::LEFT,
141            "right" => pads::RIGHT,
142            "i" => pads::I,
143            "ii" => pads::II,
144            "select" => pads::SELECT,
145            "run" => pads::RUN,
146            "iii" => pads::III,
147            "iv" => pads::IV,
148            "v" => pads::V,
149            "vi" => pads::VI,
150            _ => return Err(bad()),
151        };
152    }
153    Ok(Press {
154        mask,
155        start: start.parse().map_err(|_| bad())?,
156        hold: hold.parse().map_err(|_| bad())?,
157    })
158}
159
160/// The buttons down while `frame` frames have completed.
161pub fn held(presses: &[Press], frame: i64) -> u16 {
162    presses
163        .iter()
164        .filter(|press| (press.start..press.start + press.hold).contains(&frame))
165        .fold(0, |mask, press| mask | press.mask)
166}
167
168/// How a traced machine is built: the command line shared by `pce-trace`,
169/// `pce-state-roundtrip` and `scripts/pce_trace.py` (which builds the reference the same way).
170#[derive(Clone, Debug)]
171pub struct Setup {
172    pub image: Vec<u8>,
173    pub machine: String,
174    pub frames: i64,
175    pub presses: Vec<Press>,
176    pub seed: Option<i64>,
177    pub start_line: i64,
178    pub start_offset: i64,
179    pub vblank_dots: Option<i64>,
180    pub vertical_at_line_start: bool,
181    pub dma_resumes: bool,
182    pub psg: crate::psg::PsgSwitches,
183    pub timer_window: i64,
184    pub lines_follow_vce_bit2: bool,
185    /// `pad2` (default), `pad6`, `multitap`, `multitap-clr-low`, `none`, `fake-controller`,
186    /// `lockstep-card`, `lockstep-port`, `lockstep-path`, `tennokoe`
187    pub device: String,
188    pub detail: Option<i64>,
189    pub out: Option<String>,
190    /// Arguments this parser does not know (a binary's own).
191    pub rest: Vec<String>,
192}
193
194impl Setup {
195    /// `IMAGE [--machine pce|tg16] [--frames N] [--press SPEC]... [--seed N] [--start-line N]
196    /// [--start-offset N] [--vblank-dots N|none] [--vertical-at-line-start] [--no-dma-resume]
197    /// [--psg NAME=VALUE]... [--psg-variant NAME] [--timer-window N] [--no-bit2-lines]
198    /// [--device NAME] [--detail FRAME] [--out FILE]`
199    /// The reference's defaults around a card image.
200    pub fn for_image(image: Vec<u8>) -> Setup {
201        Setup {
202            image,
203            machine: "pce".to_string(),
204            frames: 60,
205            presses: Vec::new(),
206            seed: None,
207            start_line: 0,
208            start_offset: 0,
209            vblank_dots: Some(-8),
210            vertical_at_line_start: false,
211            dma_resumes: true,
212            psg: crate::psg::PsgSwitches::default(),
213            timer_window: 15,
214            lines_follow_vce_bit2: true,
215            device: "pad2".to_string(),
216            detail: None,
217            out: None,
218            rest: Vec::new(),
219        }
220    }
221
222    pub fn parse(args: &[String]) -> Result<Setup, String> {
223        let mut setup = Setup::for_image(Vec::new());
224        let mut path = None;
225        let mut iter = args.iter();
226        let number = |text: &String| -> Result<i64, String> {
227            text.parse().map_err(|_| format!("not a number: {text}"))
228        };
229        while let Some(arg) = iter.next() {
230            let mut value = || iter.next().ok_or_else(|| format!("{arg} needs a value"));
231            match arg.as_str() {
232                "--machine" => setup.machine = value()?.clone(),
233                "--frames" => setup.frames = number(value()?)?,
234                "--press" => setup.presses.push(parse_press(value()?)?),
235                "--seed" => setup.seed = Some(number(value()?)?),
236                "--start-line" => setup.start_line = number(value()?)?,
237                "--start-offset" => setup.start_offset = number(value()?)?,
238                "--vblank-dots" => {
239                    let text = value()?;
240                    setup.vblank_dots = if text == "none" {
241                        None
242                    } else {
243                        Some(number(text)?)
244                    };
245                }
246                "--vertical-at-line-start" => setup.vertical_at_line_start = true,
247                "--no-dma-resume" => setup.dma_resumes = false,
248                "--psg-variant" => {
249                    let name = value()?;
250                    setup.psg = crate::psg::PsgSwitches::variant(name)
251                        .ok_or_else(|| format!("no PSG variant {name}"))?;
252                }
253                "--psg" => {
254                    let text = value()?;
255                    let (name, to) = text
256                        .split_once('=')
257                        .ok_or_else(|| format!("--psg NAME=VALUE, not {text}"))?;
258                    set_psg_switch(&mut setup.psg, name, to)?;
259                }
260                "--timer-window" => setup.timer_window = number(value()?)?,
261                "--no-bit2-lines" => setup.lines_follow_vce_bit2 = false,
262                "--device" => setup.device = value()?.clone(),
263                "--detail" => setup.detail = Some(number(value()?)?),
264                "--out" => setup.out = Some(value()?.clone()),
265                _ if path.is_none() && !arg.starts_with("--") => path = Some(arg.clone()),
266                _ => setup.rest.push(arg.clone()),
267            }
268        }
269        let path = path.ok_or("no card image given")?;
270        setup.image = std::fs::read(&path).map_err(|error| format!("{path}: {error}"))?;
271        Ok(setup)
272    }
273
274    pub fn machine(&self) -> Result<crate::machine::Machine, String> {
275        let mut machine = match self.machine.as_str() {
276            "pce" => crate::machine::PC_ENGINE,
277            "tg16" => crate::machine::TURBOGRAFX_16,
278            other => return Err(format!("no machine {other}: pce or tg16")),
279        };
280        machine.lines_follow_vce_bit2 = self.lines_follow_vce_bit2;
281        if self.device == "lockstep-path" {
282            machine.vdc_count = 2;
283        }
284        Ok(machine)
285    }
286
287    /// One more machine, built the same way each time.
288    pub fn build(&self) -> Result<System, String> {
289        use crate::board::{Board, BoardOptions};
290        use crate::fake_devices::{FakeController, LockstepCard, LockstepPath, LockstepPort};
291        use crate::sockets::{Card, ControllerPort, PixelPath, PortDevice};
292
293        let device = self.device.as_str();
294        let card: Box<dyn Card> = match device {
295            "lockstep-card" => Box::new(LockstepCard::new(&self.image)?),
296            "tennokoe" => Box::new(crate::cards::TennokoeCard::new(&self.image)?),
297            _ => crate::cards::make_card(&self.image)?,
298        };
299        let pad: Option<Box<dyn ControllerPort>> = match device {
300            "none" => None,
301            "pad6" => Some(Box::new(pads::Pad6::new())),
302            "fake-controller" => Some(Box::new(FakeController::new(0x05))),
303            "multitap" | "multitap-clr-low" => {
304                let mut tap = pads::MultiTap::new(vec![
305                    Some(Box::new(pads::Pad2::new())),
306                    None,
307                    Some(Box::new(pads::Pad6::new())),
308                    None,
309                    Some(Box::new(pads::Pad2::new())),
310                ])?;
311                tap.clr_high_reads_pad = device == "multitap";
312                Some(Box::new(tap))
313            }
314            _ => Some(Box::new(pads::Pad2::new())),
315        };
316        let port: Option<Box<dyn PortDevice>> = match device {
317            "lockstep-port" => Some(Box::new(LockstepPort::new())),
318            _ => None,
319        };
320        let pixel_path: Option<Box<dyn PixelPath>> = match device {
321            "lockstep-path" => Some(Box::new(LockstepPath::default())),
322            _ => None,
323        };
324        let board = Board::new(BoardOptions {
325            machine: self.machine()?,
326            card: Some(card),
327            port,
328            pad,
329            pixel_path,
330            power_on_seed: self.seed,
331            start_line: self.start_line,
332            start_offset: self.start_offset,
333            vblank_dots: self.vblank_dots,
334            vertical_at_line_start: self.vertical_at_line_start,
335            dma_resumes: self.dma_resumes,
336            psg: self.psg,
337            timer_underflow_window_mclk: self.timer_window,
338        })?;
339        Ok(System::new(board))
340    }
341
342    /// Hold the buttons of the presses for the frame about to run. Behind a multitap the same
343    /// buttons go to ports 0 and 2.
344    pub fn apply_presses(&self, system: &mut System) {
345        let mask = held(&self.presses, system.frame());
346        let board = system.board_mut();
347        board.set_pressed(0, mask);
348        if self.device.starts_with("multitap") {
349            board.set_pressed(2, mask);
350        }
351    }
352}
353
354/// One of the PSG's switches by the reference's attribute name.
355pub fn set_psg_switch(
356    switches: &mut crate::psg::PsgSwitches,
357    name: &str,
358    value: &str,
359) -> Result<(), String> {
360    use crate::psg::KeyOnMode;
361    let flag = || match value {
362        "true" | "True" | "1" => Ok(true),
363        "false" | "False" | "0" => Ok(false),
364        _ => Err(format!("{name}: true or false, not {value}")),
365    };
366    let number = || {
367        value
368            .parse::<i64>()
369            .map_err(|_| format!("{name}: a number, not {value}"))
370    };
371    match name {
372        "write_wave_while_playing" => switches.write_wave_while_playing = flag()?,
373        "dda_latch_needs_on" => switches.dda_latch_needs_on = flag()?,
374        "r6_overrides_sample_while_on" => switches.r6_overrides_sample_while_on = flag()?,
375        "keyon_mode" => {
376            switches.keyon_mode = match value {
377                "reload" => KeyOnMode::Reload,
378                "resume_step" => KeyOnMode::ResumeStep,
379                _ => return Err(format!("keyon_mode: reload or resume_step, not {value}")),
380            }
381        }
382        "lfo_requires_ch2_on" => switches.lfo_requires_ch2_on = flag()?,
383        "lfo_zero_multiplier" => switches.lfo_zero_multiplier = number()?,
384        "lfo_mask12" => switches.lfo_mask12 = flag()?,
385        "lf_trg_halts_always" => switches.lf_trg_halts_always = flag()?,
386        "scale_table_quirk" => switches.scale_table_quirk = flag()?,
387        "silent_units" => switches.silent_units = number()? as usize,
388        "render_audio" => switches.render_audio = flag()?,
389        "noise_zero_period" => switches.noise_zero_period = number()?,
390        "noise_free_running" => switches.noise_free_running = flag()?,
391        _ => return Err(format!("no PSG switch {name}")),
392    }
393    Ok(())
394}
395
396/// Run `frames` frames with the setup's presses; a line a frame.
397pub fn run_frames(setup: &Setup, system: &mut System, frames: i64) -> Vec<String> {
398    (0..frames)
399        .map(|_| {
400            setup.apply_presses(system);
401            system.run_frame();
402            frame_line(system)
403        })
404        .collect()
405}
406
407fn started(setup: &Setup) -> Result<System, String> {
408    let mut system = setup.build()?;
409    system.board_mut().bus_log = Some(Vec::new());
410    Ok(system)
411}
412
413fn settle(system: &mut System) {
414    if let Some(log) = system.board_mut().bus_log.as_mut() {
415        log.clear();
416    }
417    system.board_mut().take_audio();
418}
419
420/// Save states, proven complete (the reference's `scripts/state_roundtrip.py` `roundtrip`):
421/// power on, run to frame `at` plus `extra` instructions (so the save falls anywhere in a
422/// frame, between two instructions), save, then build a second system the same way, load the
423/// state into it, and run both to frame `to`. Every frame after the save must be the same on
424/// both, by the gate's own lines. A third run loads the state into a system that has run
425/// elsewhere first (to frame `at` / 2); and the loaded system, saved at once, must give the
426/// same bytes back. `Ok` says what was compared, `Err` what differed.
427pub fn roundtrip(setup: &Setup, at: i64, to: i64, extra: i64) -> Result<String, String> {
428    use crate::state::{load_state, save_state};
429    let mut first = started(setup)?;
430    run_frames(setup, &mut first, at);
431    for _ in 0..extra {
432        first.step();
433    }
434    let state = save_state(&first);
435    settle(&mut first);
436    let expected = run_frames(setup, &mut first, to - at);
437    for (label, warm) in [
438        ("a fresh system", 0),
439        ("a system that had run", 1.max(at / 2)),
440    ] {
441        let mut second = started(setup)?;
442        run_frames(setup, &mut second, warm);
443        load_state(&mut second, &state).map_err(|error| format!("{label}: {error}"))?;
444        if save_state(&second) != state {
445            return Err(format!(
446                "{label}: saved again at once, the state is not the same bytes"
447            ));
448        }
449        settle(&mut second);
450        let got = run_frames(setup, &mut second, to - at);
451        for (n, (a, b)) in expected.iter().zip(&got).enumerate() {
452            if a != b {
453                return Err(format!(
454                    "{label}: differs in frame {} after the save\n  expected {a}\n  got      {b}",
455                    n + 1
456                ));
457            }
458        }
459    }
460    Ok(format!(
461        "{} bytes; {} frames after the save equal, twice",
462        state.len(),
463        to - at
464    ))
465}
466
467/// The snapshot pair in a run-ahead pass: every frame is run, a snapshot taken, `ahead` more
468/// frames run with other buttons held, and the snapshot put back. Each frame's line, and the
469/// state at the end, must equal those of a run that never looked ahead.
470pub fn runahead(setup: &Setup, frames: i64, ahead: i64) -> Result<String, String> {
471    use crate::state::{load_snapshot, save_snapshot, save_state};
472    let mut plain = started(setup)?;
473    let expected = run_frames(setup, &mut plain, frames);
474    let mut system = started(setup)?;
475    let mut bytes = 0;
476    for (n, wanted) in expected.iter().enumerate() {
477        setup.apply_presses(&mut system);
478        system.run_frame();
479        let line = frame_line(&mut system);
480        if &line != wanted {
481            return Err(format!(
482                "frame {} differs after a snapshot was put back\n  expected {wanted}\n  got      {line}",
483                n + 1
484            ));
485        }
486        let snapshot = save_snapshot(&system);
487        bytes = snapshot.len();
488        for _ in 0..ahead {
489            system
490                .board_mut()
491                .set_pressed(0, pads::RUN | pads::I | pads::RIGHT);
492            system.run_frame();
493        }
494        load_snapshot(&mut system, &snapshot)?;
495        if let Some(log) = system.board_mut().bus_log.as_mut() {
496            log.clear();
497        }
498    }
499    if save_state(&system) != save_state(&plain) {
500        return Err("the end state is not the plain run's".to_string());
501    }
502    Ok(format!(
503        "{frames} frames, {ahead} ahead of each, equal to the plain run; a snapshot is {bytes} bytes"
504    ))
505}