# 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. """ from __future__ import annotations import random from collections.abc import Callable from .variants import C012294, POKEYVariant # Write registers (DS 32) AUDF1, AUDC1, AUDF2, AUDC2, AUDF3, AUDC3, AUDF4, AUDC4 = range(8) AUDCTL, STIMER, SKRES, POTGO, SEROUT, IRQEN, SKCTL = 8, 9, 10, 11, 13, 14, 15 # Read registers (DS 32) ALLPOT, KBCODE, RANDOM, SERIN, IRQST, SKSTAT = 8, 9, 10, 13, 14, 15 #: Attributes that are wiring or host options, not chip state. _NOT_STATE = frozenset( ("variant", "record", "outputs", "pot_level", "key_response", "on_irq", "on_dump") ) def _copy(value): """Plain values copied, lists (and lists of lists) copied deeply.""" if isinstance(value, list): return [_copy(item) for item in value] return value def _never(_n: int) -> bool: return False def _no_keys(_code: int) -> int: return 0 class POKEY: """Atari C012294. One ``tick()`` is one period of the O2 pin (B0.1).""" C15_RESET = 0b0000000 # B2.1: AHRM 5.2, the 15 kHz counter's reset state C64_RESET = 0b11111 # B2.1: AHRM 5.2, the 64 kHz counter's reset state # 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). TAP4 = 5 # the 4-bit loop's output end TAP5 = 5 # the 5-bit loop's output end, latched at each fire (B3.2) TAP17 = 8 # the bit that has just left RANDOM AUDC_DELAY = 0 # B3.10: ticks from an AUDC write's application to the output stage (OBSERVED) STIMER_FF_LEAD = 1 # B3.7: STIMER sets the flip-flops this many ticks before its reload (OBSERVED) HP_LATE = False # B3.6: the copy happens in channel 3's (4's) fire tick (OBSERVED) HP_OLD = True # B3.6: of channel 1's (2's) flip-flop before this tick's clock (OBSERVED) # B6.6: the codes at which /KR2 is read as Control, Shift and Break (AHRM 5.8, DOC) CONTROL_CODE = 0x00 SHIFT_CODE = 0x10 BREAK_CODE = 0x30 def __init__(self, variant: POKEYVariant = C012294, record: bool = False) -> None: self.variant = variant self.record = record # Pins in (handoff-brief.md, "Pins in"); consulted only when the chip looks. self.pot_level: Callable[[int], bool] = _never self.key_response: Callable[[int], int] = _no_keys self.sid = 1 self.bclk_in = 1 # B7.4: the bidirectional clock pin when it is an input self.on_irq: Callable[[bool], None] | None = None self.on_dump: Callable[[bool], None] | None = None self.power_on() # -- power-on (B1.8) ------------------------------------------------- def power_on(self, seed: int | None = None) -> None: """Every register and counter 0 (initialisation mode), or seeded random (B1.8).""" rnd = random.Random(seed) if seed is not None else None def value(bits: int) -> int: return rnd.getrandbits(bits) if rnd else 0 self.clock = 0 self.audf = [value(8) for _ in range(4)] self.audc = [value(8) for _ in range(4)] self.audctl = value(8) self.skctl = value(8) self.irqen = value(8) 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) & self.irqen & ~0x08 self.irq = False # serial port status (B1.6); shifters idle (decision 2) self.serin = value(8) self.ser_overrun = 0 self.frame_error = 0 # keyboard (B1.6) self.kbcode = value(8) 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 = [value(8) for _ in range(8)] 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 self.dump_active = not self.skctl & 0x04 # B5.6 # clocks (B2.1): held at their reset states while in init mode self.c15 = self.C15_RESET if not rnd else value(7) self.c64 = self.C64_RESET if not rnd else value(5) self.clocks_init = not self.skctl & 0x03 # B2.1b: init mode as the clocks see it # timers (B2.2): counter, ticks until the scheduled fire (0 = none), fired this tick self.count = [value(8) for _ in range(4)] 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) self.resync_q = 0 # the same for a two-tone resync of timers 1+2 (B7.2) # 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 = [value(1) for _ in range(4)] self.hp = [1, 1] self.stimer_set = 0 self.audc_q: list[list[int]] = [] # B3.10: AUDC writes on their way to the output stage self.poly17 = value(17) self.outputs: list[tuple[int, int, int, int]] = [] self._update_irq() # -- the bus ----------------------------------------------------------- def write(self, register: int, value: int) -> None: """A bus write in this cycle; the chip's logic sees it from the next tick (B0.2).""" self.w_reg = register & 0x0F self.w_val = value & 0xFF def read(self, register: int) -> int: """A bus read in this cycle: the state the previous tick left (B0.1, B1.3).""" register &= 0x0F if register < 8: value = self.pot[register] step = self.pot_step # B5.5: read while this cycle's tick changes it: the AND of before and after if step and (self.pot_scan or step == 2) and not self.pot_level(register): return value & (0 if step == 2 else self.pot_count + 1) return value if register == ALLPOT: return self.allpot # B5.3 if register == KBCODE: return self.kbcode if register == RANDOM: return ~(self.poly17 >> 9) & 0xFF # 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) & 0xFF if register == SKSTAT: return self._skstat() return 0xFF # B1.2: $B and $C have no read register def _skstat(self) -> int: # B1.6: bits read 0 when true; bit 1 = 1 (input shifter idle); bit 0 = 1 value = 0x03 value |= 0 if self.frame_error else 0x80 value |= 0 if self.kb_overrun else 0x40 value |= 0 if self.ser_overrun else 0x20 value |= 0x10 if self.sid else 0 value |= 0 if self.shift_latch else 0x08 value |= 0 if self.key_held else 0x04 return value # -- time -------------------------------------------------------------- def tick(self) -> None: """One O2 period (B0.1): the chip's logic, then this cycle's write (B0.2).""" init = not self.skctl & 0x03 # -- the two derived clocks (B2.1); they see init mode one tick late (B2.1b) -- clocks_init = self.clocks_init self.clocks_init = init 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 = p64 = False else: c = self.c15 p15 = c == 0b1001001 bit = 1 if p15 else (((c >> 6) ^ (c >> 5)) & 1) ^ 1 self.c15 = ((c << 1) & 0x7F) | bit c = self.c64 p64 = c == 0b00010 bit = 1 if p64 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) r = self.poly4 fb = 0 if init else ((r >> 5) ^ (r >> 6) ^ 1) & 1 self.poly4 = (r >> 1) | (fb << 8) r = self.poly5 fb = 0 if init else ((r >> 5) ^ (r >> 7) ^ 1) & 1 self.poly5 = (r >> 1) | (fb << 9) r = self.poly17 if init: fb = 0 elif self.audctl & 0x80: # B2.9: the mode as of the end of the last tick fb = ((r >> 8) ^ (r >> 13) ^ 1) & 1 # 9-bit else: fb = (r ^ (r >> 5) ^ 1) & 1 # 17-bit self.poly17 = (r >> 1) | (fb << 16) # -- the four timers (B2.2-B2.6) -- self._timers(p15 if self.audctl & 0x01 else p64) # -- the output stage (B3.1-B3.7) -- self._outputs(init) if self.audc_q: for entry in self.audc_q: entry[0] -= 1 while self.audc_q and self.audc_q[0][0] <= 0: _, ch, value = self.audc_q.pop(0) self.audc[ch] = value # -- the keyboard scan (B6.x) -- if not self.skctl & 0x02: 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 elif p15: self._keyboard() # -- the pot scan (B5.1-B5.4) -- if self.pot_scan or 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 not self.pot_scan: self.pot_step = 0 elif self.skctl & 0x04: self.pot_step = 1 # fast scan: every tick else: self.pot_step = 1 if p15 else 0 # slow scan: the tick after the 15 kHz pulse if self.w_reg >= 0: self._apply_write(self.w_reg, self.w_val) self.w_reg = -1 self._update_irq() # B4.2: the line settles once per tick, after the write dump = not self.skctl & 0x04 and not self.pot_scan # B5.6 if dump != self.dump_active: self.dump_active = dump if self.on_dump is not None: self.on_dump(dump) self.clock += 1 if self.record: self.outputs.append(self.levels()) def _timers(self, base: bool) -> None: audctl = self.audctl count, pend, fired, audf = self.count, self.pend, self.fired, self.audf gate, passed = self.gate5, self.passed q = self.stimer_q forced = q & 1 # B2.4: STIMER's reload lands in this tick self.stimer_q = q >> 1 stimer_early = (q >> self.STIMER_FF_LEAD) & 1 if stimer_early: self.stimer_set = 2 # B3.7: the flip-flops are held set this tick and the next audc = self.audc skctl = self.skctl r = self.resync_q if skctl & 0x08 else 0 # B7.2: dropped when two-tone is off resync = r & 1 # B7.2: a two-tone resync of timers 1+2 lands in this tick self.resync_q = r >> 1 held = skctl & 0x10 # B7.3: async receive holds timers 3+4 (no start bit is ever seen) for ch in range(4): fire = False if audc[ch] & 0x80: gate[ch] = 1 # B3.2: held open while the channel is ungated if forced or (resync and ch < 2) or (held and ch >= 2): count[ch] = audf[ch] pend[ch] = 0 else: if pend[ch]: pend[ch] -= 1 if not pend[ch]: fire = True # B2.5: this channel's clock input in this tick if ch == 0: clocked = base if not audctl & 0x40 else True elif ch == 2: clocked = base if not audctl & 0x20 else True elif ch == 1: clocked = fired[0] if audctl & 0x10 else base else: clocked = fired[2] if audctl & 0x08 else base if clocked: if count[ch]: count[ch] -= 1 else: count[ch] = 0xFF # B2.2: below zero; fire three ticks later pend[ch] = 3 if fire: passed[ch] = gate[ch] # B3.2: this fire passes if the gate is open gate[ch] = self._gate(ch) # B3.2: and the gate for the next fire is latched low = (ch == 0 and audctl & 0x10) or (ch == 2 and audctl & 0x08) if not low: count[ch] = audf[ch] # B2.2 reload (not the low half: B2.6) if (ch == 1 and audctl & 0x10) or (ch == 3 and audctl & 0x08): count[ch - 1] = audf[ch - 1] # B2.6: the high's fire reloads both fired[ch] = fire if stimer_early: # B3.2: STIMER latches the four gates with the flip-flop set (B3.7) for ch in range(4): gate[ch] = self._gate(ch) if skctl & 0x08: # B7.2: (timer 1 AND the data bit) OR timer 2 resyncs both, two ticks after the fire bit = self.sod_bit and not skctl & 0x80 if (fired[0] and bit) or fired[1]: self.resync_q |= 0b10 # B7.4: the clock pins' divide-by-two flip-flops mode = (skctl >> 4) & 7 if mode == 0: self.oclk_ff = self.bclk_ff = 0 else: if (fired[3] and 2 <= mode <= 5) or (fired[1] and mode >= 6): self.oclk_ff ^= 1 if fired[3] and mode in (2, 6): self.bclk_ff ^= 1 # B2.3: timer interrupts 1, 2, 4 latched in the fire tick irq = (fired[0] and 0x01) | (fired[1] and 0x02) | (fired[3] and 0x04) if irq & self.irqen: # B4.1: only a source enabled during its latch tick self.latched |= irq & self.irqen def _gate(self, ch: int) -> int: """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. """ control = self.w_val if self.w_reg == 2 * ch + 1 else self.audc[ch] if control & 0x80: return 1 return (self.poly5 >> (self.TAP5 - ch)) & 1 def _outputs(self, init: bool) -> None: # B3.1: a fire clocks the output circuit in the following tick (fired_prev) ff, fired, audc, passed = self.ff, self.fired_prev, self.audc, self.passed_prev old0, old1 = ff[0], ff[1] p4, p17 = self.poly4, self.poly17 for ch in range(4): if not fired[ch]: continue control = 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 not init and not passed[ch]: continue if control & 0x20: ff[ch] ^= 1 # B3.5: square wave elif control & 0x40: ff[ch] = (p4 >> (self.TAP4 - ch)) & 1 # B3.3: the 4-bit generator else: ff[ch] = (p17 >> (self.TAP17 - ch)) & 1 # 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 audctl = self.audctl hp = self.hp source = fired if self.HP_LATE else self.fired if not audctl & 0x04: hp[0] = 1 elif source[2]: hp[0] = old0 if self.HP_OLD else ff[0] if not audctl & 0x02: hp[1] = 1 elif source[3]: hp[1] = old1 if self.HP_OLD else ff[1] if self.stimer_set: # 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) ff[0] = ff[1] = ff[2] = ff[3] = 1 self.fired_prev = list(self.fired) self.passed_prev = list(self.passed) def _keyboard(self) -> None: code = (self.scan_code + 1) & 0x3F # B6.1: step, then check the new code self.scan_code = code response = self.key_response(code) # B6.3: bit 0 /KR1, bit 1 /KR2 down = response & 1 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 elif code == self.SHIFT_CODE: self.shift_latch = kr2 elif code == self.BREAK_CODE: if kr2 and not self.break_prev and self.irqen & 0x80: self.latched |= 0x80 # B6.6, B4.1 self.break_prev = kr2 # B6.4: the state machine match = code == self.kb_compare or not self.skctl & 0x01 state = self.kb_state if state == 0: if down: self.kb_compare = code self.kb_state = 1 elif state == 1: if match and down: if self.irqen & 0x40: if self.latched & 0x40: 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 elif match or down: self.kb_state = 0 # match and up, or another key down elif state == 3: if match and not down: self.kb_state = 2 elif match: # state 2 if down: self.kb_state = 3 # B6.4 (HYPOTHESIS) else: self.key_held = 0 self.kb_state = 0 def _pots(self) -> None: step = self.pot_step 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: self.pot_count += 1 # B5.2 count = self.pot_count level = self.pot_level pot = self.pot allpot = 0 for n in range(8): # B5.3: every pin, every tick of a scan if not level(n): pot[n] = count allpot |= 1 << n if ending: self.pot_scan = False allpot = 0 # B5.4: forced to $00 self.allpot = allpot def run(self, cycles: int) -> None: for _ in range(cycles): self.tick() def _apply_write(self, register: int, value: int) -> None: if register < 8: if register & 1: if self.AUDC_DELAY: self.audc_q.append([self.AUDC_DELAY, register >> 1, value]) # B3.10 else: self.audc[register >> 1] = value else: self.audf[register >> 1] = value elif register == AUDCTL: self.audctl = value elif register == STIMER: self.stimer_q |= 0b100 # B2.4: the forced reload lands in tick T+3 elif register == POTGO: self.pot_step = 2 # B5.1: the next tick clears the counter and starts a scan elif register == SKRES: # B1.6: any write sets the three status latches back to 1 self.frame_error = self.kb_overrun = self.ser_overrun = 0 elif 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 elif register == SKCTL: self.skctl = value # -- pins out ---------------------------------------------------------- @property def sod(self) -> int: """B7.1: the serial data out pin: the held bit, 0 while force break (SKCTL bit 7) is set.""" return 0 if self.skctl & 0x80 else self.sod_bit @property def oclk(self) -> int: """B7.4: the output clock pin: its flip-flop, or the external clock in modes 000 and 001.""" return self.oclk_ff if (self.skctl >> 4) & 7 >= 2 else self.bclk_in @property def bclk_out(self) -> int | None: """B7.4: the bidirectional clock when the chip drives it (modes 010, 110), else None.""" return self.bclk_ff if (self.skctl >> 4) & 7 in (2, 6) else None @property def init_mode(self) -> bool: """SKCTL bits 1-0 both 0 (B1.7).""" return not self.skctl & 0x03 def _update_irq(self) -> None: # B1.4, B1.5: latched sources, plus bit 3 (idle shifter) while enabled level = bool(self.latched) or bool(self.irqen & 0x08) if level != self.irq: self.irq = level if self.on_irq is not None: self.on_irq(level) def levels(self) -> tuple[int, int, int, int]: """The four channel codes: volume if the channel's output is 1, else 0 (B3.8).""" ff, hp, audc = self.ff, self.hp, self.audc a, b, c, d = audc # B3.6: channels 1 and 2 pass through the high-pass XOR; B3.8: volume-only after it o1 = 1 if a & 0x10 else ff[0] ^ hp[0] o2 = 1 if b & 0x10 else ff[1] ^ hp[1] o3 = 1 if c & 0x10 else ff[2] o4 = 1 if d & 0x10 else ff[3] return ( a & 15 if o1 else 0, b & 15 if o2 else 0, c & 15 if o3 else 0, d & 15 if o4 else 0, ) def mix(self) -> float: """The four codes through the variant's output curve, 0.0-1.0 (B3.9).""" dac = self.variant.dac total = 0.0 for level in self.levels(): total += dac[level] return self.variant.mix_curve[int(total * 4 + 0.5)] def take_outputs(self) -> list[tuple[int, int, int, int]]: """With ``record=True``: one ``levels()`` tuple per tick since the last call.""" taken, self.outputs = self.outputs, [] return taken # -- state ------------------------------------------------------------- def snapshot(self) -> dict: """All chip state as plain values (lists copied).""" state = {} for name, value in vars(self).items(): if name in _NOT_STATE: continue state[name] = _copy(value) return state def restore(self, state: dict) -> None: for name, value in state.items(): setattr(self, name, _copy(value))