// SPDX-License-Identifier: MIT //! The TIA's two sound channels, as the die wires them (docs/timing.md "Audio"). //! //! Evidence: the channel logic is DOC (TIA-1A schematic sheet 4) settled by DIE //! (the `audio` and `audio_modes` Sim2600 traces match both pads at every //! half clock, and the die's probed wires, milestone 3); the mix is DOC (the //! console's resistors) with a FITTED assumption (ideal switches). //! //! Each channel is three pieces of logic (TIA-1A logic diagram, sheet 4, "Audio //! circuits (2 req'd)", `reference/schematics`): //! //! - the **frequency divider**: a 5-bit binary counter *compared* with AUDF, not //! loaded from it. A match enables the channel's next tick and clears the //! counter; otherwise it counts on, wrapping after 31, so lowering AUDF below //! the count lets it run on to 31 first (tia-fpga "Audio"); //! - the **noise generator**: a 5-bit shift register (the five `D1` cells), //! which AUDC D1-D0 make a 5-bit polynomial, the low end of a 9-bit one with //! the pulse counter, a gate that holds the pulse counter, or a plain divider; //! - the **pulse counter**: four set/reset latches (G6-G9) that shift as a 4-bit //! polynomial, a Johnson counter (divide by 6 or 2) or a follower of the noise //! register's output, picked by AUDC D3-D2. Its low bit is the tone; the //! volume register gates the four weighted pull-downs of the pad with it. //! //! **Ticks.** The horizontal counter clocks both channels twice a line. Each tick //! has two phases (tia-fpga sim/README.md "Audio", read off the netlist): phase A //! compares the divider and, on an enabled tick, latches the hold decision and //! the noise feedback from AUDC as it then stands; phase B shifts the registers, //! and the pads change there. The two channels differ by one latch: channel 0's //! phase A acts on the enable it latches in that same phase, channel 1's on the //! enable from the phase A before. //! //! **Output.** [`Audio::take_samples`] returns one float per tick, the //! pads' level at phase B (where they change), so the rate is two a line, //! uneven by four colour clocks; resampling is the frontend's job. An unmodified //! console joins the two pads: a 1 kΩ pull-up (2600 schematic, sheet 1) against //! each pad's pull-downs, weighted 30k, 15k, 7.5k and 3.75k (TIA sheet 4). With //! v the sum of the two pads' levels (AUDV where the tone is high, else 0) the //! pull-downs conduct v/30k and the pin falls by v/(30 + v) of the supply. //! [`mix`] scales that to 0..1 at v = 30. **A fit**: the transistors are //! taken as ideal switches and no 2600's audio has been recorded to check it //! (docs/undocumented-behavior.md, open item 5). //! //! **No lockup guards.** The pulse counter can reach %0000 and %1010 and the //! netlist has no term to steer it away (tia-fpga): only the feedback below. In //! AUDC C-F that makes %0000 and %0001 step to %1111, which then alternates with //! %0000, a divide-by-two; the die does exactly that in the `audio` trace //! (docs/undocumented-behavior.md C26). //! //! Rust-forced differences (a2600-python `audio.py` at 28fb095): `MIX` is built //! once at first use (a `OnceLock`), the same `mix()` over every summed level. //! `on_sample` is a boxed closure given the sample only: it runs inside the //! TIA's step, so it cannot borrow the TIA to read `hclock` (a host that needs //! the instant counts samples, two a line, or keeps its own clock in a shared //! cell). It is left out of save states and of `Clone`/`PartialEq`/`Debug`, //! as the TIA's own callbacks are. use serde::{Deserialize, Serialize}; use std::sync::OnceLock; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Channel { pub same_phase: bool, pub audc: u8, pub audf: u8, pub audv: u8, pub divider: u8, pub enable: bool, pub hold: bool, pub noise: u8, // 5 bits; bit 0 is the cell that feeds out pub noise_in: bool, // the feedback latched in phase A pub noise_out: bool, // the noise register's output, latched in phase A pub pulse: u8, // 4 bits; bit 0 is the tone } impl Channel { pub fn new(same_phase: bool) -> Channel { Channel { same_phase, ..Channel::default() } } pub fn phase_a(&mut self) { let matched = self.divider == self.audf; if self.same_phase { self.enable = matched; } if self.enable { self.latch(); } if !self.same_phase { self.enable = matched; } self.divider = if matched || self.divider == 31 { 0 } else { self.divider + 1 }; } fn latch(&mut self) { let (noise, pulse, audc) = (self.noise, self.pulse, self.audc); self.noise_out = noise & 1 != 0; let mode = audc & 3; if mode == 2 { // the pulse counter steps once per 31 noise steps self.hold = (noise & 0x1E) != 0x02; } else if mode == 3 { // it steps when the 5-bit polynomial's output is 1 self.hold = noise & 1 == 0; } else { self.hold = false; } if mode == 0 { // The noise register follows the pulse counter: the low half of a // 9-bit polynomial when AUDC D3-D2 are 0 too (AUDC 0 and 8), with the // all-zeros escape both registers need to start. self.noise_in = (pulse ^ noise) & 1 != 0 || (noise == 0 && pulse == 0x0A) || audc & 0x0C == 0; } else { // a 5-bit polynomial, x^5 + x^3 + 1, which escapes all-zeros self.noise_in = ((noise >> 2) ^ noise) & 1 != 0 || noise == 0; } } pub fn phase_b(&mut self) { if !self.enable { return; } let pulse = self.pulse; let kind = self.audc >> 2; let feed = if kind == 0 { // 4-bit polynomial; AUDC 0 has no feedback and fills with ones ((pulse >> 1) ^ pulse) & 1 != 0 && self.audc & 3 != 0 } else if kind == 1 { // Johnson counter: divide by 6 (the tone of AUDC 4/5) pulse & 0x08 == 0 } else if kind == 2 { // follow the noise register (AUDC 8-B) !self.noise_out } else { // Divide by 6, from any state but %0000 and %0001: those step to // %1111 and then alternate with %0000, dividing by 2 (the die steps // %0000 to %1111 in AUDC C; tia-fpga "Audio"). pulse & 0x02 == 0 }; self.noise = (self.noise >> 1) | if self.noise_in { 0x10 } else { 0 }; if !self.hold { self.pulse = ((!pulse >> 1) & 0x07) | if feed { 0x08 } else { 0 }; } } /// The pad's weighted pull-downs: AUDV while the tone is high, else 0. pub fn level(&self) -> u8 { if self.pulse & 1 != 0 { self.audv } else { 0 } } } /// The joined pads' swing for a summed level `v` (0-30), as 0..1 (a fit). pub fn mix(v: u32) -> f64 { (2 * v) as f64 / (30 + v) as f64 } /// DOC + FITTED: mix() over every summed level. pub fn mix_table() -> &'static [f64; 31] { static MIX: OnceLock<[f64; 31]> = OnceLock::new(); MIX.get_or_init(|| std::array::from_fn(|v| mix(v as u32))) } /// `on_sample`: called with each sample as it is made. pub type SampleCallback = Box; /// Both channels; [`Audio::tick_a`] and [`Audio::tick_b`] come from the TIA's line. #[derive(Serialize, Deserialize)] pub struct Audio { pub channels: [Channel; 2], pub samples: Vec, // Called with each sample as it is made, in phase B of the tick, where // the pads change: a host mixing another sound chip at the TIA's sample // instants (the 7800's cartridge POKEY) reads its own clock there; the // TIA's ``hclock`` and the board's ``cycles`` say when. Host code, no // hardware claim. #[serde(skip)] pub on_sample: Option, } impl Clone for Audio { fn clone(&self) -> Audio { Audio { channels: self.channels.clone(), samples: self.samples.clone(), on_sample: None, } } } impl PartialEq for Audio { fn eq(&self, other: &Audio) -> bool { self.channels == other.channels && self.samples == other.samples } } impl std::fmt::Debug for Audio { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Audio") .field("channels", &self.channels) .field("samples", &self.samples) .finish() } } impl Default for Audio { fn default() -> Self { Audio::new() } } impl Audio { pub fn new() -> Audio { Audio { channels: [Channel::new(true), Channel::new(false)], samples: Vec::new(), on_sample: None, } } /// The samples since the last call, one per tick, 0..1 (see [`mix`]). pub fn take_samples(&mut self) -> Vec { std::mem::take(&mut self.samples) } /// AUDC0/1 $15/$16, AUDF0/1 $17/$18, AUDV0/1 $19/$1A. pub fn write(&mut self, address: u8, value: u8) { let i = (address.wrapping_sub(0x15) & 1) as usize; let c = &mut self.channels[i]; if address <= 0x16 { c.audc = value & 0x0F; } else if address <= 0x18 { c.audf = value & 0x1F; } else { c.audv = value & 0x0F; } } pub fn tick_a(&mut self) { for c in self.channels.iter_mut() { c.phase_a(); } } pub fn tick_b(&mut self) { let [c0, c1] = &mut self.channels; c0.phase_b(); c1.phase_b(); let sample = mix_table()[(c0.level() + c1.level()) as usize]; self.samples.push(sample); if let Some(on_sample) = self.on_sample.as_mut() { on_sample(sample); } } }