//! The sound generator: three tone channels and a noise channel behind one write port. //! //! Every rule names where it comes from. "spec 5.1" is a section of sn76489-python's //! `docs/spec.md`, which names the document behind it (TI's and Sega's manuals, Maxim's SMS //! Power page, John Kortink's BBC Micro capture); U and C numbers are that document's //! unknowns and contradictions, D numbers the decisions in its `docs/handoff-brief.md`. //! A rule no source supports says CHOICE; one taken by decision says PROVISIONAL. //! //! What differs between the four parts is data on [`PSGVariant`] (`variants.rs`). Nothing //! here asks which variant it is running. //! //! The chip divides its input clock by 16 (spec 4.1). One *tick* is 16 input clocks, //! and nothing inside the chip changes between ticks, so the core produces one output //! level per tick (spec 4.3, a choice that follows). Filtering, resampling, a //! console's sag and a mono speaker are the board's (spec 7.7, 9.3). //! //! A transcription of sn76489-python's `src/sn76489_python/chip.py` at f8157f4: same names, //! same order, same comments. Where Rust forced a difference: //! //! - State is `pub` fields of fixed-size arrays and integers where Python has attributes and //! lists; `samples` is a `Vec` of `(left, right)` pairs. Integers are `u32` (the clock //! remainder `u64`): none of the registers or counters comes near either width. //! - Python's keyword arguments become two constructors: `SN76489::new(variant)` and //! `SN76489::with_silent_start(variant, silent_start)`; `reset(silent_start)` takes the flag //! positionally. `SN76489::default()` is Python's `SN76489()`, the Master System's part. //! - `write`, `write_stereo` and `write_test` take a `u32` and mask it as Python does; a //! negative Python int has no counterpart. //! - `run` takes a `u64`. Python's `run` accepts a negative count (it returns at once when the //! ticks come to zero or fewer, after changing `clock_remainder`); a `u64` cannot be negative. //! - `write_test` on a part without the register returns `Err(NoTestRegister)` where Python //! raises `AttributeError`, and changes nothing, as Python's raise does. //! - In `run`, Python's `bit_count()` is `count_ones()`, and its generator expressions over the //! four channels are written out; the sums are added in the same order, so every level is the //! same `f64`. //! //! Save states (not in sn76489-python, whose boards walk the attributes): with the `serde` //! feature `SN76489` is `Serialize`/`Deserialize`, every field included (the variant with all //! its fields and its part's name). use crate::variants::{PSGVariant, SEGA_VDP_PSG}; /// Input clocks per tick and per output level: the chip's divide-by-16 (spec 4.1, /// documented: TI's data sheet, "decremented at a N/16 rate"). pub const CLOCKS_PER_SAMPLE: u64 = 16; /// What `write_test` returns on a part without the Mega Drive's test register: Python's /// `AttributeError`, with its message. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct NoTestRegister(pub &'static str); impl std::fmt::Display for NoTestRegister { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} has no test register (spec section 11)", self.0) } } impl std::error::Error for NoTestRegister {} /// One chip. All state is plain fields (numbers and arrays), named here. /// /// `tone`: the three 10-bit tone values. `noise`: the 3-bit noise control (bit /// 2 white, bits 1-0 the rate). `volume`: four 4-bit attenuations, the fourth /// the noise channel's. `stereo`: the Game Gear's port $06, $FF elsewhere. /// `latched`: the register code (spec 2.2) the last latch byte chose. /// `counters`, `outputs`: each tone generator's down counter and flip-flop. /// `noise_counter`, `noise_input`: the fixed-rate noise divider and its /// flip-flop. `lfsr`: the noise shift register, output end at bit 0. `test`: /// the Mega Drive's three test bits. `clock_remainder`: input clocks not yet /// making a tick. `samples`: levels produced and not yet taken. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SN76489 { pub variant: PSGVariant, pub tone: [u32; 3], pub noise: u32, pub volume: [u32; 4], pub stereo: u32, pub latched: u32, pub counters: [u32; 3], pub outputs: [u32; 3], pub noise_counter: u32, pub noise_input: u32, pub lfsr: u32, pub test: u32, pub clock_remainder: u64, pub samples: Vec<(f64, f64)>, } impl Default for SN76489 { fn default() -> Self { SN76489::new(SEGA_VDP_PSG) } } impl SN76489 { pub fn new(variant: PSGVariant) -> Self { SN76489::with_silent_start(variant, false) } pub fn with_silent_start(variant: PSGVariant, silent_start: bool) -> Self { let mut chip = SN76489 { variant, tone: [0; 3], noise: 0, volume: [0; 4], stereo: 0, latched: 0, counters: [0; 3], outputs: [0; 3], noise_counter: 0, noise_input: 0, lfsr: 0, test: 0, clock_remainder: 0, samples: Vec::new(), }; chip.reset(silent_start); chip } /// Power-on, as far as any source describes it (spec section 10). /// /// `silent_start` starts every channel at attenuation 15 whatever the part /// does. It is for a board that does not want the unreset TI chip's power-on /// tone (D5); it changes nothing on Sega's parts, which start silent. pub fn reset(&mut self, silent_start: bool) { let variant = self.variant; // Tone and noise registers 0: documented at tier 3 for Sega's parts (spec // 10.2). On the TI chip, which is not reset at all (spec 10.4), zero is // MAME's rendering of "a medium volume tone": PROVISIONAL (D5, U13). self.tone = [0, 0, 0]; self.noise = 0; self.volume = [if silent_start { 15 } else { variant.power_on_attenuation }; 4]; // "After a power-on reset" every stereo bit is 1 (spec 9.2, Sega's manual). self.stereo = 0xFF; self.latched = variant.power_on_latch; // No source says where the counters, flip-flops, divider and shift register // stand at power-on (spec 10.6, U10). CHOICE, the seed's: counters at zero, // tone flip-flops set, so each falls on the first tick; the shift register // as a noise write leaves it; the divide-by-16 at the start of its cycle. // The seed's value for the flip-flops was kept after a closed-box model // of the Mega Drive's part was seen to start in that phase // (docs/validation.md, rung 5). That is a model's opinion, not evidence. self.counters = [0, 0, 0]; self.outputs = [1, 1, 1]; self.noise_counter = 0; self.noise_input = 0; self.lfsr = 1 << (variant.lfsr_bits - 1); self.test = 0; self.clock_remainder = 0; self.samples = Vec::new(); } // -- the write port ---------------------------------------------------------- /// One byte to the chip's only port (spec section 3). /// /// A write takes effect at once, at whatever point of the 16-clock tick it /// arrives; the next level produced shows it. When within the tick a real /// write lands is unknown (spec 3.9, U9): CHOICE. pub fn write(&mut self, value: u32) { let value = value & 0xFF; if value & 0x80 != 0 { // A latch byte: bits 6-4 choose the register and stay chosen until the // next latch byte (spec 3.1; register codes, spec 2.2). self.latched = (value >> 4) & 7; } else if (self.latched & 1 != 0 || self.latched == 6) && !self.variant.data_byte_reaches_all_registers { // A data byte while an attenuation or the noise register is latched // writes its low bits there, as a latch byte would (spec 3.6), on the // parts where it does anything at all. return; } let register = self.latched; let channel = (register >> 1) as usize; if register & 1 != 0 { // Attenuation: all four bits, from either kind of byte (spec 3.3, 3.6). self.volume[channel] = value & 0x0F; } else if channel == 3 { // Noise control: feedback bit 2 and rate bits 1-0; bit 3 is ignored // (spec 3.4). self.noise = value & 0x07; // Every write to it clears the shift register and leaves one bit set at // the input end, even a write of the value already there (spec 3.7, // 6.4.1, 6.4.2). The output is the register's last stage (see `run`), // so it reads 0 from this moment: CHOICE (spec 6.4.4, U7). The rate // divider is not restarted: CHOICE (spec 6.4.5, U7). self.lfsr = 1 << (self.variant.lfsr_bits - 1); } else if value & 0x80 != 0 { // A latch byte replaces the low 4 bits of the tone value and leaves the // high 6; the value in use changes at once (spec 3.2). self.tone[channel] = (self.tone[channel] & 0x3F0) | (value & 0x0F); } else { // A data byte replaces the high 6 bits; bit 6 is ignored (spec 3.5). self.tone[channel] = (self.tone[channel] & 0x00F) | ((value & 0x3F) << 4); } } /// The Game Gear's port $06 (spec 9.1): bits 7-4 put the noise and tones 2, /// 1, 0 on the left, bits 3-0 the same on the right. On a part without the /// register this does nothing (spec 9.4, a CHOICE carried from the seed). pub fn write_stereo(&mut self, value: u32) { if self.variant.stereo { self.stereo = value & 0xFF; } } /// The Mega Drive's VDP debug register 0, of which bits 11-9 are the PSG's. /// /// PROVISIONAL and untested (D7; spec section 11, U15). The only source is one /// paragraph on Plutiedev: "When bit 9 is clear, PSG works as normal. When it's /// set, however, all PSG channels get replaced with the volume level of one of /// them. Bits 11-10 pick which channel is the source of the volume level." /// That is taken literally in [`SN76489::run`]. The override exists only on the /// Mega Drive's part: on the others there is nothing to write, and the call /// fails as a missing attribute does. pub fn write_test(&mut self, value: u32) -> Result<(), NoTestRegister> { if !self.variant.test_override { return Err(NoTestRegister(self.variant.name)); } self.test = (value >> 9) & 7; Ok(()) } // -- time -------------------------------------------------------------------- /// Advance by `clocks` input clocks, appending one level pair per tick. // Python's `if counter0: counter0 -= 1` is kept as written rather than as // `saturating_sub`, so that the counters read as the reference's do. #[allow(clippy::implicit_saturating_sub)] pub fn run(&mut self, clocks: u64) { let total = self.clock_remainder + clocks; let ticks = total / CLOCKS_PER_SAMPLE; self.clock_remainder = total % CLOCKS_PER_SAMPLE; if ticks == 0 { return; } let variant = self.variant; // A tone value of n toggles the output every n ticks (spec 5.1, 5.2); 1 // toggles every tick (spec 5.5, C1); what 0 stands for is the variant's // (spec 5.6, 5.7: PROVISIONAL). The registers cannot change inside this // call, so they are read once. let zero = variant.tone_zero_period; let or_zero = |value: u32| if value != 0 { value } else { zero }; let period0 = or_zero(self.tone[0]); let period1 = or_zero(self.tone[1]); let period2 = or_zero(self.tone[2]); let [mut counter0, mut counter1, mut counter2] = self.counters; let [mut output0, mut output1, mut output2] = self.outputs; // Noise rates 0 to 2 shift every 32, 64 or 128 ticks: a divider reloaded // with $10, $20 or $40 whose flip-flop shifts the register when it rises // (spec 6.1.1, 6.1.2). Rate 3 takes the third tone generator's output as the // shift clock instead (spec 6.1.3, C4). let rate = self.noise & 3; let follows_tone = rate == 3; let noise_period = 0x10 << rate; let shift_level = variant.noise_shift_level; let mut noise_counter = self.noise_counter; let mut noise_input = self.noise_input; // White noise feeds back the exclusive OR of the tapped stages; "periodic" // noise feeds the leaving bit back unchanged, a tap on bit 0 alone (spec // 6.2.2 to 6.2.4). let taps = if self.noise & 4 != 0 { variant.white_noise_taps } else { 0x0001 }; let top = variant.lfsr_bits - 1; let mut lfsr = self.lfsr; // Each channel adds its level when its bit is 1 and nothing when it is 0 // (spec 7.5), to the sides the stereo register allows (spec 9.1). let table = &variant.volume_table; let mut levels = self.volume.map(|attenuation| table[attenuation as usize]); // The Mega Drive's test override (spec section 11, PROVISIONAL): with its // enable bit set, every channel's output is replaced by the volume level of // the chosen channel. Read literally, the square waves and noise no longer // reach the output; they keep running underneath (CHOICE, U15). let overridden = self.test & 1; if overridden != 0 { levels = [levels[((self.test >> 1) & 3) as usize]; 4]; } let stereo = self.stereo; let side = |shift: u32| -> [f64; 4] { std::array::from_fn(|channel| { if stereo & (shift << channel) != 0 { levels[channel] } else { 0.0 } }) }; let [left0, left1, left2, left3] = side(0x10); let [right0, right1, right2, right3] = side(0x01); let held = ( left0 + left1 + left2 + left3, right0 + right1 + right2 + right3, ); let samples = &mut self.samples; samples.reserve(ticks as usize); for _ in 0..ticks { // Tone generators (spec 5.1): the counter counts down once a tick; at // zero the flip-flop toggles and the counter is loaded again from the // register. A new value therefore waits for the next reload (spec 5.4, // U11). if counter0 != 0 { counter0 -= 1; } if counter0 == 0 { counter0 = period0; output0 ^= 1; } if counter1 != 0 { counter1 -= 1; } if counter1 == 0 { counter1 = period1; output1 ^= 1; } let mut shift = false; if counter2 != 0 { counter2 -= 1; } if counter2 == 0 { counter2 = period2; output2 ^= 1; // Rate 3: one shift for every full cycle of this output. shift = follows_tone && output2 == shift_level; } if !follows_tone { // The fixed-rate divider. While rate 3 is chosen it stands still and // picks up where it stopped: CHOICE, no source describes it. if noise_counter != 0 { noise_counter -= 1; } if noise_counter == 0 { noise_counter = noise_period; noise_input ^= 1; shift = noise_input == 1; } } if shift { lfsr = (lfsr >> 1) | (((lfsr & taps).count_ones() & 1) << top); } if overridden != 0 { samples.push(held); } else { // The noise channel's bit is the stage at the output end of the // register (spec 6.2.5; Kortink: the generator's output is bit 0 of // the new value; Maxim: "Output=ShiftRegister&1"). let noise_bit = lfsr & 1; samples.push(( (if output0 != 0 { left0 } else { 0.0 }) + (if output1 != 0 { left1 } else { 0.0 }) + (if output2 != 0 { left2 } else { 0.0 }) + (if noise_bit != 0 { left3 } else { 0.0 }), (if output0 != 0 { right0 } else { 0.0 }) + (if output1 != 0 { right1 } else { 0.0 }) + (if output2 != 0 { right2 } else { 0.0 }) + (if noise_bit != 0 { right3 } else { 0.0 }), )); } } self.counters = [counter0, counter1, counter2]; self.outputs = [output0, output1, output2]; self.noise_counter = noise_counter; self.noise_input = noise_input; self.lfsr = lfsr; } /// Return and clear the levels produced since the last call: one `(left, /// right)` pair per tick, each from 0.0 to 4.0 (four channels at full volume). pub fn take_samples(&mut self) -> Vec<(f64, f64)> { std::mem::take(&mut self.samples) } }