//! Shared by the tests: ways to drive the chip and read its output as a board would. //! //! The tests look at what `take_samples()` returns wherever they can, and at state //! fields only where the statement under test is about a register. //! //! A transcription of sn76489-python's `tests/helpers.py` at f8157f4. Each test file uses //! some of these, so the rest are allowed to go unused there. Added for Rust: `Rng`, //! Python's `random.Random` (so the tests' random streams are the reference's own), `find` //! (Python's `bytes.find`) and `reference_dir`. #![allow(dead_code)] use std::path::PathBuf; use sha2::{Digest, Sha256}; use sn76489::{ PSGVariant, CLOCKS_PER_SAMPLE, GAME_GEAR_PSG, SEGA_VDP_PSG, SN76489, SN76489AN, YM7101_PSG, }; /// The reference's git-ignored `reference/` directory, holding fetched captures, when it /// is on this machine: `$SN76489_REFERENCE`, else `external/sn76489-python/reference`, else /// `../sn76489-python/reference`. Only Kortink's capture is read from it. pub fn reference_dir() -> Option { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let candidates = [ std::env::var_os("SN76489_REFERENCE").map(PathBuf::from), Some(root.join("external/sn76489-python/reference")), Some(root.join("../sn76489-python/reference")), ]; candidates.into_iter().flatten().find(|p| p.is_dir()) } /// The clock Sega's manuals compute their tables with (Game Gear manual, psg-2). pub const NTSC_CLOCK: u64 = 3_579_545; pub const SEGA_PARTS: [PSGVariant; 3] = [SEGA_VDP_PSG, GAME_GEAR_PSG, YM7101_PSG]; /// The four parts, as the test files' `ALL`. pub const ALL: [PSGVariant; 4] = [SN76489AN, SEGA_VDP_PSG, GAME_GEAR_PSG, YM7101_PSG]; /// Run `ticks` ticks and return the left level after each. pub fn left(psg: &mut SN76489, ticks: u64) -> Vec { psg.run(ticks * CLOCKS_PER_SAMPLE); psg.take_samples().into_iter().map(|pair| pair.0).collect() } /// The same as 0 or 1, for a chip with one channel audible at full volume. pub fn bits(psg: &mut SN76489, ticks: u64) -> Vec { left(psg, ticks) .into_iter() .map(|level| if level > 0.5 { 1 } else { 0 }) .collect() } /// The two-byte tone load of TI's data sheet, section 6. pub fn write_tone(psg: &mut SN76489, channel: u32, value: u32) { psg.write(0x80 | (channel << 5) | (value & 0x0F)); psg.write((value >> 4) & 0x3F); } pub fn write_volume(psg: &mut SN76489, channel: u32, attenuation: u32) { psg.write(0x90 | (channel << 5) | (attenuation & 0x0F)); } /// A chip with every channel off but one, which is at full volume. pub fn solo(variant: PSGVariant, channel: u32) -> SN76489 { let mut psg = SN76489::with_silent_start(variant, true); write_volume(&mut psg, channel, 0); psg } /// Indices at which the level differs from the one before. pub fn changes(levels: &[T]) -> Vec { (1..levels.len()) .filter(|&i| levels[i] != levels[i - 1]) .collect() } pub fn rises(stream: &[u8]) -> Vec { (1..stream.len()) .filter(|&i| stream[i] != 0 && stream[i - 1] == 0) .collect() } /// The noise channel's bit after each of `shifts` shifts from a noise write. /// /// The register is clocked through rate 3 with the third tone value at 1, which /// toggles that tone every tick, so the register shifts once in two ticks. From /// power-on the tone's first toggle is a fall (the core's chosen starting state), /// so the first shift is on the second tick. pub fn noise_bits(variant: PSGVariant, control: u32, shifts: u64) -> Vec { let mut psg = solo(variant, 3); write_tone(&mut psg, 2, 1); psg.write(0xE0 | (control & 0x04) | 0x03); bits(&mut psg, 2 * shifts) .into_iter() .skip(1) .step_by(2) .collect() } pub fn sha256(data: &[u8]) -> String { Sha256::digest(data) .iter() .map(|b| format!("{b:02x}")) .collect() } /// Python's `bytes.find(sub, start)`. pub fn find(haystack: &[u8], needle: &[u8], start: usize) -> Option { (start..=haystack.len().saturating_sub(needle.len())) .find(|&i| &haystack[i..i + needle.len()] == needle) } /// Python's `random.Random(seed)` for a non-negative integer seed: MT19937 seeded by /// `init_by_array` with the seed's 32-bit words, and `randrange` and `random()` as CPython's /// and PyPy's `random.py` build them on it (`_randbelow` by `getrandbits` with rejection; /// `random()` from two words, 53 bits). With it the random streams here are the reference /// tests' streams number for number. pub struct Rng { state: [u32; 624], index: usize, } impl Rng { pub fn new(seed: u64) -> Self { let mut key = vec![seed as u32]; if seed >> 32 != 0 { key.push((seed >> 32) as u32); } let mut rng = Rng { state: [0; 624], index: 624, }; rng.init_genrand(19_650_218); let (n, len) = (624usize, key.len()); let (mut i, mut j) = (1usize, 0usize); for _ in 0..n.max(len) { let prev = rng.state[i - 1] ^ (rng.state[i - 1] >> 30); rng.state[i] = (rng.state[i] ^ prev.wrapping_mul(1_664_525)) .wrapping_add(key[j]) .wrapping_add(j as u32); i += 1; j += 1; if i >= n { rng.state[0] = rng.state[n - 1]; i = 1; } if j >= len { j = 0; } } for _ in 0..n - 1 { let prev = rng.state[i - 1] ^ (rng.state[i - 1] >> 30); rng.state[i] = (rng.state[i] ^ prev.wrapping_mul(1_566_083_941)).wrapping_sub(i as u32); i += 1; if i >= n { rng.state[0] = rng.state[n - 1]; i = 1; } } rng.state[0] = 0x8000_0000; rng } fn init_genrand(&mut self, seed: u32) { self.state[0] = seed; for i in 1..624 { let prev = self.state[i - 1] ^ (self.state[i - 1] >> 30); self.state[i] = prev.wrapping_mul(1_812_433_253).wrapping_add(i as u32); } self.index = 624; } fn genrand(&mut self) -> u32 { if self.index >= 624 { for k in 0..624 { let y = (self.state[k] & 0x8000_0000) | (self.state[(k + 1) % 624] & 0x7FFF_FFFF); let mut v = self.state[(k + 397) % 624] ^ (y >> 1); if y & 1 != 0 { v ^= 0x9908_B0DF; } self.state[k] = v; } self.index = 0; } let mut y = self.state[self.index]; self.index += 1; y ^= y >> 11; y ^= (y << 7) & 0x9D2C_5680; y ^= (y << 15) & 0xEFC6_0000; y ^ (y >> 18) } /// `getrandbits(k)` for 1 <= k <= 32. fn getrandbits(&mut self, k: u32) -> u64 { u64::from(self.genrand() >> (32 - k)) } /// `randrange(start, stop)`, for ranges below 2^32. pub fn range(&mut self, start: u64, stop: u64) -> u64 { let n = stop - start; let k = 64 - n.leading_zeros(); let mut r = self.getrandbits(k); while r >= n { r = self.getrandbits(k); } start + r } /// `random()`. pub fn random(&mut self) -> f64 { let a = u64::from(self.genrand() >> 5); let b = u64::from(self.genrand() >> 6); (a as f64 * 67_108_864.0 + b as f64) / 9_007_199_254_740_992.0 } }