// SPDX-License-Identifier: MIT //! Sound: the TIA's stream, each cartridge POKEY's stream, and the mix (a fit, U15). //! //! **Streams** (the reference's brief: "sound as separate streams"). The TIA's two //! channels tick twice a line from its own horizontal counter (a2600-python's //! `audio.py`: one sample per tick, at the pads' phase B; DIE, inherited), which //! in 7800 mode free-runs at 228 colour clocks a line beside MARIA's 227 (docs/timing.md //! "2600 mode"), so the stream's rate is 2 x 3,579,545 / 228 = 31,399.5 samples a //! second on NTSC (31,113.9 on PAL), uneven by a few clocks within a line. A //! cartridge POKEY ticks once per Φ2 period (pokey-python, contract: one //! `tick()` per period; DOC: [1702B] p. 29, C22); its level is **sampled at the //! TIA's sample instants** (its `mix()` read just after each TIA tick B), so both //! streams share one clock and one length (not a hardware value). Point sampling at //! 31.4 kHz aliases POKEY tones above 15.7 kHz; that is a choice of this frontend //! stage, not of the chips, and the per-period levels remain available from //! pokey-rust (`record = true`). //! //! **The mix** is not documented (docs/undocumented-behavior.md U15: the //! console's audio resistor network is not in the pinned schematics, and no //! console recording is pinned; its resistor values would settle it). It is a //! **fit** (FITTED), labelled: each stream is already 0..1 by its own chip's fit //! (a2600-python `audio.mix`; pokey-python `mix()`: the four channel codes through its //! DAC and fitted saturating curve, its B3.9), and the output is their weighted sum //! `(tia + k * pokey) / (1 + k)` with `k = POKEY_WEIGHT` per chip. The weight 1 is //! equal full scale; the reference's scripts/audio_compare.py prints the ratio MAME //! 0.285's own recording implies, as a detector's number, not a judge's. //! //! [`wav_bytes`] writes 16-bit mono PCM at the stream's nominal rate. //! //! Rust-forced differences (a7800-python `sound.py` at d6b220d): the tap's lists are //! shared with the TIA's sample callback (`Rc>`). The reference's callback //! drains the TIA's own sample list every 4,096 samples (`audio.take_samples()`, to keep //! it bounded; nothing reads it while the tap is attached); a Rust callback cannot reach //! the `Audio` that calls it, so [`SoundTap::take`] drains it instead, when the host //! takes the mix. Python's `round` (half to even) is `round_ties_even`. use std::cell::RefCell; use std::rc::Rc; use pokey::POKEY; use crate::board::Board; use crate::machine::Machine; // FITTED (U15): equal full scale, checked against MAME 0.285's recording as a detector // (Ballblazer 3-10 s level r 0.943 on the archived core, 0.949 on pokey-python 6ed1ffa, // scripts/audio_compare.py); other weights tried: not recorded pub const POKEY_WEIGHT: f64 = 1.0; /// TIA audio ticks a second: two per 228-colour-clock line of the TIA's own counter. pub fn tia_rate(machine: &Machine) -> f64 { let colour_clock = machine.maria_hz() / 2.0; // MARIA's clock / 2 = the TIA's colour clock (DOC) 2.0 * colour_clock / 228.0 // DIE: the TIA's 228-clock counter (a2600-python) } #[derive(Default)] pub struct Streams { pub tia: Vec, pub pokey: Vec, pub mixed: Vec, } /// Records the TIA's samples and, at each one, every cartridge POKEY's level. /// /// Attach with [`SoundTap::attach`] before running; [`SoundTap::take`] returns the mixed /// samples since the last call, `streams.tia` and `streams.pokey` the raw streams. pub struct SoundTap { pub pokeys: Vec>>, pub keep_streams: bool, pub streams: Rc>, } impl SoundTap { pub fn new(board: &Board, keep_streams: bool) -> SoundTap { SoundTap { pokeys: board.cartridge.pokeys(), keep_streams, streams: Rc::new(RefCell::new(Streams::default())), } } /// Hook a2600-rust's `Audio::on_sample` (its docs/api.md: called with each /// sample where it is made, phase B of the tick), so each POKEY is read at /// the TIA's sample instant. pub fn attach(self, board: &mut Board) -> SoundTap { let pokeys = self.pokeys.clone(); let weight = POKEY_WEIGHT * pokeys.len() as f64; let scale = 1.0 / (1.0 + weight); let streams = self.streams.clone(); let keep = self.keep_streams; board.tia.audio.on_sample = Some(Box::new(move |t: f64| { let p = if pokeys.is_empty() { 0.0 } else { let mut sum = 0.0; for chip in pokeys.iter() { sum += chip.borrow().mix(); } sum / pokeys.len() as f64 }; let mut s = streams.borrow_mut(); s.mixed.push((t + weight * p) * scale); if keep { s.tia.push(t); s.pokey.push(p); } })); self } /// The mixed samples since the last call (and the TIA's own list drained). pub fn take(&self, board: &mut Board) -> Vec { board.tia.audio.take_samples(); // the TIA's own list, unread here: drained std::mem::take(&mut self.streams.borrow_mut().mixed) } } /// 16-bit mono PCM, 0..1 mapped to -32767..32767 around the mean (DC removed). /// Output formatting: not a hardware value. pub fn wav_bytes(samples: &[f64], rate: f64) -> Vec { let mean = if samples.is_empty() { 0.0 } else { let mut sum = 0.0; for s in samples { sum += s; } sum / samples.len() as f64 }; let mut frames = Vec::with_capacity(samples.len() * 2); for s in samples { let v = ((s - mean) * 32767.0).round_ties_even().clamp(-32767.0, 32767.0) as i16; frames.extend_from_slice(&v.to_le_bytes()); } let rate = rate.round_ties_even() as u32; let mut out = Vec::with_capacity(44 + frames.len()); out.extend_from_slice(b"RIFF"); out.extend_from_slice(&(36 + frames.len() as u32).to_le_bytes()); out.extend_from_slice(b"WAVEfmt "); out.extend_from_slice(&16u32.to_le_bytes()); out.extend_from_slice(&1u16.to_le_bytes()); // PCM out.extend_from_slice(&1u16.to_le_bytes()); // mono out.extend_from_slice(&rate.to_le_bytes()); out.extend_from_slice(&(rate * 2).to_le_bytes()); out.extend_from_slice(&2u16.to_le_bytes()); out.extend_from_slice(&16u16.to_le_bytes()); out.extend_from_slice(b"data"); out.extend_from_slice(&(frames.len() as u32).to_le_bytes()); out.extend_from_slice(&frames); out }