//! The Namco 3-voice wavetable generator (`docs/sound-hardware.md`, "Namco //! WSG"): a 32-nibble register file, the 256-byte wave PROM, three 20-bit //! phase accumulators clocked at 96 kHz (the CPU clock / 32, so exactly //! 1,584 samples per frame), mixed as MAME mixes them. Register writes are //! applied at the sample their T-state falls in. use super::roms::RomSet; pub const SAMPLE_RATE: u32 = 96_000; pub const T_STATES_PER_SAMPLE: u64 = 32; pub const SAMPLES_PER_FRAME: usize = 1_584; /// MAME's `MIX_RES`: 128 x 3 voices. const MIX_RES: f32 = 384.0; /// The route into the speaker in galaga.cpp: 0.90 x 10/16. pub const ROUTE_GAIN: f32 = 0.5625; pub struct Wsg { wave: [i8; 256], pub regs: [u8; 0x20], pub acc: [u32; 3], } impl Wsg { pub fn new(roms: &RomSet) -> Wsg { let mut wave = [0i8; 256]; for (i, w) in wave.iter_mut().enumerate() { *w = (roms.wave[i] & 0x0f) as i8 - 8; } Wsg { wave, regs: [0; 0x20], acc: [0; 3], } } /// `pacman_sound_w`: the low nibble of a write to 0x6800 + offset. pub fn write(&mut self, offset: u8, value: u8) { self.regs[usize::from(offset & 0x1f)] = value & 0x0f; } fn voice(&self, v: usize) -> (u32, u8, usize) { let r = &self.regs; let (freq, volume) = match v { 0 => ( u32::from(r[0x10]) | u32::from(r[0x11]) << 4 | u32::from(r[0x12]) << 8 | u32::from(r[0x13]) << 12 | u32::from(r[0x14]) << 16, r[0x15], ), 1 => ( u32::from(r[0x16]) << 4 | u32::from(r[0x17]) << 8 | u32::from(r[0x18]) << 12 | u32::from(r[0x19]) << 16, r[0x1a], ), _ => ( u32::from(r[0x1b]) << 4 | u32::from(r[0x1c]) << 8 | u32::from(r[0x1d]) << 12 | u32::from(r[0x1e]) << 16, r[0x1f], ), }; let waveform = usize::from(r[0x05 + 5 * v] & 7); (freq, volume, waveform) } /// One 96 kHz sample of the three-voice mix, before the route gain: /// -0.9375..0.8203 full scale. A silent voice does not advance (MAME). #[inline] pub fn sample(&mut self) -> f32 { let mut out = 0.0f32; for v in 0..3 { let (freq, volume, waveform) = self.voice(v); if volume == 0 { continue; } self.acc[v] = (self.acc[v] + freq) & 0xf_ffff; let step = (self.acc[v] >> 15) as usize; let s = self.wave[waveform * 32 + step]; out += f32::from(s) * f32::from(volume) / MIX_RES; } out } } /// A frame's worth of samples from a machine frame: the timed register /// writes the bus logged (absolute T-state, offset, value), applied in /// order at the sample they fall in. pub fn render_frame(wsg: &mut Wsg, frame: u64, writes: &[(u64, u8, u8)], out: &mut Vec) { let base = frame * (SAMPLES_PER_FRAME as u64) * T_STATES_PER_SAMPLE; let mut next = 0; for i in 0..SAMPLES_PER_FRAME as u64 { let t = base + i * T_STATES_PER_SAMPLE; while next < writes.len() && writes[next].0 <= t { wsg.write(writes[next].1, writes[next].2); next += 1; } out.push(wsg.sample() * ROUTE_GAIN); } while next < writes.len() { wsg.write(writes[next].1, writes[next].2); next += 1; } }