// SPDX-License-Identifier: MIT //! The POKEY chip: registers, one tick per O2 period, the pins. //! //! Every rule cites its number in docs/behaviour.md, where its source and //! evidence tag are written. Modelling level: cycle. //! //! A transcription of pokey-python's `chip.py` (at 6ed1ffa): same names, same order, same //! comments (the rule numbers and evidence tags are the reference's; `docs/behaviour.md` is the //! reference's). Where Rust forced a difference: //! //! - **Wiring.** Python's callables are boxed closures. A Rust closure cannot borrow the chip //! that calls it, and the reference's `PotRC` helper reads `chip.clock` and //! `chip.dump_active` from inside `pot_level` and `on_dump`; so those two callbacks are //! handed a [`Look`] (the chip's `clock` and `dump_active` at the moment of the call, exactly //! what the Python helper would read). `key_response` and `on_irq` take what Python's take. //! `on_irq` and `on_dump` are `Option`s, as in Python (`None` when unwired). //! - **`read` takes `&mut self`**: it may call the board's `pot_level` (B5.5), which may keep //! state (as `PotRC` does). It changes nothing in the chip. //! - **`power_on(seed)`** takes `Option`; the seeded values come from //! [`crate::pyrandom`], Python's Mersenne Twister and integer seeding transcribed, so a seed //! gives the same state on both cores (negative seeds, which Python folds with `abs`, are //! not offered). //! - **State.** Python's `snapshot()` is a dict of `vars()` less `_NOT_STATE`; here it is a //! [`State`] struct with the same fields in the same order (generated with the chip's own //! field list by one macro, so the two cannot drift). `restore` takes it back. `_copy` is //! `Clone`. //! - **Types.** Python's integers are unbounded; every value here is far inside its type: //! registers and 8-bit counters `u8`, flags Python keeps as 0/1 `u8`, flags it keeps as //! `True`/`False` `bool`, the polynomial counters `u32`, `clock` `u64`, `w_reg` `i32` (-1: //! no write waiting). Python's `and`/`or` on ints used as truth values become explicit //! comparisons. `levels()` is a tuple of four `u8`; `bclk_out()` is `Option`. //! - Private methods drop Python's leading underscore (`_timers` is `timers`, `_outputs` is //! `outputs`: Rust keeps a method and the `outputs` field apart as Python's underscore did). //! - Python's `@property` pins (`sod`, `oclk`, `bclk_out`, `init_mode`) are methods. //! - The class constants are associated constants; `TAP4`, `TAP5`, `TAP17` and //! `STIMER_FF_LEAD` are `usize`/`u32` so they can index and shift. use crate::pyrandom::PyRandom; use crate::variants::{POKEYVariant, C012294}; // Write registers (DS 32) pub const AUDF1: u8 = 0; pub const AUDC1: u8 = 1; pub const AUDF2: u8 = 2; pub const AUDC2: u8 = 3; pub const AUDF3: u8 = 4; pub const AUDC3: u8 = 5; pub const AUDF4: u8 = 6; pub const AUDC4: u8 = 7; pub const AUDCTL: u8 = 8; pub const STIMER: u8 = 9; pub const SKRES: u8 = 10; pub const POTGO: u8 = 11; pub const SEROUT: u8 = 13; pub const IRQEN: u8 = 14; pub const SKCTL: u8 = 15; // Read registers (DS 32) pub const ALLPOT: u8 = 8; pub const KBCODE: u8 = 9; pub const RANDOM: u8 = 10; pub const SERIN: u8 = 13; pub const IRQST: u8 = 14; pub const SKSTAT: u8 = 15; /// What a wiring callback that needs it may read of the chip during the call (Rust-forced: /// the closure cannot borrow the chip). The values are the chip's at the moment of the call. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Look { pub clock: u64, pub dump_active: bool, } /// P0-P7: pin n above threshold. pub type PotLevel = Box bool>; /// /KR1, /KR2 for a 6-bit scan code: bit 0 = KR1 asserted, bit 1 = KR2 asserted. pub type KeyResponse = Box u8>; /// Called on each change of /IRQ. pub type OnIrq = Box; /// Called on each change of the dump transistors. pub type OnDump = Box; fn never(_n: usize, _look: Look) -> bool { false } fn no_keys(_code: u8) -> u8 { 0 } macro_rules! pokey_struct { ( wiring { $($(#[$wm:meta])* $wname:ident: $wty:ty,)* } state { $($(#[$sm:meta])* $sname:ident: $sty:ty,)* } ) => { /// Atari C012294. One `tick()` is one period of the O2 pin (B0.1). #[allow(clippy::upper_case_acronyms)] pub struct POKEY { $($(#[$wm])* pub $wname: $wty,)* $($(#[$sm])* pub $sname: $sty,)* } /// All chip state as plain values: `POKEY::snapshot()` (Python's dict, as a struct). /// Everything except the wiring (`pot_level`, `key_response`, `on_irq`, `on_dump`), /// the variant, the record flag and the recorded outputs (Python's `_NOT_STATE`). #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct State { $(pub $sname: $sty,)* } impl POKEY { fn unpowered(variant: POKEYVariant, record: bool) -> Self { POKEY { variant, record, outputs: Vec::new(), pot_level: Box::new(never), key_response: Box::new(no_keys), on_irq: None, on_dump: None, $($sname: Default::default(),)* } } // -- state ------------------------------------------------------------- /// All chip state as plain values (lists copied). pub fn snapshot(&self) -> State { State { $($sname: self.$sname.clone(),)* } } pub fn restore(&mut self, state: &State) { $(self.$sname = state.$sname.clone();)* } } }; } pokey_struct! { wiring { variant: POKEYVariant, record: bool, outputs: Vec<(u8, u8, u8, u8)>, // Pins in (handoff-brief.md, "Pins in"); consulted only when the chip looks. pot_level: PotLevel, key_response: KeyResponse, on_irq: Option, on_dump: Option, } state { sid: u8, /// B7.4: the bidirectional clock pin when it is an input bclk_in: u8, clock: u64, audf: [u8; 4], audc: [u8; 4], audctl: u8, skctl: u8, irqen: u8, /// the write waiting for the end of this cycle's tick (B0.2) w_reg: i32, w_val: u8, // interrupts (B1.4, B1.5) latched: u8, irq: bool, // serial port status (B1.6); shifters idle (decision 2) serin: u8, ser_overrun: u8, frame_error: u8, // keyboard (B1.6) kbcode: u8, kb_overrun: u8, key_held: u8, shift_latch: u8, /// B6.6 ctrl_latch: u8, /// B6.6: Break raises its interrupt on a down transition only break_prev: u8, /// B6.1, B6.2: K0-K5, held at its reset value while disabled scan_code: u8, /// B6.4: 0 key up, 1 debounce down, 3 confirmed down, 2 debounce up kb_state: u8, kb_compare: u8, // pots (B5.x): registers, the scan counter, whether a scan runs, ALLPOT, the dump state pot: [u8; 8], pot_count: u32, /// B5.7: no scan at power-on pot_scan: bool, /// what the next tick does to the counter: 0 nothing, 1 step, 2 clear pot_step: u8, allpot: u8, dump_active: bool, // clocks (B2.1): held at their reset states while in init mode c15: u8, c64: u8, /// B2.1b: init mode as the clocks see it clocks_init: bool, // timers (B2.2): counter, ticks until the scheduled fire (0 = none), fired this tick count: [u8; 4], pend: [u8; 4], fired: [bool; 4], /// B3.1 fired_prev: [bool; 4], /// bit k set: STIMER's forced reload k ticks from now (B2.4) stimer_q: u8, /// the same for a two-tone resync of timers 1+2 (B7.2) resync_q: u8, // serial pins out (B7.1, B7.4): the data bit, the output and bidirectional clocks sod_bit: u8, oclk_ff: u8, bclk_ff: u8, /// B3.2: each channel's gate for its next fire (1 = open) gate5: [u8; 4], /// B3.2: the gate as this tick's fire found it passed: [u8; 4], passed_prev: [u8; 4], // polynomial counters (B2.7): register polarity, zero after init mode poly4: u32, poly5: u32, // output stage (B3.x): distortion flip-flops, high-pass flip-flops of channels 1 and 2 ff: [u8; 4], hp: [u8; 2], stimer_set: u8, /// B3.10: AUDC writes on their way to the output stage: [ticks, channel, value] audc_q: Vec<[i32; 3]>, poly17: u32, } } impl Default for POKEY { /// `POKEY()`: the C012294 row, not recording. fn default() -> Self { POKEY::new(C012294.clone(), false) } } impl POKEY { /// B2.1: AHRM 5.2, the 15 kHz counter's reset state pub const C15_RESET: u8 = 0b0000000; /// B2.1: AHRM 5.2, the 64 kHz counter's reset state pub const C64_RESET: u8 = 0b11111; // B3.4: the stage channel 1 samples in each generator; channel k samples k-1 stages // further down (one tick later). Order DOC (AHRM 5.5); stages OBSERVED (closed box). /// the 4-bit loop's output end pub const TAP4: usize = 5; /// the 5-bit loop's output end, latched at each fire (B3.2) pub const TAP5: usize = 5; /// the bit that has just left RANDOM pub const TAP17: usize = 8; /// B3.10: ticks from an AUDC write's application to the output stage (OBSERVED) pub const AUDC_DELAY: i32 = 0; /// B3.7: STIMER sets the flip-flops this many ticks before its reload (OBSERVED) pub const STIMER_FF_LEAD: u32 = 1; /// B3.6: the copy happens in channel 3's (4's) fire tick (OBSERVED) pub const HP_LATE: bool = false; /// B3.6: of channel 1's (2's) flip-flop before this tick's clock (OBSERVED) pub const HP_OLD: bool = true; // B6.6: the codes at which /KR2 is read as Control, Shift and Break (AHRM 5.8, DOC) pub const CONTROL_CODE: u8 = 0x00; pub const SHIFT_CODE: u8 = 0x11; pub const BREAK_CODE: u8 = 0x30; pub fn new(variant: POKEYVariant, record: bool) -> Self { let mut chip = POKEY::unpowered(variant, record); // Pins in (handoff-brief.md, "Pins in"); consulted only when the chip looks. chip.sid = 1; chip.bclk_in = 1; // B7.4: the bidirectional clock pin when it is an input chip.power_on(None); chip } fn look(&self) -> Look { Look { clock: self.clock, dump_active: self.dump_active, } } // -- power-on (B1.8) ------------------------------------------------- /// Every register and counter 0 (initialisation mode), or seeded random (B1.8). pub fn power_on(&mut self, seed: Option) { let mut rnd = seed.map(PyRandom::new); let seeded = rnd.is_some(); let mut value = |bits: u32| -> u32 { match rnd.as_mut() { Some(r) => r.getrandbits(bits), None => 0, } }; self.clock = 0; self.audf = [0; 4].map(|_: u8| value(8) as u8); self.audc = [0; 4].map(|_: u8| value(8) as u8); self.audctl = value(8) as u8; self.skctl = value(8) as u8; self.irqen = value(8) as u8; self.w_reg = -1; // the write waiting for the end of this cycle's tick (B0.2) self.w_val = 0; // interrupts (B1.4, B1.5) self.latched = value(8) as u8 & self.irqen & !0x08; self.irq = false; // serial port status (B1.6); shifters idle (decision 2) self.serin = value(8) as u8; self.ser_overrun = 0; self.frame_error = 0; // keyboard (B1.6) self.kbcode = value(8) as u8; self.kb_overrun = 0; self.key_held = 0; self.shift_latch = 0; self.ctrl_latch = 0; // B6.6 self.break_prev = 0; // B6.6: Break raises its interrupt on a down transition only self.scan_code = 0x3F; // B6.1, B6.2: K0-K5, held at its reset value while disabled self.kb_state = 0; // B6.4: 0 key up, 1 debounce down, 3 confirmed down, 2 debounce up self.kb_compare = 0; // pots (B5.x): registers, the scan counter, whether a scan runs, ALLPOT, the dump state self.pot = [0; 8].map(|_: u8| value(8) as u8); self.pot_count = 0; self.pot_scan = false; // B5.7: no scan at power-on self.pot_step = 0; // what the next tick does to the counter: 0 nothing, 1 step, 2 clear self.allpot = 0; // B5.6 self.dump_active = self.skctl & 0x04 == 0; // clocks (B2.1): held at their reset states while in init mode self.c15 = if !seeded { Self::C15_RESET } else { value(7) as u8 }; self.c64 = if !seeded { Self::C64_RESET } else { value(5) as u8 }; // B2.1b: init mode as the clocks see it self.clocks_init = self.skctl & 0x03 == 0; // timers (B2.2): counter, ticks until the scheduled fire (0 = none), fired this tick self.count = [0; 4].map(|_: u8| value(8) as u8); self.pend = [0, 0, 0, 0]; self.fired = [false, false, false, false]; self.fired_prev = [false, false, false, false]; // B3.1 self.stimer_q = 0; // bit k set: STIMER's forced reload k ticks from now (B2.4) // the same for a two-tone resync of timers 1+2 (B7.2) self.resync_q = 0; // serial pins out (B7.1, B7.4): the data bit, the output and bidirectional clocks self.sod_bit = 1; self.oclk_ff = 0; self.bclk_ff = 0; self.gate5 = [1, 1, 1, 1]; // B3.2: each channel's gate for its next fire (1 = open) self.passed = [0, 0, 0, 0]; // B3.2: the gate as this tick's fire found it self.passed_prev = [0, 0, 0, 0]; // polynomial counters (B2.7): register polarity, zero after init mode self.poly4 = value(9); self.poly5 = value(10); // output stage (B3.x): distortion flip-flops, high-pass flip-flops of channels 1 and 2 self.ff = [0; 4].map(|_: u8| value(1) as u8); self.hp = [1, 1]; self.stimer_set = 0; self.audc_q = Vec::new(); // B3.10: AUDC writes on their way to the output stage self.poly17 = value(17); self.outputs = Vec::new(); self.update_irq(); } // -- the bus ----------------------------------------------------------- /// A bus write in this cycle; the chip's logic sees it from the next tick (B0.2). pub fn write(&mut self, register: u8, value: u8) { self.w_reg = (register & 0x0F) as i32; self.w_val = value; } /// A bus read in this cycle: the state the previous tick left (B0.1, B1.3). pub fn read(&mut self, register: u8) -> u8 { let register = register & 0x0F; if register < 8 { let value = self.pot[register as usize]; let step = self.pot_step; // B5.5: read while this cycle's tick changes it: the AND of before and after if step != 0 && (self.pot_scan || step == 2) && { let look = self.look(); !(self.pot_level)(register as usize, look) } { return value & (if step == 2 { 0 } else { (self.pot_count + 1) as u8 }); } return value; } if register == ALLPOT { return self.allpot; // B5.3 } if register == KBCODE { return self.kbcode; } if register == RANDOM { return (!(self.poly17 >> 9) & 0xFF) as u8; // B2.7: stages 16-9, inverted } if register == SERIN { return self.serin; } if register == IRQST { // B1.4 pending = 0; B1.5 bit 3 low while the output shifter idles (always, decision 2) return !(self.latched | 0x08); } if register == SKSTAT { return self.skstat(); } 0xFF // B1.2: $B and $C have no read register } fn skstat(&self) -> u8 { // B1.6: bits read 0 when true; bit 1 = 1 (input shifter idle); bit 0 = 1 let mut value = 0x03; value |= if self.frame_error != 0 { 0 } else { 0x80 }; value |= if self.kb_overrun != 0 { 0 } else { 0x40 }; value |= if self.ser_overrun != 0 { 0 } else { 0x20 }; value |= if self.sid != 0 { 0x10 } else { 0 }; value |= if self.shift_latch != 0 { 0 } else { 0x08 }; value |= if self.key_held != 0 { 0 } else { 0x04 }; value } // -- time -------------------------------------------------------------- /// One O2 period (B0.1): the chip's logic, then this cycle's write (B0.2). pub fn tick(&mut self) { let init = self.skctl & 0x03 == 0; // -- the two derived clocks (B2.1); they see init mode one tick late (B2.1b) -- let clocks_init = self.clocks_init; self.clocks_init = init; let p15; let p64; if clocks_init { // B2.1a: the reset value is shifted in, one bit per tick (7 and 5 ticks to reset fully) self.c15 = (self.c15 << 1) & 0x7F; self.c64 = ((self.c64 << 1) & 0x1F) | 1; p15 = false; p64 = false; } else { let c = self.c15; p15 = c == 0b1001001; let bit = if p15 { 1 } else { (((c >> 6) ^ (c >> 5)) & 1) ^ 1 }; self.c15 = ((c << 1) & 0x7F) | bit; let c = self.c64; p64 = c == 0b00010; let bit = if p64 { 1 } else { ((c >> 4) ^ (c >> 2)) & 1 }; self.c64 = ((c << 1) & 0x1F) | bit; } // -- the polynomial counters (B2.7, B2.8) -- // 4-bit loop in stages 8-5, 5-bit loop in stages 9-5; stages 4-0 carry the // delayed copies the four channels sample (B3.4, B3.2) let r = self.poly4; let fb = if init { 0 } else { ((r >> 5) ^ (r >> 6) ^ 1) & 1 }; self.poly4 = (r >> 1) | (fb << 8); let r = self.poly5; let fb = if init { 0 } else { ((r >> 5) ^ (r >> 7) ^ 1) & 1 }; self.poly5 = (r >> 1) | (fb << 9); let r = self.poly17; let fb = if init { 0 } else if self.audctl & 0x80 != 0 { // B2.9: the mode as of the end of the last tick ((r >> 8) ^ (r >> 13) ^ 1) & 1 // 9-bit } else { (r ^ (r >> 5) ^ 1) & 1 // 17-bit }; self.poly17 = (r >> 1) | (fb << 16); // -- the four timers (B2.2-B2.6) -- self.timers(if self.audctl & 0x01 != 0 { p15 } else { p64 }); // -- the output stage (B3.1-B3.7) -- self.outputs(init); if !self.audc_q.is_empty() { for entry in self.audc_q.iter_mut() { entry[0] -= 1; } while !self.audc_q.is_empty() && self.audc_q[0][0] <= 0 { let [_, ch, value] = self.audc_q.remove(0); self.audc[ch as usize] = value as u8; } } // -- the keyboard scan (B6.x) -- if self.skctl & 0x02 == 0 { self.kb_state = 0; // B6.2: forced to state 0, counter held, SKSTAT bit 2 back to 1 self.scan_code = 0x3F; self.key_held = 0; } else if p15 { self.keyboard(); } // -- the pot scan (B5.1-B5.4) -- if self.pot_scan || self.pot_step == 2 { self.pots(); } // what the next tick does to the scan counter (B5.2); a POTGO write overrides it (B5.1) if !self.pot_scan { self.pot_step = 0; } else if self.skctl & 0x04 != 0 { self.pot_step = 1; // fast scan: every tick } else { self.pot_step = if p15 { 1 } else { 0 }; // slow scan: the tick after the 15 kHz pulse } if self.w_reg >= 0 { self.apply_write(self.w_reg as u8, self.w_val); self.w_reg = -1; } self.update_irq(); // B4.2: the line settles once per tick, after the write let dump = self.skctl & 0x04 == 0 && !self.pot_scan; // B5.6 if dump != self.dump_active { self.dump_active = dump; let look = self.look(); if let Some(on_dump) = self.on_dump.as_mut() { on_dump(dump, look); } } self.clock += 1; if self.record { let levels = self.levels(); self.outputs.push(levels); } } fn timers(&mut self, base: bool) { let audctl = self.audctl; let q = self.stimer_q; let forced = q & 1; // B2.4: STIMER's reload lands in this tick self.stimer_q = q >> 1; let stimer_early = (q >> Self::STIMER_FF_LEAD) & 1; if stimer_early != 0 { self.stimer_set = 2; // B3.7: the flip-flops are held set this tick and the next } let skctl = self.skctl; let r = if skctl & 0x08 != 0 { self.resync_q } else { 0 }; // B7.2: dropped when two-tone is off let resync = r & 1; // B7.2: a two-tone resync of timers 1+2 lands in this tick self.resync_q = r >> 1; let held = skctl & 0x10; // B7.3: async receive holds timers 3+4 (no start bit is ever seen) for ch in 0..4 { let mut fire = false; if self.audc[ch] & 0x80 != 0 { self.gate5[ch] = 1; // B3.2: held open while the channel is ungated } if forced != 0 || (resync != 0 && ch < 2) || (held != 0 && ch >= 2) { self.count[ch] = self.audf[ch]; self.pend[ch] = 0; } else { if self.pend[ch] != 0 { self.pend[ch] -= 1; if self.pend[ch] == 0 { fire = true; } } // B2.5: this channel's clock input in this tick let clocked = if ch == 0 { if audctl & 0x40 == 0 { base } else { true } } else if ch == 2 { if audctl & 0x20 == 0 { base } else { true } } else if ch == 1 { if audctl & 0x10 != 0 { self.fired[0] } else { base } } else if audctl & 0x08 != 0 { self.fired[2] } else { base }; if clocked { if self.count[ch] != 0 { self.count[ch] -= 1; } else { self.count[ch] = 0xFF; // B2.2: below zero; fire three ticks later self.pend[ch] = 3; } } if fire { self.passed[ch] = self.gate5[ch]; // B3.2: this fire passes if the gate is open self.gate5[ch] = self.gate(ch); // B3.2: and the gate for the next fire is latched let low = (ch == 0 && audctl & 0x10 != 0) || (ch == 2 && audctl & 0x08 != 0); if !low { self.count[ch] = self.audf[ch]; // B2.2 reload (not the low half: B2.6) } if (ch == 1 && audctl & 0x10 != 0) || (ch == 3 && audctl & 0x08 != 0) { self.count[ch - 1] = self.audf[ch - 1]; // B2.6: the high's fire reloads both } } } self.fired[ch] = fire; } if stimer_early != 0 { // B3.2: STIMER latches the four gates with the flip-flop set (B3.7) for ch in 0..4 { self.gate5[ch] = self.gate(ch); } } let fired = self.fired; if skctl & 0x08 != 0 { // B7.2: (timer 1 AND the data bit) OR timer 2 resyncs both, two ticks after the fire let bit = self.sod_bit != 0 && skctl & 0x80 == 0; if (fired[0] && bit) || fired[1] { self.resync_q |= 0b10; } } // B7.4: the clock pins' divide-by-two flip-flops let mode = (skctl >> 4) & 7; if mode == 0 { self.oclk_ff = 0; self.bclk_ff = 0; } else { if (fired[3] && (2..=5).contains(&mode)) || (fired[1] && mode >= 6) { self.oclk_ff ^= 1; } if fired[3] && (mode == 2 || mode == 6) { self.bclk_ff ^= 1; } } // B2.3: timer interrupts 1, 2, 4 latched in the fire tick let irq = (if fired[0] { 0x01 } else { 0 }) | (if fired[1] { 0x02 } else { 0 }) | (if fired[3] { 0x04 } else { 0 }); if irq & self.irqen != 0 { // B4.1: only a source enabled during its latch tick self.latched |= irq & self.irqen; } } /// B3.2: the gate latched for the channel's next fire: open (1) or shut (0). /// /// Ungated (AUDC bit 7, counting a write made in this very cycle) it is open; /// gated it is the channel's 5-bit bit now. fn gate(&self, ch: usize) -> u8 { let control = if self.w_reg == 2 * ch as i32 + 1 { self.w_val } else { self.audc[ch] }; if control & 0x80 != 0 { return 1; } ((self.poly5 >> (Self::TAP5 - ch)) & 1) as u8 } fn outputs(&mut self, init: bool) { // B3.1: a fire clocks the output circuit in the following tick (fired_prev) let fired = self.fired_prev; let passed = self.passed_prev; let (old0, old1) = (self.ff[0], self.ff[1]); let (p4, p17) = (self.poly4, self.poly17); for ch in 0..4 { if !fired[ch] { continue; } let control = self.audc[ch]; // B3.2: the gate the fire found; open in init mode (AHRM 5.5: the 5-bit // generator is a constant 1 there) if !init && passed[ch] == 0 { continue; } if control & 0x20 != 0 { self.ff[ch] ^= 1; // B3.5: square wave } else if control & 0x40 != 0 { self.ff[ch] = ((p4 >> (Self::TAP4 - ch)) & 1) as u8; // B3.3: the 4-bit generator } else { self.ff[ch] = ((p17 >> (Self::TAP17 - ch)) & 1) as u8; // B3.3: the 9/17-bit generator } } // B3.6: the high-pass flip-flops copy channel 1 (2) when channel 3 (4) fires; forced 1 when off let audctl = self.audctl; let source = if Self::HP_LATE { fired } else { self.fired }; if audctl & 0x04 == 0 { self.hp[0] = 1; } else if source[2] { self.hp[0] = if Self::HP_OLD { old0 } else { self.ff[0] }; } if audctl & 0x02 == 0 { self.hp[1] = 1; } else if source[3] { self.hp[1] = if Self::HP_OLD { old1 } else { self.ff[1] }; } if self.stimer_set != 0 { // B3.7: STIMER holds the four flip-flops at 1 in ticks T+2 and T+3 self.stimer_set -= 1; // (after each tick's clocks, so a clock in either is lost) self.ff = [1, 1, 1, 1]; } self.fired_prev = self.fired; self.passed_prev = self.passed; } fn keyboard(&mut self) { let code = (self.scan_code + 1) & 0x3F; // B6.1: step, then check the new code self.scan_code = code; let response = (self.key_response)(code); // B6.3: bit 0 /KR1, bit 1 /KR2 let down = response & 1; let kr2 = (response >> 1) & 1; // B6.6: the modifier line at $00 (Control), $10 (Shift), $30 (Break), debounce or not if code == Self::CONTROL_CODE { self.ctrl_latch = kr2; } else if code == Self::SHIFT_CODE { self.shift_latch = kr2; } else if code == Self::BREAK_CODE { if kr2 != 0 && self.break_prev == 0 && self.irqen & 0x80 != 0 { self.latched |= 0x80; // B6.6, B4.1 } self.break_prev = kr2; } // B6.4: the state machine let matched = code == self.kb_compare || self.skctl & 0x01 == 0; let state = self.kb_state; if state == 0 { if down != 0 { self.kb_compare = code; self.kb_state = 1; } } else if state == 1 { if matched && down != 0 { if self.irqen & 0x40 != 0 { if self.latched & 0x40 != 0 { self.kb_overrun = 1; // B6.5 } self.latched |= 0x40; } self.kbcode = code | self.shift_latch << 6 | self.ctrl_latch << 7; self.key_held = 1; self.kb_state = 3; } else if matched || down != 0 { self.kb_state = 0; // match and up, or another key down } } else if state == 3 { if matched && down == 0 { self.kb_state = 2; } } else if matched { // state 2 if down != 0 { self.kb_state = 3; // B6.4 (HYPOTHESIS) } else { self.key_held = 0; self.kb_state = 0; } } } fn pots(&mut self) { let step = self.pot_step; let mut ending = false; if step == 2 { // B5.1: POTGO clears the counter in the tick after its write self.pot_count = 0; self.pot_scan = true; } else { ending = self.pot_count == 228; // B5.4: the tick that begins at 228 ends the scan if step != 0 { self.pot_count += 1; // B5.2 } } let count = self.pot_count; let look = self.look(); let mut allpot = 0; for n in 0..8 { // B5.3: every pin, every tick of a scan if !(self.pot_level)(n, look) { self.pot[n] = count as u8; allpot |= 1 << n; } } if ending { self.pot_scan = false; allpot = 0; // B5.4: forced to $00 } self.allpot = allpot; } pub fn run(&mut self, cycles: u64) { for _ in 0..cycles { self.tick(); } } fn apply_write(&mut self, register: u8, value: u8) { if register < 8 { if register & 1 != 0 { if Self::AUDC_DELAY != 0 { // B3.10 self.audc_q .push([Self::AUDC_DELAY, (register >> 1) as i32, value as i32]); } else { self.audc[(register >> 1) as usize] = value; } } else { self.audf[(register >> 1) as usize] = value; } } else if register == AUDCTL { self.audctl = value; } else if register == STIMER { self.stimer_q |= 0b100; // B2.4: the forced reload lands in tick T+3 } else if register == POTGO { self.pot_step = 2; // B5.1: the next tick clears the counter and starts a scan } else if register == SKRES { // B1.6: any write sets the three status latches back to 1 self.frame_error = 0; self.kb_overrun = 0; self.ser_overrun = 0; } else if register == IRQEN { self.irqen = value; // B4.1: at the end of this tick, enabling and disabling alike self.latched &= value; // B1.4: a disabled source is locked at 1 } else if register == SKCTL { self.skctl = value; } } // -- pins out ---------------------------------------------------------- /// B7.1: the serial data out pin: the held bit, 0 while force break (SKCTL bit 7) is set. pub fn sod(&self) -> u8 { if self.skctl & 0x80 != 0 { 0 } else { self.sod_bit } } /// B7.4: the output clock pin: its flip-flop, or the external clock in modes 000 and 001. pub fn oclk(&self) -> u8 { if (self.skctl >> 4) & 7 >= 2 { self.oclk_ff } else { self.bclk_in } } /// B7.4: the bidirectional clock when the chip drives it (modes 010, 110), else None. pub fn bclk_out(&self) -> Option { if matches!((self.skctl >> 4) & 7, 2 | 6) { Some(self.bclk_ff) } else { None } } /// SKCTL bits 1-0 both 0 (B1.7). pub fn init_mode(&self) -> bool { self.skctl & 0x03 == 0 } fn update_irq(&mut self) { // B1.4, B1.5: latched sources, plus bit 3 (idle shifter) while enabled let level = self.latched != 0 || self.irqen & 0x08 != 0; if level != self.irq { self.irq = level; if let Some(on_irq) = self.on_irq.as_mut() { on_irq(level); } } } /// The four channel codes: volume if the channel's output is 1, else 0 (B3.8). pub fn levels(&self) -> (u8, u8, u8, u8) { let (ff, hp) = (&self.ff, &self.hp); let [a, b, c, d] = self.audc; // B3.6: channels 1 and 2 pass through the high-pass XOR; B3.8: volume-only after it let o1 = if a & 0x10 != 0 { 1 } else { ff[0] ^ hp[0] }; let o2 = if b & 0x10 != 0 { 1 } else { ff[1] ^ hp[1] }; let o3 = if c & 0x10 != 0 { 1 } else { ff[2] }; let o4 = if d & 0x10 != 0 { 1 } else { ff[3] }; ( if o1 != 0 { a & 15 } else { 0 }, if o2 != 0 { b & 15 } else { 0 }, if o3 != 0 { c & 15 } else { 0 }, if o4 != 0 { d & 15 } else { 0 }, ) } /// The four codes through the variant's output curve, 0.0-1.0 (B3.9). pub fn mix(&self) -> f64 { let dac = &self.variant.dac; let mut total = 0.0; let (a, b, c, d) = self.levels(); for level in [a, b, c, d] { total += dac[level as usize]; } self.variant.mix_curve[(total * 4.0 + 0.5) as usize] } /// With `record=true`: one `levels()` tuple per tick since the last call. pub fn take_outputs(&mut self) -> Vec<(u8, u8, u8, u8)> { std::mem::take(&mut self.outputs) } }