// SPDX-License-Identifier: MIT //! Run lockstep scripts (scripts/lockstep_gen.py, scripts/export_streams.py) on this crate and //! print the trace that scripts/lockstep_ref.py prints for ay8910-python. //! //! ```text //! cargo run --release --features serde --example ay8910-trace -- SCRIPT [SCRIPT ...] [--out-dir DIR] [--roundtrip] //! ``` //! //! With one script and no `--out-dir` the trace goes to stdout; otherwise each script's trace //! is written to DIR/.trace. The script format is scripts/lockstep_gen.py's docstring. //! //! `--roundtrip` (rung 4, save states): at every `save`, `state` and `take` line the chip is //! saved and restored through both serde_json and bincode, required to equal the chip it came //! from, and the restored copy runs on. The reference does nothing there, so the traces must //! still be identical. use std::fmt::Write as _; use std::path::{Path, PathBuf}; use ay8910_rust::{PSGVariant, AY8910, AY8912, AY8913, PSG, SUNSOFT_5B, VARIANTS, YM2149}; use sha2::{Digest, Sha256}; fn part(key: &str) -> PSGVariant { match key { "AY8910" => AY8910, "AY8912" => AY8912, "AY8913" => AY8913, "YM2149" => YM2149, "SUNSOFT_5B" => SUNSOFT_5B, _ => panic!("unknown variant {key}"), } } fn digest(bytes: &[u8]) -> String { let hash = Sha256::digest(bytes); hash[..8].iter().fold(String::new(), |mut s, b| { let _ = write!(s, "{b:02x}"); s }) } fn level_bytes(levels: &[[u8; 3]]) -> Vec { levels.iter().flatten().copied().collect() } fn level_list(levels: &[[u8; 3]]) -> String { levels.iter().fold(String::new(), |mut s, [a, b, c]| { let _ = write!(s, " {a},{b},{c}"); s }) } fn bools(values: &[bool]) -> String { values .iter() .map(|&b| (b as u8).to_string()) .collect::>() .join(",") } fn list(values: &[T]) -> String { values .iter() .map(T::to_string) .collect::>() .join(",") } fn state(chip: &PSG) -> String { let registers: String = chip.registers.iter().map(|r| format!("{r:02X}")).collect(); format!( "state variant={} record={} envelope_top={} driven={} registers={} address={} \ selected={} bus={} clock_divider={} divider_count={} phase={} tone_period={} \ tone_count={} tone_held={} tone_output={} noise_period={} noise_count={} \ noise_held={} noise_half={} noise_register={} envelope_period={} envelope_count={} \ envelope_held={} envelope_half={} envelope_step={} envelope_rising={} \ envelope_holding={} envelope_level={} clock={} queued={} levels={}", chip.variant.name.replace(' ', "_"), chip.record as u8, chip.envelope_top, list(&chip.driven), registers, chip.address, chip.selected as u8, chip.bus, chip.clock_divider, chip.divider_count, chip.phase, list(&chip.tone_period), list(&chip.tone_count), bools(&chip.tone_held), list(&chip.tone_output), chip.noise_period, chip.noise_count, chip.noise_held as u8, chip.noise_half, chip.noise_register, chip.envelope_period, chip.envelope_count, chip.envelope_held as u8, chip.envelope_half, chip.envelope_step, chip.envelope_rising as u8, chip.envelope_holding as u8, chip.envelope_level, chip.clock, chip.outputs.len(), list(&chip.levels_now), ) } fn tables(out: &mut Vec) { out.push(format!( "constants {} {} {}", ay8910_rust::CLOCKS_PER_STEP, ay8910_rust::STROBE_PHASE, ay8910_rust::COUNT_PHASE )); for v in VARIANTS.iter() { let dac: Vec = v .dac .iter() .map(|x| format!("{:016x}", x.to_bits())) .collect(); out.push(format!( "variant {}|{}|{}|{}|{}|{}|{}|{}", v.name, v.envelope_steps, v.ports, list(&v.register_masks), v.clock_divider, v.has_sel_pin as u8, v.codes(), dac.join(",") )); } for (name, table) in [ ("DAC_AY_MEASURED", &ay8910_rust::DAC_AY_MEASURED[..]), ("DAC_AY_LOGARITHMIC", &ay8910_rust::DAC_AY_LOGARITHMIC[..]), ("DAC_YM_DATASHEET", &ay8910_rust::DAC_YM_DATASHEET[..]), ("DAC_YM_MEASURED", &ay8910_rust::DAC_YM_MEASURED[..]), ("DAC_5B", &ay8910_rust::DAC_5B[..]), ] { let bits: Vec = table .iter() .map(|x| format!("{:016x}", x.to_bits())) .collect(); out.push(format!("table {name} {}", bits.join(","))); } } fn roundtrip(chip: PSG) -> PSG { let json = serde_json::to_string(&chip).expect("serialise (json)"); let from_json: PSG = serde_json::from_str(&json).expect("restore (json)"); assert_eq!(from_json, chip, "a chip restored from JSON differs"); let bytes = bincode::serialize(&from_json).expect("serialise (bincode)"); let restored: PSG = bincode::deserialize(&bytes).expect("restore (bincode)"); assert_eq!(restored, chip, "a chip restored from bincode differs"); restored } fn trace(text: &str, round: bool) -> Vec { let mut out = Vec::new(); let mut lines = text.lines(); let head: Vec<&str> = lines .next() .expect("variant line") .split_whitespace() .collect(); assert_eq!(head[0], "variant"); let mut chip = PSG::with_record(part(head[1]), head.get(3) != Some(&"0")); let full = lines.next().expect("mode line").split_whitespace().nth(1) == Some("full"); for line in lines { let words: Vec<&str> = line.split_whitespace().collect(); let Some((&op, args)) = words.split_first() else { continue; }; let num = |i: usize| -> u64 { args[i].parse().expect("a number") }; let byte = |i: usize| -> u8 { args[i].parse().expect("a byte") }; let pins = |i: usize| -> Option { (args[i] != "-").then(|| args[i].parse().expect("a byte")) }; match op { "s" => chip.select(byte(0)), "d" => chip.write(byte(0)), "w" => chip.write_register(byte(0), byte(1)), "r" => out.push(format!("r {}", chip.read())), "rr" => out.push(format!("rr {}", chip.read_register(byte(0)))), "pa" => chip.port_a_in = pins(0), "pb" => chip.port_b_in = pins(0), "la" => chip.port_a_out = args[0] == "1", "lb" => chip.port_b_out = args[0] == "1", "div" => chip.clock_divider = byte(0), "reset" => chip.reset(), "tick" => { let n = num(0); let mut polled = Vec::with_capacity(n as usize); for _ in 0..n { chip.tick(); polled.push(chip.levels()); } if full { out.push(format!("tick {n}{}", level_list(&polled))); } else { out.push(format!("tick {n} {}", digest(&level_bytes(&polled)))); } } "run" => chip.run(num(0)), "take" => { if round { chip = roundtrip(chip); } let taken = chip.take_outputs(); if full { out.push(format!("take {}{}", taken.len(), level_list(&taken))); } else { out.push(format!( "take {} {}", taken.len(), digest(&level_bytes(&taken)) )); } } "samples" => { let values = chip.take_samples(); let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); out.push(format!("samples {} {}", values.len(), digest(&bytes))); } "mix" => out.push(format!("mix {:016x}", chip.mix().to_bits())), "levels" => { let [a, b, c] = chip.levels(); out.push(format!("levels {a} {b} {c}")); } "state" => { if round { chip = roundtrip(chip); } out.push(state(&chip)); } "tables" => tables(&mut out), "save" => { if round { chip = roundtrip(chip); } out.push("save".into()); } _ => panic!("unknown op {op}"), } for (register, value) in chip.take_port_changes() { out.push(format!("P {register} {value}")); } } out } fn main() { let mut out_dir: Option = None; let mut round = false; let mut scripts = Vec::new(); let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--out-dir" => out_dir = Some(PathBuf::from(args.next().expect("a directory"))), "--roundtrip" => round = true, _ => scripts.push(PathBuf::from(arg)), } } for script in &scripts { let text = std::fs::read_to_string(script).expect("read the script"); let result = trace(&text, round).join("\n") + "\n"; match (&out_dir, scripts.len()) { (None, 1) => print!("{result}"), (dir, _) => { let dir = dir.clone().unwrap_or_else(|| PathBuf::from(".")); let stem = Path::new(script).file_stem().expect("a name"); std::fs::write(dir.join(stem).with_extension("trace"), result) .expect("write the trace"); } } } }