//! Galaxian's discrete sound board, transcribed from galemu's `synth.py`: //! a deterministic signal-level approximation of the four 555 stages, the //! pitch divider, the noise LFSR, and the FIRE and HIT envelopes, one frame //! of 792 PCM16 samples at 48 kHz per board frame. The arithmetic is kept in //! the reference's order so the samples match it. use super::board::Event; use super::bytes::{Reader, Writer}; pub const SAMPLE_RATE: f64 = 48_000.0; pub const SAMPLES_PER_FRAME: usize = 792; const PITCH_CLOCK: f64 = 1_536_000.0; const NOISE_CLOCK: f64 = 7_920.0; const TTL_HIGH: f64 = 4.0; const SUPPLY_555: f64 = 5.0; const DIODE_PEAK: f64 = TTL_HIGH - 0.5; const BG_DAC_BIT_SIEMENS: [f64; 4] = [ 1.0 / 1_000_000.0, 1.0 / 470_000.0, 1.0 / 220_000.0, 1.0 / 100_000.0, ]; const BG_DAC_BIAS_SIEMENS: f64 = 1.0 / 15_000.0; const BG_DAC_GROUND_SIEMENS: f64 = 1.0 / 330_000.0; const BG_DAC_BIAS_VOLTS: f64 = 4.4; const BG_LFO_JUNCTION_VOLTS: f64 = 0.7; const BG_LFO_CURRENT_OHMS: f64 = 100_000.0; const BG_LFO_RAMP_VOLTS: f64 = SUPPLY_555 / 3.0; const BG_LFO_CAPACITOR_FARADS: f64 = 1e-6; const BG_TONE_CHARGE_RC: [f64; 3] = [5.7e-3, 4.3e-3, 3.2e-3]; const BG_TONE_LEVEL: f64 = 3_400.0; const FIRE_CHARGE_RC: f64 = (10_000.0 + 22_000.0) * 0.01e-6; const FIRE_CONTROL_SWEEP_WEIGHT: f64 = 10_000.0 / (10_000.0 + 2_200.0); const FIRE_CONTROL_NOISE_VOLTS: f64 = TTL_HIGH * 2_200.0 / (10_000.0 + 2_200.0); const FIRE_COUPLING_ALPHA: f64 = 2.2e-5 / (2.2e-5 + 1.0 / SAMPLE_RATE); const FIRE_MIX_GAIN: f64 = 3_000.0; const HIT_FILTER_DAMPING: f64 = 0.404; const HIT_MIX_GAIN: f64 = 7_000.0; /// Constants the reference computes with `log`/`exp` at import time. struct Derived { bg_control_floor: f64, bg_control_span: f64, bg_tone_discharge_seconds: [f64; 3], bg_mix_lpf_alpha: f64, fire_discharge_seconds: f64, fire_sweep_alpha: f64, fire_release_decay: f64, hit_release_decay: f64, hit_filter_gain: f64, } fn derived() -> Derived { let ln2 = std::f64::consts::LN_2; let pi = std::f64::consts::PI; let bg_control_gain = 10_000.0 / (1.0 / (1.0 / 47_000.0 + 1.0 / 47_000.0 + 1.0 / 10_000.0)); Derived { bg_control_floor: bg_control_gain * SUPPLY_555 / 3.0 - SUPPLY_555 * 10_000.0 / 47_000.0, bg_control_span: bg_control_gain * SUPPLY_555 / 3.0, bg_tone_discharge_seconds: [ln2 * 4.7e-3, ln2 * 3.3e-3, ln2 * 2.2e-3], bg_mix_lpf_alpha: 1.0 - (-2.0 * pi * 477.5 / SAMPLE_RATE).exp(), fire_discharge_seconds: ln2 * 22_000.0 * 0.01e-6, fire_sweep_alpha: 1.0 - (-1.0 / (SAMPLE_RATE * 2_200.0 * 47e-6)).exp(), fire_release_decay: (-1.0 / (SAMPLE_RATE * 100_000.0 * 1e-6)).exp(), hit_release_decay: (-1.0 / (SAMPLE_RATE * 172_000.0 * 2.2e-6)).exp(), hit_filter_gain: 2.0 * pi * 168.0 / SAMPLE_RATE, } } /// One decoded sound write (`devices.decode_sound_write`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SoundEvent { pub kind: &'static str, pub value: u8, pub channel: Option, } /// galemu's `decode_sound_write`, with the channel the synthesizer needs. pub fn decode_sound_event(address: u16, value: u8) -> Option { if address & 0xF800 == 0x7800 { return Some(SoundEvent { kind: "sound_pitch", value, channel: None, }); } let canonical = address & 0xF807; let bit = value & 1; let event = |kind, channel| { Some(SoundEvent { kind, value: bit, channel, }) }; match canonical { 0x6004..=0x6007 => event( "sound_background_resistor", Some(usize::from(canonical - 0x6004)), ), 0x6800..=0x6802 => event("sound_tone_enable", Some(usize::from(canonical - 0x6800))), 0x6803 => event("sound_hit", None), 0x6804 => event("sound_unused", None), 0x6805 => event("sound_fire", None), 0x6806..=0x6807 => event("sound_volume", Some(usize::from(canonical - 0x6806))), _ => None, } } /// The sound writes among a frame's board events, as the display extracts them. pub fn sound_events(events: &[Event]) -> Vec { events .iter() .filter(|e| e.value <= 0xFF) .filter_map(|e| decode_sound_event(e.address, e.value as u8)) .collect() } /// galemu's `SoundState`: latches, phases and filter state across frames. #[derive(Clone, Debug, PartialEq)] pub struct SoundState { pub pitch: u8, pub background: [bool; 4], pub tones: [bool; 3], pub volume: [bool; 2], pub fire_gate: bool, pub hit_gate: bool, pub sample_position: u64, noise_lfsr: u32, noise_phase: f64, lfo_phase: f64, tone_phases: [f64; 3], background_lowpass: f64, pitch_phase: f64, divider_count: u32, fire_sweep: f64, fire_phase: f64, fire_charge: f64, fire_coupling_in: f64, fire_coupling_out: f64, hit_charge: f64, hit_lowpass: f64, hit_bandpass: f64, } impl Default for SoundState { fn default() -> Self { SoundState { pitch: 0xFF, background: [false; 4], tones: [false; 3], volume: [false; 2], fire_gate: false, hit_gate: false, sample_position: 0, noise_lfsr: 0, noise_phase: 0.0, lfo_phase: 0.0, tone_phases: [0.0; 3], background_lowpass: 0.0, pitch_phase: 0.0, divider_count: 0, fire_sweep: TTL_HIGH, fire_phase: 0.0, fire_charge: 0.0, fire_coupling_in: 0.0, fire_coupling_out: 0.0, hit_charge: 0.0, hit_lowpass: 0.0, hit_bandpass: 0.0, } } } impl SoundState { /// The state as bytes, every field in declaration order (`f64` by its /// bits, so exactly), for a save state; [`SoundState::read`] gives it /// back. The synthesis is not touched. pub fn write(&self, w: &mut Writer) { w.u8(self.pitch); for &v in self.background.iter().chain(&self.tones).chain(&self.volume) { w.bool(v); } w.bool(self.fire_gate); w.bool(self.hit_gate); w.u64(self.sample_position); w.u32(self.noise_lfsr); w.f64(self.noise_phase); w.f64(self.lfo_phase); for &v in &self.tone_phases { w.f64(v); } w.f64(self.background_lowpass); w.f64(self.pitch_phase); w.u32(self.divider_count); for v in [ self.fire_sweep, self.fire_phase, self.fire_charge, self.fire_coupling_in, self.fire_coupling_out, self.hit_charge, self.hit_lowpass, self.hit_bandpass, ] { w.f64(v); } } pub fn read(r: &mut Reader) -> Result { let pitch = r.u8()?; let background = [r.bool()?, r.bool()?, r.bool()?, r.bool()?]; let tones = [r.bool()?, r.bool()?, r.bool()?]; let volume = [r.bool()?, r.bool()?]; Ok(SoundState { pitch, background, tones, volume, fire_gate: r.bool()?, hit_gate: r.bool()?, sample_position: r.u64()?, noise_lfsr: r.u32()?, noise_phase: r.f64()?, lfo_phase: r.f64()?, tone_phases: [r.f64()?, r.f64()?, r.f64()?], background_lowpass: r.f64()?, pitch_phase: r.f64()?, divider_count: r.u32()?, fire_sweep: r.f64()?, fire_phase: r.f64()?, fire_charge: r.f64()?, fire_coupling_in: r.f64()?, fire_coupling_out: r.f64()?, hit_charge: r.f64()?, hit_lowpass: r.f64()?, hit_bandpass: r.f64()?, }) } fn apply_events(&mut self, events: &[SoundEvent]) { for event in events { match (event.kind, event.channel) { ("sound_pitch", _) => self.pitch = event.value, ("sound_background_resistor", Some(c)) => self.background[c] = event.value != 0, ("sound_tone_enable", Some(c)) => self.tones[c] = event.value != 0, ("sound_volume", Some(c)) => self.volume[c] = event.value != 0, ("sound_fire", _) => self.fire_gate = event.value != 0, ("sound_hit", _) => self.hit_gate = event.value != 0, _ => {} } } } /// Apply one frame's writes and synthesize exactly 792 samples into `out`. pub fn synthesize_frame(&mut self, events: &[SoundEvent], out: &mut [i16; SAMPLES_PER_FRAME]) { let d = derived(); self.apply_events(events); let lfo_rate = lfo_rate(&self.background); let fire_sweep_target = if self.fire_gate { 0.0 } else { TTL_HIGH }; for sample_out in out.iter_mut() { self.lfo_phase = (self.lfo_phase + lfo_rate / SAMPLE_RATE) % 1.0; let control = d.bg_control_floor + d.bg_control_span * self.lfo_phase; let tone_log = ((SUPPLY_555 - control / 2.0) / (SUPPLY_555 - control)).ln(); let mut tone_mix = 0.0; let mut sample = 0.0; #[allow(clippy::needless_range_loop)] // the reference indexes three arrays by channel for channel in 0..3 { let charge_seconds = BG_TONE_CHARGE_RC[channel] * tone_log; let period_seconds = charge_seconds + d.bg_tone_discharge_seconds[channel]; self.tone_phases[channel] = (self.tone_phases[channel] + 1.0 / (period_seconds * SAMPLE_RATE)) % 1.0; if self.tones[channel] { let duty = charge_seconds / period_seconds; let centered = if self.tone_phases[channel] < duty { 1.0 - duty } else { -duty }; tone_mix += BG_TONE_LEVEL * centered; } } self.background_lowpass += (tone_mix - self.background_lowpass) * d.bg_mix_lpf_alpha; sample += self.background_lowpass; if self.pitch != 0xFF { self.pitch_phase += PITCH_CLOCK / ((256.0 - f64::from(self.pitch)) * SAMPLE_RATE); let advances = self.pitch_phase as u32; if advances != 0 { self.divider_count = (self.divider_count + advances) & 0x0F; self.pitch_phase -= f64::from(advances); } sample += pitch_mixer(self.divider_count, &self.volume); } self.noise_phase += NOISE_CLOCK / SAMPLE_RATE; if self.noise_phase >= 1.0 { let steps = self.noise_phase as u32; self.noise_phase -= f64::from(steps); for _ in 0..steps { self.noise_lfsr = advance_noise(self.noise_lfsr); } } let noise_high = self.noise_lfsr & 1 != 0; self.fire_sweep += (fire_sweep_target - self.fire_sweep) * d.fire_sweep_alpha; let mut control = FIRE_CONTROL_SWEEP_WEIGHT * self.fire_sweep; if noise_high { control += FIRE_CONTROL_NOISE_VOLTS; } let charge_seconds = FIRE_CHARGE_RC * ((SUPPLY_555 - control / 2.0) / (SUPPLY_555 - control)).ln(); let period_seconds = charge_seconds + d.fire_discharge_seconds; let phase_step = 1.0 / (period_seconds * SAMPLE_RATE); let duty = charge_seconds / period_seconds; let mut next_phase = self.fire_phase + phase_step; let high_span = if next_phase < 1.0 { (next_phase.min(duty) - self.fire_phase).max(0.0) } else { next_phase -= 1.0; (duty - self.fire_phase).max(0.0) + next_phase.min(duty) }; self.fire_phase = next_phase; self.fire_charge = if self.fire_gate { DIODE_PEAK } else { self.fire_charge * d.fire_release_decay }; let fire_level = self.fire_charge * high_span / phase_step; self.fire_coupling_out = FIRE_COUPLING_ALPHA * (self.fire_coupling_out + fire_level - self.fire_coupling_in); self.fire_coupling_in = fire_level; sample += self.fire_coupling_out * FIRE_MIX_GAIN; self.hit_charge = if self.hit_gate { DIODE_PEAK } else { self.hit_charge * d.hit_release_decay }; let hit_level = if noise_high { self.hit_charge } else { 0.0 }; self.hit_lowpass += d.hit_filter_gain * self.hit_bandpass; self.hit_bandpass += d.hit_filter_gain * (hit_level - self.hit_lowpass - HIT_FILTER_DAMPING * self.hit_bandpass); sample += self.hit_bandpass * HIT_MIX_GAIN; *sample_out = clamp_pcm(sample); } self.sample_position += SAMPLES_PER_FRAME as u64; } } fn pitch_mixer(counter: u32, volume: &[bool; 2]) -> f64 { let mut signal = if counter & 0x01 != 0 { 1_000.0 } else { -1_000.0 }; signal += if counter & 0x04 != 0 { 1_500.0 } else { -1_500.0 }; if volume[0] { signal += if counter & 0x04 != 0 { 3_300.0 } else { -3_300.0 }; } if volume[1] { signal += if counter & 0x08 != 0 { 2_200.0 } else { -2_200.0 }; } signal } fn lfo_rate(background: &[bool; 4]) -> f64 { let mut source = BG_DAC_BIAS_VOLTS * BG_DAC_BIAS_SIEMENS; let mut total = BG_DAC_BIAS_SIEMENS + BG_DAC_GROUND_SIEMENS; for (conductance, enabled) in BG_DAC_BIT_SIEMENS.iter().zip(background) { total += conductance; if *enabled { source += TTL_HIGH * conductance; } } let dac_volts = source / total; let ramp_amps = (SUPPLY_555 - dac_volts - BG_LFO_JUNCTION_VOLTS) / BG_LFO_CURRENT_OHMS; ramp_amps / (BG_LFO_CAPACITOR_FARADS * BG_LFO_RAMP_VOLTS) } fn advance_noise(seed: u32) -> u32 { let feedback = ((seed >> 4) ^ (seed >> 16) ^ 1) & 1; ((seed << 1) | feedback) & 0x1FFFF } /// Python's `round` is half-to-even. fn clamp_pcm(value: f64) -> i16 { value.round_ties_even().clamp(-32_768.0, 32_767.0) as i16 }