// SPDX-License-Identifier: MIT //! The AY-3-8910 programmable sound generator and its Yamaha relatives, clock by clock. //! //! Three square-wave tone channels, one noise generator, one envelope generator, a //! mixer, two 8-bit I/O ports and sixteen registers behind an address latch. The //! programmer's model is GI's data sheet and Yamaha's catalog. The timing inside the //! divider's eight is what the pins of lvd's model of deathsoft's AY-3-8910 die //! schematic show, run as a closed box by ay8910-python (`ay_ref`; its source is GPL-3.0 //! and was not read): the probes and their answers are ay8910-python's docs/rederived.md, //! and at every input clock of its referee's streams the three channels drive what that //! model drives (its docs/validation.md). What the Yamaha parts do differently is data on //! [`PSGVariant`]. //! //! The machine (ay8910-python's docs/rederived.md, items 1 and 2): //! //! * **One turn of eight internal clocks, two moments in it.** Every counter is an //! up-counter. On the strobe (`STROBE_PHASE`) each counter that may be compared //! is, and one that has reached its period (count >= period) expires: it is //! cleared and *held*. On the count (`COUNT_PHASE`, the next clock) every counter //! counts by one and every hold is let go. //! * **A held counter is not compared.** So a counter that has just expired, or come //! out of /RESET, cannot expire at the next strobe: period 0 is period 1, for the //! tones, the noise and the envelope (also the wiki's "Period 0 verification"). //! * **The strobe stays open for one more clock.** A period written after the //! strobe's clock and before the count's is compared at once, with the count the //! strobe saw. Written at any other time it waits for the next strobe. A period //! shortened under a running count therefore ends the half-cycle early, never //! wraps round (the wiki's "Phase counting verification"). //! * **The envelope's restart depends on the half of the eight.** A shape write //! before the count clears the envelope's counter and holds it; after the count it //! keeps the counter's lowest bit, clears the rest, and does not hold it. This is //! the model's behaviour measured at its pins, with no hardware statement behind //! it (ay8910-python's docs/claims.md). //! * **The noise and the envelope run at half their counter's rate.** A flip-flop //! after each counter lets the shift register step, and the AY's 16-step envelope //! move, on every second expiry. Yamaha's 32-step envelope moves on every one. //! * **The noise is a 17-bit register shifting left**, fed bit 16 XOR bit 13, or a 1 //! while it is all zero, which is how it leaves /RESET; a channel hears the //! *inverse* of bit 16. The taps are the wiki's "LFSR verification" (hardware) and //! MAME's ay8910.cpp, "verified on AY-3-8910 and YM2149 chips" (BSD-3-Clause, the //! same pair mirrored); the start and the polarity are seen at the model's pins //! (the streams `noise_sequence` and `resets`). //! //! A transcription of ay8910-python's `chip.py` (at a3bb485), method for method, in the same //! order and with the same names. Where Rust forced a difference: //! //! - **The ports' callables are state.** Python's `port_a_in` is a callable returning the //! levels the outside drives (unset: none); here [`PSG::port_a_in`] is those levels, //! `Option`, which the board sets before a read. Python's `port_a_out(value)` is a //! callable the chip calls when what it drives changes; here [`PSG::port_a_out`] is a flag //! that the board listens, and each such change is queued, as `(register, value)`, for //! [`PSG::take_port_changes`], in the order Python would have called. The same for port B. //! The chip calls, and queues, exactly where Python calls. This keeps `PSG` a plain value //! (`Clone`, comparable, and serialisable for save states) with no closures inside. //! - Python's private attributes are public fields without the underscore (`divider_count`, //! `driven`, `envelope_top`), so that a board's save state and the lockstep harness can read //! them; `_levels` is `levels_now`, beside the method [`PSG::levels`]. //! - `PSG(variant, record=False)` is [`PSG::with_record`]; [`PSG::new`] records, as Python's //! default does. //! - The three codes are an array `[u8; 3]` (Python's tuple). use crate::variants::{PSGVariant, AY8910}; /// Internal clocks per count: the chip's divide-by-eight. pub const CLOCKS_PER_STEP: u32 = 8; /// Where in the eight the strobe compares the counters and where they count, as /// clocks after /RESET is released. pub const STROBE_PHASE: u8 = 2; pub const COUNT_PHASE: u8 = 3; /// Register numbers, by GI's names (the data sheet counts them in octal, R0-R17). pub const TONE_A_FINE: u8 = 0; pub const TONE_A_COARSE: u8 = 1; pub const NOISE_PERIOD: u8 = 6; pub const MIXER: u8 = 7; pub const VOLUME_A: u8 = 8; pub const ENVELOPE_FINE: u8 = 11; pub const ENVELOPE_COARSE: u8 = 12; pub const ENVELOPE_SHAPE: u8 = 13; pub const PORT_A: u8 = 14; pub const PORT_B: u8 = 15; /// The shape register's bits. pub const HOLD: u8 = 1; pub const ALTERNATE: u8 = 2; pub const ATTACK: u8 = 4; pub const CONTINUE: u8 = 8; /// The DAC code each of channels A, B and C drives. pub type Levels = [u8; 3]; /// One chip: its pins, its sixteen registers and its five counters. /// /// `registers` holds what each register keeps of the last byte written: its /// own width on an AY, all eight bits on a Yamaha part (the engine uses only the /// bits a register has a use for). [`PSG::levels`] is the chip's digital output, /// the DAC code each channel drives this instant, and is what the referee is /// compared on. /// /// The I/O ports are pins, which the board drives and listens to: `port_a_in` is the /// levels the outside drives onto port A's pins (`None`: the chip's own pull-ups, $FF), /// and with `port_a_out` set the levels the chip drives are queued, for /// [`PSG::take_port_changes`], whenever they change (a port set to input drives /// nothing and its pull-ups read $FF). The same for port B. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct PSG { pub variant: PSGVariant, /// Queue one [`PSG::levels`] per input clock for [`PSG::take_outputs`]. A board that /// asks for [`PSG::levels`] itself after each [`PSG::tick`] passes false. pub record: bool, pub port_a_in: Option, pub port_b_in: Option, pub port_a_out: bool, pub port_b_out: bool, /// What the chip has driven on a listened port since the last /// [`PSG::take_port_changes`]: `(register, value)`, register 14 or 15. pub port_changes: Vec<(u8, u8)>, pub envelope_top: u8, /// What the chip last drove on ports A and B ($FF: an input, pulled up). pub driven: [u8; 2], pub registers: [u8; 16], /// The address latch, and whether the last address byte selected the chip. pub address: u8, pub selected: bool, /// The chip's internal data bus, which keeps its last byte as charge. pub bus: u8, /// The /SEL pin's effect: input clocks per internal clock (1 or 2). pub clock_divider: u8, pub divider_count: u8, pub phase: u8, /// Each counter has a flip-flop that an expiry sets and the count clears, and /// that holds the counter at 0 in between: `*_held`. pub tone_period: [u32; 3], pub tone_count: [u32; 3], pub tone_held: [bool; 3], pub tone_output: [u8; 3], pub noise_period: u32, pub noise_count: u32, pub noise_held: bool, pub noise_half: u8, pub noise_register: u32, pub envelope_period: u32, pub envelope_count: u32, pub envelope_held: bool, pub envelope_half: u8, pub envelope_step: u8, pub envelope_rising: bool, pub envelope_holding: bool, pub envelope_level: u8, pub clock: u64, pub outputs: Vec, pub levels_now: Levels, } impl Default for PSG { fn default() -> PSG { PSG::new(AY8910) } } /// The registers that hold a counter's period: the tones', the noise's, the envelope's. fn is_period_register(register: u8) -> bool { matches!( register, 0..=5 | NOISE_PERIOD | ENVELOPE_FINE | ENVELOPE_COARSE ) } impl PSG { /// `PSG(variant)`: a chip that queues its outputs. pub fn new(variant: PSGVariant) -> PSG { PSG::with_record(variant, true) } /// `PSG(variant, record=record)`. pub fn with_record(variant: PSGVariant, record: bool) -> PSG { let envelope_top = variant.envelope_steps - 1; let mut chip = PSG { variant, record, port_a_in: None, port_b_in: None, port_a_out: false, port_b_out: false, port_changes: Vec::new(), envelope_top, driven: [0xFF, 0xFF], registers: [0; 16], address: 0, selected: false, bus: 0, clock_divider: 1, divider_count: 0, phase: 0, tone_period: [0; 3], tone_count: [0; 3], tone_held: [true; 3], tone_output: [1; 3], noise_period: 0, noise_count: 0, noise_held: true, noise_half: 0, noise_register: 0, envelope_period: 0, envelope_count: 0, envelope_held: true, envelope_half: 0, envelope_step: 0, envelope_rising: false, envelope_holding: false, envelope_level: envelope_top, clock: 0, outputs: Vec::new(), levels_now: [0; 3], }; chip.reset(); chip } /// /RESET, as at power-on: every register 0, every counter 0, the divider at /// the start of its eight, the tones high and the noise register empty. /// /// Register 7 at 0 enables every tone and both noise and tone on each channel /// and makes both ports inputs; the volumes at 0 keep the channels silent. /// A real part powers on in no particular state; boards pulse /RESET. pub fn reset(&mut self) { self.registers = [0; 16]; self.address = 0; self.selected = false; self.bus = 0; self.clock_divider = self.variant.clock_divider; self.divider_count = 0; self.phase = 0; self.tone_period = [0, 0, 0]; self.tone_count = [0, 0, 0]; self.tone_held = [true, true, true]; self.tone_output = [1, 1, 1]; self.noise_period = 0; self.noise_count = 0; self.noise_held = true; self.noise_half = 0; self.noise_register = 0; self.envelope_period = 0; self.envelope_count = 0; self.envelope_held = true; self.envelope_half = 0; self.envelope_step = 0; self.envelope_rising = false; self.envelope_holding = false; self.envelope_level = self.envelope_top; self.clock = 0; self.outputs = Vec::new(); self.levels_now = self.mix_levels(); self.drive_port(PORT_A); self.drive_port(PORT_B); } // -- the bus ----------------------------------------------------------------------- /// Latch an address byte (BDIR and BC1 high). /// /// The low four bits name the register. The high four must be 0, the chip's /// mask-programmed address with A8 high and /A9 low: any other byte leaves the /// latch alone and deselects the chip, so the data writes and reads that /// follow do nothing (GI's data sheet, "Register Array"; the 5B's $C000 the /// same, Sunsoft_5B_audio.wiki). The address byte leaves 0 on the internal /// bus where an unused register bit would read it (ay8910-python's docs/rederived.md, /// item 3). pub fn select(&mut self, value: u8) { self.selected = (value & 0xF0) == 0; if self.selected { self.address = value & 0x0F; } self.bus = 0; } /// Write a data byte to the selected register (BDIR high, BC1 low). /// /// The registers are latches open for as long as the strobe lasts and the chip /// has no clock of its own for them: the write is taken as an instant, between /// two input clocks. Bring the chip to the moment with [`PSG::run`] first. pub fn write(&mut self, value: u8) { if self.selected { self.bus = value; self.write_selected(self.address, self.bus); } } /// Read the selected register (BDIR low, BC1 high): what the chip drives /// onto the data pins. A register's own bits are what it keeps; the bits it /// lacks are whatever the internal bus last carried ([`PSG::read_register`]). /// /// A deselected chip does not drive the data pins; this returns $FF for it, /// and a board with its own open bus checks `selected`. pub fn read(&self) -> u8 { if !self.selected { return 0xFF; } self.read_register(self.address) } /// An address byte and a data byte together: [`PSG::select`], [`PSG::write`]. pub fn write_register(&mut self, register: u8, value: u8) { self.select(register); self.write(value); } /// What a read of `register` (0-15) returns now, with the latch left as /// it is. /// /// Registers 14 and 15 are their ports' pins. Any other register gives the /// bits it keeps, and in the bits it lacks the internal bus: the last data /// byte written, or 0 if an address byte came after it. That is the die /// model's answer at its pins (ay8910-python's docs/rederived.md, item 3); the usual /// sequence, an address byte then the read, gives the 0 MAME's ay8910.cpp /// reports from a real AY-3-8910 ("inaccessible bits ... read back as 0"). pub fn read_register(&self, register: u8) -> u8 { let register = register & 0x0F; if register == PORT_A { return self.port_pins(PORT_A, self.port_a_in); } if register == PORT_B { return self.port_pins(PORT_B, self.port_b_in); } let kept = self.variant.register_masks[register as usize]; self.registers[register as usize] | (self.bus & !kept) } /// Python's `_write_register`. fn write_selected(&mut self, register: u8, value: u8) { self.registers[register as usize] = value & self.variant.register_masks[register as usize]; let registers = &self.registers; if register < NOISE_PERIOD { let channel = (register >> 1) as usize; let (fine, coarse) = (registers[channel * 2], registers[channel * 2 + 1]); self.tone_period[channel] = ((coarse & 0x0F) as u32) << 8 | fine as u32; } else if register == NOISE_PERIOD { self.noise_period = (registers[NOISE_PERIOD as usize] & 0x1F) as u32; } else if register == MIXER { self.drive_port(PORT_A); self.drive_port(PORT_B); } else if register == ENVELOPE_FINE || register == ENVELOPE_COARSE { self.envelope_period = (registers[ENVELOPE_COARSE as usize] as u32) << 8 | registers[ENVELOPE_FINE as usize] as u32; } else if register == ENVELOPE_SHAPE { self.restart_envelope(); } else if register >= PORT_A { self.drive_port(register); } if self.strobe_open() && is_period_register(register) { // Written after the strobe's clock, before the count's: compared now. self.compare(); } self.levels_now = self.mix_levels(); } // -- the ports --------------------------------------------------------------------- /// Register 7's bit 6 makes port A an output, bit 7 port B. fn port_is_output(&self, register: u8) -> bool { self.registers[MIXER as usize] & (if register == PORT_A { 0x40 } else { 0x80 }) != 0 } fn port_bonded(&self, register: u8) -> bool { self.variant .ports .contains(if register == PORT_A { 'A' } else { 'B' }) } /// The levels on a port's eight pins, which is what a read returns in /// either direction (ay8910-python's docs/rederived.md, item 4). /// /// The outside's levels, or the pull-ups' $FF with nothing driving them (GI: /// "when in the 'input' mode, all pins will read normally high"). As an /// output the chip drives its latch, and a pin the outside pulls low reads /// low (ay8910-python's phase0.md, decision 8). A port the part does not bond out has /// no outside: its pull-ups, or its latch. fn port_pins(&self, register: u8, outside: Option) -> u8 { let mut levels = 0xFF; if let Some(outside) = outside { if self.port_bonded(register) { levels = outside; } } if self.port_is_output(register) { levels &= self.registers[register as usize]; } levels } /// Tell the board what the chip now drives on a port, if that has changed. fn drive_port(&mut self, register: u8) { let port = (register - PORT_A) as usize; let value = if self.port_is_output(register) { self.registers[register as usize] } else { 0xFF }; if value != self.driven[port] { self.driven[port] = value; let out = if register == PORT_A { self.port_a_out } else { self.port_b_out }; if out && self.port_bonded(register) { self.port_changes.push((register, value)); } } } /// Return and clear what the chip has driven on the listened ports since the last /// call, in order: `(register, value)`, where Python calls `port_a_out(value)` or /// `port_b_out(value)`. pub fn take_port_changes(&mut self) -> Vec<(u8, u8)> { std::mem::take(&mut self.port_changes) } // -- time -------------------------------------------------------------------------- /// One input clock. With `clock_divider` 2 the chip moves on every second /// one (the second, the fourth, ... after /RESET). #[inline] pub fn tick(&mut self) { self.clock += 1; self.divider_count += 1; if self.divider_count >= self.clock_divider { self.divider_count = 0; let phase = self.phase; self.phase = (phase + 1) & 7; if phase == STROBE_PHASE { self.compare(); self.levels_now = self.mix_levels(); } else if phase == COUNT_PHASE { self.count(); } } if self.record { self.outputs.push(self.levels_now); } } /// `clocks` input clocks: [`PSG::tick`] that many times. pub fn run(&mut self, clocks: u64) { for _ in 0..clocks { self.tick(); } } /// Whether the clock just run was the strobe's, so that the next is the /// count's and the comparators still see a period written now. fn strobe_open(&self) -> bool { self.phase == (STROBE_PHASE + 1) & 7 } /// The strobe: every counter not held that has reached its period expires. fn compare(&mut self) { for channel in 0..3 { if !self.tone_held[channel] && self.tone_count[channel] >= self.tone_period[channel] { self.tone_count[channel] = 0; self.tone_held[channel] = true; self.tone_output[channel] ^= 1; } } if !self.noise_held && self.noise_count >= self.noise_period { self.noise_count = 0; self.noise_held = true; self.noise_half ^= 1; if self.noise_half == 0 { self.shift_noise(); } } if !self.envelope_held && self.envelope_count >= self.envelope_period { self.envelope_count = 0; self.envelope_held = true; if self.envelope_top == 15 { self.envelope_half ^= 1; if self.envelope_half != 0 { return; } } self.step_envelope(); } } /// The count: every counter goes up by one and every hold is let go. fn count(&mut self) { for channel in 0..3 { self.tone_count[channel] += 1; self.tone_held[channel] = false; } self.noise_count += 1; self.noise_held = false; self.envelope_count += 1; self.envelope_held = false; } /// One step of the 17-bit register: left, taking in bit 16 XOR bit 13, or a /// 1 while the register is all zero (as /RESET leaves it). pub fn shift_noise(&mut self) { let noise = self.noise_register; let feedback = ((noise >> 16) ^ (noise >> 13)) & 1; self.noise_register = ((noise << 1) | feedback | (noise == 0) as u32) & 0x1FFFF; } // -- the envelope ------------------------------------------------------------------ /// A write to the shape register, whatever its value: the envelope starts /// its first ramp again, rising with ATTACK, and anything holding it is let go /// (the wiki's "Envelope phase reset verification"). /// /// Its period counter (ay8910-python's docs/rederived.md, item 2): written before this /// turn's count, the counter is cleared and held until the count; written after it, /// only the counter's lowest bit is kept and nothing holds it, so the first /// step comes a count sooner when that bit was 1. fn restart_envelope(&mut self) { if self.counters_counted() { self.envelope_count &= 1; self.envelope_held = false; } else { self.envelope_count = 0; self.envelope_held = true; } self.envelope_half = 0; self.envelope_step = 0; self.envelope_holding = false; self.envelope_rising = self.registers[ENVELOPE_SHAPE as usize] & ATTACK != 0; self.ramp(); } /// Whether the divider is in the second half of its eight, the four clocks /// after the count. fn counters_counted(&self) -> bool { self.phase > COUNT_PHASE } fn ramp(&mut self) { let top = self.envelope_top; let step = self.envelope_step; self.envelope_level = if self.envelope_rising { step } else { top - step }; } /// One step along the ramp. At the end of a ramp the shape decides: without /// CONTINUE the level is 0 from then on; with HOLD it stays where the ramp /// ended, or at the other end with ALTERNATE as well; otherwise the ramp /// repeats, turned round each time with ALTERNATE. fn step_envelope(&mut self) { if self.envelope_holding { return; } self.envelope_step += 1; if self.envelope_step <= self.envelope_top { self.ramp(); return; } self.envelope_step = 0; let shape = self.registers[ENVELOPE_SHAPE as usize]; if shape & CONTINUE == 0 { self.envelope_holding = true; self.envelope_level = 0; } else if shape & HOLD != 0 { self.envelope_holding = false; let ends_high = self.envelope_rising ^ (shape & ALTERNATE != 0); self.envelope_level = if ends_high { self.envelope_top } else { 0 }; } else { if shape & ALTERNATE != 0 { self.envelope_rising = !self.envelope_rising; } self.ramp(); } } // -- the outputs ------------------------------------------------------------------- /// The DAC code of each channel: its volume, or the envelope's level, while /// (tone OR tone-disabled) AND (noise OR noise-disabled); 0 otherwise. /// /// The AY's codes are the 4-bit volume itself. Yamaha's are the 5-bit /// envelope, and a 4-bit volume `v` drives `2v + 1`. fn mix_levels(&self) -> Levels { let registers = &self.registers; let mixer = registers[MIXER as usize]; let noise = ((!self.noise_register >> 16) & 1) as u8; let wide = self.variant.envelope_steps == 32; let mut codes = [0u8; 3]; for (channel, code) in codes.iter_mut().enumerate() { let tone_gate = self.tone_output[channel] | (mixer >> channel); let noise_gate = noise | (mixer >> (channel + 3)); if tone_gate & noise_gate & 1 == 0 { *code = 0; continue; } let volume = registers[VOLUME_A as usize + channel]; *code = if volume & 0x10 != 0 { self.envelope_level } else if wide { (volume & 0x0F) * 2 + 1 } else { volume & 0x0F }; } codes } /// What channels A, B and C drive now: DAC codes, 0-15 on an AY part and /// 0-31 on a Yamaha one (`variant.dac` turns a code into a level). #[inline] pub fn levels(&self) -> Levels { self.levels_now } /// The three channels' levels added, 0.0-3.0, by the variant's DAC table: /// what three output pins tied together through equal resistors would carry. /// The pins' shared load, the filters and the amplifier are the board's. #[inline] pub fn mix(&self) -> f64 { let dac = &self.variant.dac; let [a, b, c] = self.levels_now; dac[a as usize] + dac[b as usize] + dac[c as usize] } /// Return and clear the queued outputs: one [`PSG::levels`] per input clock /// run, each the state after that clock. pub fn take_outputs(&mut self) -> Vec { std::mem::take(&mut self.outputs) } /// Return and clear the queued outputs as mixed levels, one [`PSG::mix`] per /// input clock. pub fn take_samples(&mut self) -> Vec { let outputs = self.take_outputs(); let dac = &self.variant.dac; outputs .iter() .map(|&[a, b, c]| dac[a as usize] + dac[b as usize] + dac[c as usize]) .collect() } }