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