//! The sound board against galemu: the PCM the Rust synthesizer produces //! for a run's per-frame sound writes equals galemu's `synth.py` output //! (oracle/reference/.s16, from oracle/galemu_sound.py). Needs the //! ROM set at rom/galaxian/; skips without it. use std::fs; use std::path::PathBuf; use serde_json::Value; use z80_wasm::galaxian::board::Machine; use z80_wasm::galaxian::roms; use z80_wasm::galaxian::sound::{sound_events, SoundState, SAMPLES_PER_FRAME}; use z80_wasm::galaxian::trace::parse_inputs; fn root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } fn pcm_for(run: &Value, program: &[u8]) -> Vec { let inputs: Vec = run["inputs"] .as_array() .unwrap() .iter() .map(|v| v.as_str().unwrap().to_string()) .collect(); let inputs = parse_inputs(&inputs).unwrap(); let mut machine = Machine::new(program, true).unwrap(); machine.board_mut().trace_memory_writes = false; let mut state = SoundState::default(); let mut frame = [0i16; SAMPLES_PER_FRAME]; let mut pcm = Vec::new(); let mut next_input = 0; for f in 0..run["frames"].as_u64().unwrap() { while next_input < inputs.len() && inputs[next_input].at <= f { machine .board_mut() .set_input(&inputs[next_input].control, inputs[next_input].pressed) .unwrap(); next_input += 1; } machine.run_frame().unwrap(); let events = std::mem::take(&mut machine.board_mut().events); state.synthesize_frame(&sound_events(&events), &mut frame); for sample in frame { pcm.extend_from_slice(&sample.to_le_bytes()); } } pcm } #[test] fn pcm_matches_galemu() { let dir = root().join("rom/galaxian"); if !dir.is_dir() { eprintln!("rom/galaxian/ not present; skipping"); return; } let roms = roms::load(|name| fs::read(dir.join(name)).ok()).unwrap(); let runs: Vec = serde_json::from_str(&fs::read_to_string(root().join("oracle/runs.json")).unwrap()) .unwrap(); let mut checked = 0; for run in runs.iter().filter(|r| r.get("frames").is_some()) { let name = run["name"].as_str().unwrap(); let Ok(reference) = fs::read(root().join("oracle/reference").join(format!("{name}.s16"))) else { continue; }; let ours = pcm_for(run, &roms.program); assert_eq!(ours.len(), reference.len(), "{name}: length"); let mut worst = 0i32; let mut first_bad = None; for (i, (a, b)) in ours.chunks(2).zip(reference.chunks(2)).enumerate() { let a = i16::from_le_bytes([a[0], a[1]]); let b = i16::from_le_bytes([b[0], b[1]]); let diff = (i32::from(a) - i32::from(b)).abs(); if diff > worst { worst = diff; } if diff > 0 && first_bad.is_none() { first_bad = Some((i, a, b)); } } assert_eq!(worst, 0, "{name}: first differing sample {:?}", first_bad); eprintln!("{name}: {} samples identical", ours.len() / 2); checked += 1; } assert!(checked > 0, "no PCM reference checked"); }