# 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). Register map and reset values: DOC Appx 2 ("Mikey Addresses") unless tagged. """ from __future__ import annotations from array import array from lynx_python.cart.port import CartPort from lynx_python.mikey.display import Display from lynx_python.mikey.timers import TimerBank from lynx_python.mikey.uart import 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). DPRAM_END = 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). SAMPLE_TICKS = 500 SAMPLE_RATE = 16_000_000 // SAMPLE_TICKS class Mikey: __slots__ = ( "atten", "audio_in", "audio_regs", "cart", "dispadr", "dispctl", "display", "external_power", "iodat", "iodir", "mstereo", "next_sample", "nibble_defect", "no_expansion", "now", "palette", "pbkup", "ram", "samples", "sdone_pending", "serctl", "serdat", "stereo", "sysctl1", "timers", "uart", ) # fmt: skip def __init__(self, cart: CartPort, stereo: bool) -> None: self.stereo = stereo self.cart = cart self.timers = TimerBank(self._borrow) self.ram = bytearray(0x10000) self.display = Display(self) self.sysctl1 = 0b10 # DOC reset x,x,x,x,x,x,1,0: power on, strobe low self.iodir = 0 # DOC reset 0 self.iodat = 0 # DOC reset value not given for IODAT itself: HYPOTHESIS 0 self.serctl = 0 self.serdat = 0 self.dispctl = 0 # DOC reset 0: video DMA disabled self.pbkup = 0 self.dispadr = 0 self.palette = bytearray(32) # $FDA0-$FDBF: green, then blue|red self.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). self.atten = bytearray(5) self.samples = None # array('h') of left, right pairs once start_audio is called self.next_sample = 0 self.nibble_defect = False self.audio_regs = bytearray(32) # $FD20-$FD3F as stored bytes (M6 adds the LFSR) self.sdone_pending = 0 self.uart = Uart(self._uart_pending) # The display reads RAM by DMA: the bus is the channel (the board sets ``ram``). # Input lines read through IODAT (DOC Appx 2 IODAT; values HYPOTHESIS, U17): self.audio_in = 1 self.external_power = 0 self.no_expansion = 1 self.now = 0 # -- time -------------------------------------------------------------------------- def run_until(self, tick: int) -> None: samples = self.samples if samples is not None: # 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) left, right = self.mix() samples.append(left) samples.append(right) self.next_sample += SAMPLE_TICKS self.timers.run_until(tick) if self.uart.arriving: self.uart.run_until(tick) self.now = tick def _borrow(self, index: int, when: int) -> None: if index == 0: self.display.line_borrow(when) elif index == 2: self.display.frame_borrow(when) elif index == 4 and self.uart is not None: self.uart.clock(when) elif index >= 8: self._audio_clock(index - 8) def _audio_clock(self, channel: int) -> None: """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)"). """ regs = self.audio_regs base = channel * 8 shift = regs[base + 3] | ((regs[base + 7] >> 4) << 8) feedback = regs[base + 1] taps = (feedback & 0x3F) | ((feedback & 0x40) << 4) | ((feedback & 0x80) << 4) taps |= regs[base + 5] & 0x80 parity = (shift & taps).bit_count() & 1 bit = parity ^ 1 shift = ((shift << 1) | bit) & 0xFFF regs[base + 3] = shift & 0xFF regs[base + 7] = (regs[base + 7] & 0x0F) | ((shift >> 8) << 4) volume = regs[base] - 256 if regs[base] & 0x80 else regs[base] step = volume if bit else -volume if regs[base + 5] & 0x20: output = regs[base + 2] - 256 if regs[base + 2] & 0x80 else regs[base + 2] step = max(-128, min(127, output + step)) regs[base + 2] = step & 0xFF # -- the audio mix --------------------------------------------------------------------- def start_audio(self, now: int) -> None: """Begin recording 16-bit stereo samples every ``SAMPLE_TICKS`` from ``now``.""" self.samples = array("h") self.next_sample = now def mix(self) -> tuple[int, int]: """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). """ regs = self.audio_regs left = right = 0 stereo = self.stereo mute, pan, atten = self.mstereo, self.atten[4], self.atten for c in range(4): out = regs[c * 8 + 2] if self.nibble_defect: out ^= 0x08 value = out - 256 if out & 0x80 else out if not stereo: left += value continue if not mute & (0x10 << c): left += value * (atten[c] >> 4) // 15 if pan & (0x10 << c) else value if not mute & (1 << c): right += value * (atten[c] & 0x0F) // 15 if pan & (1 << c) else value if not stereo: right = left return left * 64, right * 64 # four signed bytes span -512..508: 16 bits # -- interrupts -------------------------------------------------------------------- def irq_bits(self) -> int: """INTSET as read: the timers' bits and the UART's bit 4 (set by its level).""" return self.timers.pending def _uart_pending(self, bit: int) -> None: # TEST ROM uart2 5: the UART's level sets INTSET bit 4; only INTRST clears it. self.timers.pending |= bit # -- cart address lines -------------------------------------------------------------- def _cart_lines(self) -> None: # DOC Appx 2 IODAT B1 = Cart Address Data (an output when IODIR B1 = 1). # HYPOTHESIS: as an input the line floats high. data = (self.iodat >> 1) & 1 if self.iodir & 0x02 else 1 self.cart.set_data(data) # AUDIN as an output (IODIR B4) drives the cart's AUDIN pin (M7 banking). self.cart.set_audin((self.iodat >> 4) & 1 if self.iodir & 0x10 else 1) # -- registers --------------------------------------------------------------------- def read(self, address: int) -> int: reg = address & 0xFF if reg < 0x20: return self.timers.read(reg >> 2, reg & 3, self.now) if reg < 0x40: return self.audio_read(reg - 0x20) if 0x40 <= reg <= 0x44: return self.atten[reg - 0x40] if self.stereo else 0 if reg == 0x50: return self.mstereo if self.stereo else 0 if reg in (0x80, 0x81): return self.irq_bits() # 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() if reg == 0x8C: return self.uart.read_serctl() if self.uart is not None else 0 if reg == 0x8D: return self.uart.read_serdat() if self.uart is not None else 0 if 0xA0 <= reg < 0xC0: return self.palette[reg - 0xA0] # DOC Appx 2: $FDC0-$FDFF "not yet allocated" (like $FD51-$FD7F), so the palette # stops at $FDBF. HYPOTHESIS (U18): write-only and unallocated addresses read 0; # a probe ROM on a real Lynx (read $FDC0-$FDFF after filling the palette) would # settle it, including whether the palette is mirrored there (U18b). return 0 def read_iodat(self) -> int: # 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. audin = self.cart.audin_pin() & self.audio_in pins = (audin << 4) | (self.no_expansion << 2) | self.external_power return (self.iodat & self.iodir) | (pins & ~self.iodir & 0xFF) def write(self, address: int, value: int) -> None: reg = address & 0xFF now = self.now if reg < 0x20: self.timers.write(reg >> 2, reg & 3, value, now) elif reg < 0x40: self.audio_write(reg - 0x20, value) elif 0x40 <= reg <= 0x44: if self.stereo: self.atten[reg - 0x40] = value elif reg == 0x50: if self.stereo: self.mstereo = value elif reg == 0x80: self.timers.pending &= ~value # DOC INTRST: write resets the set bits self.uart._level() # DOC §11: a level; it sets bit 4 again while it holds elif reg == 0x81: self.timers.pending |= value & 0xEF # DOC INTSET (bit 4 is the UART's level) elif reg == 0x87: self.sysctl1 = value self.cart.set_strobe(value & 1) # DOC B0 = Cart Address Strobe elif reg == 0x8A: self.iodir = value self._cart_lines() elif reg == 0x8B: self.iodat = value self._cart_lines() elif reg == 0x8C: if self.uart is not None: self.uart.write_serctl(value, now) elif reg == 0x8D: if self.uart is not None: self.uart.write_serdat(value, now) elif reg == 0x92: self.dispctl = value elif reg == 0x93: self.pbkup = value elif reg == 0x94: self.dispadr = (self.dispadr & 0xFF00) | (value & 0xFC) # DOC: bottom 2 bits ignored elif reg == 0x95: self.dispadr = (value << 8) | (self.dispadr & 0xFF) elif 0xA0 <= reg < 0xC0: # 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] = value & 0x0F if reg < 0xB0 else value # DOC Appx 2: $FDC0-$FDFF not yet allocated; HYPOTHESIS (U18b): writes there are # ignored (Toki's fade writes $FDC0-$FDDF; the palette is not mirrored). # -- audio registers (stored; milestone 6 gives them their channels) ------------------ def audio_read(self, offset: int) -> int: channel, reg = offset >> 3, offset & 7 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) return self.audio_regs[offset] def audio_write(self, offset: int, value: int) -> None: channel, reg = offset >> 3, offset & 7 timer_index = 8 + channel self.audio_regs[offset] = value if reg == 4: self.timers.write(timer_index, 0, value, self.now) elif 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) elif reg == 6: self.timers.write(timer_index, 2, value, self.now) elif reg == 7: self.timers.write(timer_index, 3, value & 0x0F, self.now)