// SPDX-License-Identifier: MIT //! Mikey: timers, interrupts, the cart address lines, display registers, palette, //! UART and audio registers. Imports nothing from the board (a recorded bus trace can //! drive it alone) (`mikey/__init__.py`). //! //! Register map and reset values: DOC Appx 2 ("Mikey Addresses") unless tagged. //! //! Differences forced by Rust: the Python Mikey holds references to the cart port and to //! the board's RAM (display DMA reads it: the bus is the channel); here the board owns //! both and passes them to the calls that use them (`cart`, `ram`). The timer bank's //! `on_borrow` callback is a queue drained by [`Mikey::drain_borrows`] (see //! `mikey::timers`). The UART is always present (Python's `uart is not None` tests are //! always true and are dropped). `samples` (an `array('h')` once recording) is an //! `Option>`. pub mod display; pub mod timers; pub mod uart; use serde::{Deserialize, Serialize}; use crate::cart::port::CartPort; use display::{Display, MikeyLines}; use timers::TimerBank; use uart::Uart; /// Mikey registers backed by the timer/audio dual-ported RAM (DOC Spec §4: "addressed in a /// cyclical manner", latency up to its 1.25 µs cycle = 20 ticks). pub const DPRAM_END: u16 = 0xFD40; /// Audio samples: one every 500 ticks = 32,000 Hz exactly (a host choice, not hardware; /// the hardware's own output filter is a one-pole low pass near 4 kHz, DOC Spec §7). pub const SAMPLE_TICKS: i64 = 500; pub const SAMPLE_RATE: i64 = 16_000_000 / SAMPLE_TICKS; #[derive(Clone, Serialize, Deserialize)] pub struct Mikey { pub atten: [u8; 5], pub audio_in: u8, pub audio_regs: [u8; 32], pub dispadr: u32, pub dispctl: u8, pub display: Display, pub external_power: u8, pub iodat: u8, pub iodir: u8, pub mstereo: u8, pub next_sample: i64, pub nibble_defect: bool, pub no_expansion: u8, pub now: i64, pub palette: [u8; 32], pub pbkup: u8, pub samples: Option>, pub sdone_pending: u8, pub serctl: u8, pub serdat: u8, pub stereo: bool, pub sysctl1: u8, pub timers: TimerBank, pub uart: Uart, } impl Mikey { pub fn new(stereo: bool) -> Mikey { Mikey { stereo, timers: TimerBank::new(), display: Display::new(), sysctl1: 0b10, // DOC reset x,x,x,x,x,x,1,0: power on, strobe low iodir: 0, // DOC reset 0 iodat: 0, // DOC reset value not given for IODAT itself: HYPOTHESIS 0 serctl: 0, serdat: 0, dispctl: 0, // DOC reset 0: video DMA disabled pbkup: 0, dispadr: 0, palette: [0; 32], // $FDA0-$FDBF: green, then blue|red mstereo: 0, // DOC reset 0 (Lynx II) // $FD40-$FD43 ATTEN, $FD44 MPAN (Lynx II); reset values unknown (U11): HYPOTHESIS 0 // (MPAN 0: no attenuation applied, every channel heard). atten: [0; 5], samples: None, // left, right pairs once start_audio is called next_sample: 0, nibble_defect: false, audio_regs: [0; 32], // $FD20-$FD3F as stored bytes (M6 adds the LFSR) sdone_pending: 0, uart: Uart::new(), // The display reads RAM by DMA: the bus is the channel (the board passes ``ram``). // Input lines read through IODAT (DOC Appx 2 IODAT; values HYPOTHESIS, U17): audio_in: 1, external_power: 0, no_expansion: 1, now: 0, } } // -- time -------------------------------------------------------------------------- pub fn run_until(&mut self, tick: i64, ram: &[u8]) { if self.samples.is_some() { // Sample the mix on the tick line: each sample sees every event at or // before its tick (the order of record), none after. while self.next_sample <= tick { self.timers.run_until(self.next_sample); self.drain_borrows(ram); let (left, right) = self.mix(); let samples = self.samples.as_mut().unwrap(); samples.push(left); samples.push(right); self.next_sample += SAMPLE_TICKS; } } self.timers.run_until(tick); self.drain_borrows(ram); if !self.uart.arriving.is_empty() { self.uart.run_until(tick, &mut self.timers.pending); } self.now = tick; } /// The timer bank's borrows since the last drain, handled in order (the reference's /// `on_borrow` calls; see `mikey::timers`). pub fn drain_borrows(&mut self, ram: &[u8]) { if self.timers.borrows.is_empty() { return; } let borrows = std::mem::take(&mut self.timers.borrows); for &(index, when) in &borrows { self.borrow(index, when, ram); } let mut borrows = borrows; borrows.clear(); if self.timers.borrows.is_empty() { self.timers.borrows = borrows; // keep the allocation } } fn borrow(&mut self, index: usize, when: i64, ram: &[u8]) { if index == 0 { let timer0 = &self.timers.timers[0]; let lines = MikeyLines { dispadr: self.dispadr, dispctl: self.dispctl, timer0_backup: timer0.backup, timer0_period: timer0.period(), ram, palette: &self.palette, }; self.display.line_borrow(when, &lines); } else if index == 2 { self.display .frame_borrow(when, self.timers.timers[2].backup); } else if index == 4 { self.uart.clock(when, &mut self.timers.pending); } else if index >= 8 { self.audio_clock(index - 8); } } /// One borrow of an audio channel's timer clocks its polynomial counter. /// /// DOC Spec §7 (lynx7) and Appx 2 FD20-FD27: a 12-bit shift register; the taps /// enabled by FEEDBACK B0-B5 (bits 0-5), B6 (bit 10), B7 (bit 11) and CTLA B7 /// (bit 7) are exclusive-ored and the inversion is shifted in at bit 0; bit 0 /// selects +VOLUME or its two's complement. In integrate mode (CTLA B5) that is /// added to OUTPUT, clipped rather than wrapped (HYPOTHESIS: at the signed limits /// $7F/$80; Appx 2 writes "(ff,00)"). fn audio_clock(&mut self, channel: usize) { let regs = &mut self.audio_regs; let base = channel * 8; let mut shift = regs[base + 3] as u32 | (((regs[base + 7] >> 4) as u32) << 8); let feedback = regs[base + 1] as u32; let mut taps = (feedback & 0x3F) | ((feedback & 0x40) << 4) | ((feedback & 0x80) << 4); taps |= (regs[base + 5] & 0x80) as u32; let parity = (shift & taps).count_ones() & 1; let bit = parity ^ 1; shift = ((shift << 1) | bit) & 0xFFF; regs[base + 3] = (shift & 0xFF) as u8; regs[base + 7] = (regs[base + 7] & 0x0F) | (((shift >> 8) << 4) as u8); let volume = regs[base] as i8 as i32; let mut step = if bit != 0 { volume } else { -volume }; if regs[base + 5] & 0x20 != 0 { let output = regs[base + 2] as i8 as i32; step = (-128).max(127.min(output + step)); } regs[base + 2] = (step & 0xFF) as u8; } // -- the audio mix --------------------------------------------------------------------- /// Begin recording 16-bit stereo samples every `SAMPLE_TICKS` from `now`. pub fn start_audio(&mut self, now: i64) { self.samples = Some(Vec::new()); self.next_sample = now; } /// The four channels' outputs as the DAC sees them, left and right, 16-bit. /// /// DOC Spec §7: "the 4 signals are digitally mixed" into one pulse-width /// modulated output; Lynx I's earphone jack "outputs the mono sound on both /// channels". Lynx II (C8): DOC Appx 2 MSTEREO ($FD50): a 1 disables channel c /// (bit 4 + c left, bit c right). DOC (cc65 `asminc/lynx.inc`, zlib: names and /// masks only): ATTENREG0-3 ($FD40-$FD43) hold a left attenuation in the high /// nibble and a right one in the low nibble; MPAN ($FD44) has the same bit layout /// as MSTEREO. HYPOTHESIS: an MPAN bit set applies that side's attenuation, as /// a fraction n/15 (42Bastian's lniccc2000 player, Apache-2.0, writes $FF to MPAN /// with the comment "all channels off" while ATTEN is still at its reset value, /// taken here as 0; U11). No test ROM covers the mix. /// /// The low-nibble PWM defect (DOC §7 "Bug in the lower nybble") is an option, /// `nibble_defect`, off by default: each channel's value with bit 3 inverted /// (HYPOTHESIS: where in the chain it sits). pub fn mix(&self) -> (i16, i16) { let regs = &self.audio_regs; let (mut left, mut right) = (0i32, 0i32); let stereo = self.stereo; let (mute, pan, atten) = (self.mstereo, self.atten[4], &self.atten); for c in 0..4 { let mut out = regs[c * 8 + 2]; if self.nibble_defect { out ^= 0x08; } let value = out as i8 as i32; if !stereo { left += value; continue; } // Python's // is floor division: div_euclid by a positive divisor. if mute & (0x10 << c) == 0 { left += if pan & (0x10 << c) != 0 { (value * (atten[c] >> 4) as i32).div_euclid(15) } else { value }; } if mute & (1 << c) == 0 { right += if pan & (1 << c) != 0 { (value * (atten[c] & 0x0F) as i32).div_euclid(15) } else { value }; } } if !stereo { right = left; } ((left * 64) as i16, (right * 64) as i16) // four signed bytes span -512..508: 16 bits } // -- interrupts -------------------------------------------------------------------- /// INTSET as read: the timers' bits and the UART's bit 4 (set by its level). pub fn irq_bits(&self) -> u32 { self.timers.pending } // -- cart address lines -------------------------------------------------------------- fn cart_lines(&self, cart: &mut CartPort) { // DOC Appx 2 IODAT B1 = Cart Address Data (an output when IODIR B1 = 1). // HYPOTHESIS: as an input the line floats high. let data = if self.iodir & 0x02 != 0 { (self.iodat >> 1) & 1 } else { 1 }; cart.set_data(data); // AUDIN as an output (IODIR B4) drives the cart's AUDIN pin (M7 banking). cart.set_audin(if self.iodir & 0x10 != 0 { (self.iodat >> 4) & 1 } else { 1 }); } // -- registers --------------------------------------------------------------------- pub fn read(&mut self, address: u16, cart: &CartPort) -> u8 { let reg = (address & 0xFF) as u8; if reg < 0x20 { return self.timers.read((reg >> 2) as usize, reg & 3, self.now); } if reg < 0x40 { return self.audio_read((reg - 0x20) as usize); } if (0x40..=0x44).contains(®) { return if self.stereo { self.atten[(reg - 0x40) as usize] } else { 0 }; } if reg == 0x50 { return if self.stereo { self.mstereo } else { 0 }; } if reg == 0x80 || reg == 0x81 { return self.irq_bits() as u8; // DOC: a read of either is a poll } if reg == 0x86 { return self.audio_in << 7; // DOC: B7 = audio-in comparator } if reg == 0x88 { return 0x01; // DOC MIKEYHREV = '01' } if reg == 0x8B { return self.read_iodat(cart); } if reg == 0x8C { return self.uart.read_serctl(); } if reg == 0x8D { return self.uart.read_serdat(); } if reg >= 0xA0 { return self.palette[(reg - 0xA0) as usize]; } // HYPOTHESIS (U18): write-only and unallocated addresses read 0. 0 } pub fn read_iodat(&self, cart: &CartPort) -> u8 { // DOC Appx 2: "only the lines that are set to input are actually valid for // reading"; Spec §16 "IODAT is not really a R/W register". HYPOTHESIS (U17): // output lines read back what was written; inputs read their pins. // AUDIN as an input reads the cart's pin: an EEPROM's DO, else the pull-up. let audin = cart.audin_pin() & self.audio_in; let pins = (audin << 4) | (self.no_expansion << 2) | self.external_power; (self.iodat & self.iodir) | (pins & !self.iodir) } pub fn write(&mut self, address: u16, value: u8, cart: &mut CartPort, ram: &[u8]) { let reg = (address & 0xFF) as u8; let now = self.now; if reg < 0x20 { self.timers.write((reg >> 2) as usize, reg & 3, value, now); self.drain_borrows(ram); } else if reg < 0x40 { self.audio_write((reg - 0x20) as usize, value, ram); } else if (0x40..=0x44).contains(®) { if self.stereo { self.atten[(reg - 0x40) as usize] = value; } } else if reg == 0x50 { if self.stereo { self.mstereo = value; } } else if reg == 0x80 { self.timers.pending &= !(value as u32); // DOC INTRST: write resets the set bits self.uart.set_level(&mut self.timers.pending); // DOC §11: a level; it sets bit 4 again while it holds } else if reg == 0x81 { self.timers.pending |= (value & 0xEF) as u32; // DOC INTSET (bit 4 is the UART's level) } else if reg == 0x87 { self.sysctl1 = value; cart.set_strobe(value & 1); // DOC B0 = Cart Address Strobe } else if reg == 0x8A { self.iodir = value; self.cart_lines(cart); } else if reg == 0x8B { self.iodat = value; self.cart_lines(cart); } else if reg == 0x8C { self.uart.write_serctl(value, now, &mut self.timers.pending); } else if reg == 0x8D { self.uart.write_serdat(value, now, &mut self.timers.pending); } else if reg == 0x92 { self.dispctl = value; } else if reg == 0x93 { self.pbkup = value; } else if reg == 0x94 { self.dispadr = (self.dispadr & 0xFF00) | (value & 0xFC) as u32; // DOC: bottom 2 bits ignored } else if reg == 0x95 { self.dispadr = ((value as u32) << 8) | (self.dispadr & 0xFF); } else if reg >= 0xA0 { // TEST ROM memio 1: green ($FDA0-$FDAF) keeps the low nibble only (a write // of $FF reads back $0F); blue/red ($FDB0-$FDBF) keep all 8 bits. self.palette[(reg - 0xA0) as usize] = if reg < 0xB0 { value & 0x0F } else { value }; } } // -- audio registers (stored; milestone 6 gives them their channels) ------------------ pub fn audio_read(&self, offset: usize) -> u8 { let (channel, reg) = (offset >> 3, offset & 7); let timer = &self.timers.timers[8 + channel]; if reg == 4 { return timer.backup; } if reg == 5 { return (self.audio_regs[offset] & 0x80) | (timer.ctla & 0x7F); } if reg == 6 { return timer.count; } if reg == 7 { return (self.audio_regs[offset] & 0xF0) | (timer.ctlb(self.now) & 0x0F); } self.audio_regs[offset] } pub fn audio_write(&mut self, offset: usize, value: u8, ram: &[u8]) { let (channel, reg) = (offset >> 3, offset & 7); let timer_index = 8 + channel; self.audio_regs[offset] = value; if reg == 4 { self.timers.write(timer_index, 0, value, self.now); } else if reg == 5 { // DOC Appx 2 FD25: B7 = feedback bit 7, B6 reset done, B5 integrate, B4 reload, // B3 count, B2-0 clock select: the timer half has no interrupt enable. self.timers.write(timer_index, 1, value & 0x7F, self.now); } else if reg == 6 { self.timers.write(timer_index, 2, value, self.now); } else if reg == 7 { self.timers.write(timer_index, 3, value & 0x0F, self.now); } self.drain_borrows(ram); } }