# Handoff: build `pokey-python`, the Atari POKEY core ## Context you are inheriting The family's shape is **chips are cores, boards compose cores**. A non-CPU chip gets its own repository when more than one emulator could use it. POKEY's consumers: the Atari 5200 (`a5200-python`), Atari 7800 cartridges (`a7800-python`), later the Atari 8-bit computers and many Atari arcade boards (Centipede, Missile Command, Tempest with two, Star Wars and the quad-POKEY boards with four). So this core is **the whole chip**: audio, timers, interrupts, RANDOM, serial port, keyboard scan, pot scan. A board that finds a corner raises it here (an issue or a PR; re-certification is fine), never as a workaround in the board. Phase 0 (this repository as you find it) is documents, pinned references, two driver scripts that have been run, and this brief. **There is no emulator code.** The user's rules that bind the work: - **Oracle tiers** ([validation.md](validation.md)); a lower tier is a detector, never a judge; say the tier of every claim. - **No GPL, LGPL or unlicensed source is read** ([restart.md](restart.md), binding since 2026-11-14; this replaces Phase 0's "read for facts, copy nothing"). Altirra's code, Atari800, ASAP, MAME's POKEY and Mark Watson's HDL are not opened at all; Mikstas's VHDL has no licence and is only built and driven through its pins (a closed box: values measured through it are `OBSERVED`). The documents permitted are listed in restart.md rule 4. - **Python floor 3.11**, CPython and PyPy both green. Plain ints in the hot path, no generators, so that Rust and `-fast` forks can transcribe it. A PyPy object with 80 or more attributes becomes a dict and runs about three times slower: keep the chip object under that (a5200-python asks for it too). - **Reference cores are correct, not fast.** Never skip work because a channel is inaudible or a scan idle; a `-fast` fork is later work. - Local git only, small commits; no dangerous-looking shell commands; ROMs are read in place and never committed. ## Reading order 1. [start-here.md](start-here.md): the chip. 2. [timing.md](timing.md): the cycle numbers, and the table of what the VHDL did against hardware. 3. [undocumented-behavior.md](undocumented-behavior.md): C1-C8, U1-U13. 4. [validation.md](validation.md): the oracles, the split judge, the rungs. 5. [mame-oracle.md](mame-oracle.md). 6. Altirra Hardware Reference Manual chapter 5 in full (`reference/docs/altirra-hrm.pdf`): it is 30 pages and the docs here only summarise it. 7. The family's sibling sound cores show the house style for code and tooling: `ay8910-python`, `sn76489-python`, `gb-apu-python` (a chip whose time unit is the host's cycle). 8. `python -I scripts/fetch_references.py` (the documents, Acid800, the closed box's VHDL directory and Pokey Explorer), then `python -I scripts/run_vhdl.py --oss DIR` and `MAME_ROMPATH=DIR python -I scripts/mame_pokey.py` to see both drivers run. 9. ijor's `PokeyReSchem-13.pdf` (by hand only) is **not used** until the owner rules whether an unlicensed die schematic counts as "source" under the restart's rule 1 ([provenance.md](provenance.md)). U1 is attacked through the closed box's pins instead. ## Module shape (proposed) `src/pokey_python/` (name: decision 1, decided (b)). After the restart the modules may be mixins over one object; the table is a guide, not a contract: | Module | Holds | | --- | --- | | `chip.py` | `POKEY`: registers, `tick()`, `run()`, `read()`, `write()`, the pins | | `_clocks.py` | the 64 kHz and 15 kHz polynomial dividers, init mode | | `_polys.py` | the 4-, 5- and 9/17-bit counters, RANDOM, the per-channel delays | | `_timers.py` | four counters, borrow pipelines, joins, STIMER, two-tone resync | | `_output.py` | distortion flip-flops, high-pass, volume-only, the four codes | | `_irq.py` | IRQEN, IRQST, the line | | `_serial.py` | both shifters, clock modes, the three serial interrupts | | `_keyboard.py` | scan counter, the four-state machine, KBCODE, SKSTAT bits | | `_pots.py` | scan counter, POT0-7, ALLPOT, dump state | | `variants.py` | `POKEYVariant` rows (data, not subclasses) and DAC tables | | `state.py` | snapshot and restore | | `rc.py` | optional board-side helper: the capacitor on a pot pin (decision 4) | One fact per line where the fact is encoded, with its source as a comment (`# AHRM 5.3: +3 borrow pipeline`). If splitting the hot state across modules costs the 80-attribute rule or a method call per cycle per part, keep the modules as mixins or plain functions over one object; readability of each part matters more than the file count. ## The interface (proposed, in the family's style) Reconciled on 2026-11-11 with what a5200-python (`docs/handoff-brief.md`, "pokey-python: what the 5200 board needs") and a7800-python (`docs/cartridge.md`, "POKEY (to pokey-python)") ask for. Both fit; nothing they ask is refused. ```python from pokey_python import POKEY, C012294 chip = POKEY(C012294, record=False) # a board that polls; record=True queues outputs ``` **Time.** The unit is one period of the O2 pin. The core never assumes a rate (1.79 MHz on the home machines, 1.25 or 1.5 MHz on arcade boards, uneven on a 7800 cartridge: a7800 U10) and never looks at a video chip: the 15 and 64 kHz clocks are divided from O2 inside. - `chip.tick()` is one O2 period; `chip.run(n)` is n. `chip.clock` counts them. (`tick()` exists beside `run()` for PyPy, as in ay8910-python.) - The board calls it for **every** machine cycle, including those in which the CPU is halted. - A bus access belongs to one cycle. The order within a cycle is: the board performs the access, then calls `tick()`. With that order every number in timing.md reads directly: a write made before tick number T and a read made before tick number T+8+N is "write at T+0, read at T+8+N". **Bus.** | Call | Meaning | | --- | --- | | `chip.write(register, value)` | `register` is the 4-bit address A3-A0; the board decodes chip selects and mirrors | | `chip.read(register) -> int` | unmapped registers return `$FF`; reads have no side effects on the chip (true of every POKEY read register) | **Pins in.** Plain ints and callables the board supplies; each is consulted only when the chip looks. | Pin | API | Default (nothing attached) | | --- | --- | --- | | P0-P7 | `chip.pot_level = f(n) -> bool` (above threshold); asked each 15 kHz tick in slow scan and each cycle in fast scan, and on any cycle for ALLPOT | never crosses (reads 228) (U10) | | /KR1, /KR2 | `chip.key_response = f(code) -> int`, bit 0 = KR1 asserted, bit 1 = KR2 asserted, for the 6-bit scan code now on K0-K5; asked once per scan step | 0 | | SID | `chip.sid` (0 or 1), or `chip.serial_in = f() -> int` | 1 (mark) | | BCLK when an input | `chip.bclk_in` | 1 | The board's matrix is the board's: the 5200's function ignores bits 0 and 5 of the code, so one key answers at four codes; the core assumes nothing about the matrix. **Pins out.** | Pin | API | | --- | --- | | /IRQ | `chip.irq` (True while asserted), readable after every tick; optional `chip.on_irq(level)` | | audio, digital | `chip.levels() -> (c1, c2, c3, c4)`, each the channel's volume (0-15) if its output bit is 1, else 0: what the judge compares every cycle | | audio, analogue | `chip.mix() -> float`, the four codes through `variant.dac` (the measured, saturating curve: decision 5); the amplifier, filters, the mix with GTIA's or the TIA's sound and resampling are the board's | | K0-K5 | `chip.scan_code` | | dump transistors | `chip.dump_active` (True while the chip is discharging the pot pins); optional `chip.on_dump(level)` | | SOD, OCLK, BCLK out | `chip.sod`, `chip.oclk`, `chip.bclk_out` (None while BCLK is an input); optional `chip.on_serial(sod, oclk, bclk)` | With `record=True`, `take_outputs()` returns one `levels()` tuple per cycle run since the last call, as the sibling cores do; the referee and the conformance kit use it. **State.** `chip.snapshot() -> dict` of plain values and `chip.restore(dict)`. `POKEY()` and `chip.power_on()` give the documented starting state (decision 8). There is no `reset()`: the chip has no reset pin; a board's reset line does not reach POKEY. **Variants** are `POKEYVariant` values: `name`, `dac` (the transfer table), and room for a maker row if U8 ever finds a difference. A quad POKEY is four `POKEY` objects in the board until U9 says otherwise. ### The 5200 board's nine requests, one by one From a5200-python's `docs/handoff-brief.md` (its Phase 0 is finished): | # | Request | Answer | | --- | --- | --- | | 1 | one call per machine cycle, halted cycles included; `run(n)` | granted: `tick()`, `run(n)` | | 2 | divider phase defined and observable | granted: set by leaving init mode (timing.md, "The two derived clocks"); `power_on()` starts in init mode (decision 8). The exact first-tick offsets are the U1 rows until rung 2 closes them | | 3 | `pot_level(n) -> bool`, and notice of dump and release | granted: `chip.pot_level`, `chip.dump_active`, optional `chip.on_dump` | | 4 | scan code to /KR1 and /KR2 by callable; no 1:1 matrix assumed | granted: `chip.key_response(code)` | | 5 | /IRQ as a level after every cycle | granted: `chip.irq`. The two-or-three-cycle delay before the 6502 responds is the board's and the CPU's, not modelled here | | 6 | RANDOM on any cycle | granted | | 7 | four channel levels per cycle, or a sample buffer | the levels: `levels()` and `mix()`. **Not granted: a filled sample buffer at a host rate**; resampling stays in the board (decision 3) | | 8 | serial pins may idle | granted; and decision 2 proposes the shifters come later | | 9 | snapshot/restore; under 80 attributes | granted, as a rule of the build | a7800-python's table (`docs/cartridge.md`) asks for a 4-bit register number, an advance by one O2 whatever its length, RANDOM, an optional IRQ and a mixed level per O2: all granted by the same interface. Its "write-only variant" is the cartridge's decode, not the chip's. Both boards pin Acid800 1.2 too (the same archive and hash as here); Acid5200's ten POKEY tests are the 5200 board's check of this core. ### What this core asks of its siblings - **a5200-python, a7800-python**: call `tick()` on every O2 period; do the bus access before the tick of its cycle; never derive POKEY's 15 kHz clock from the video counter. Own the RC model of the pot pins (or use `pokey.rc`, decision 4), the keypad matrix, the audio mix and resampling. - **a7800-python**: say how many O2 periods a stretched TIA/RIOT access and a DMA burst give the cartridge port (its U10); the core does whatever number it is told. - **6502-python**: nothing. (A dev-only dependency if the AcidSAP harness is built: decision 6.) - Acid5200's ten `pokey_*` tests are a5200-python's milestone-4 exit; a failure there is filed here with the test's name. ## Rungs The table in [validation.md](validation.md) is the ladder: each rung has its judge, the judge's tier and a measurable exit. One rung per commit series, in order 1, 2, 3, 4, 5, 6, 7, then 9 (faults), 8 (music) and 10 (adoption). The serial port is rung 7 (decision 2 asks whether it is in the first build). Start of rung 2, before any divider code: close or bound U1, because every later stream comparison rests on the alignment between the core and the VHDL. Referee tooling to write first (rung 2): `scripts/referee.py` (stimulus file from a write list, run `pokey_tb`, parse; `run_vhdl.py` has the pieces), `scripts/streams.py` (seeded and directed streams), and the per-channel decode of the audio pin with volumes 1, 2, 4, 8 (validation.md, "What it still takes", item 1). The closed box is driven only through its pins. ## Proposed smoke list There are no ROMs for a chip; the smoke set is streams and programs. It must run in under two minutes including the VHDL (about 300,000 model cycles). | # | Stream | Why | | --- | --- | --- | | 1 | the nine rows of the timing.md comparison table | the hardware numbers | | 2 | each distortion on channel 1 at the machine clock, AUDF1 = 0..4, 2,000 cycles each | the patterns Plogue recorded | | 3 | channels 1+2 and 3+4 joined at the machine clock, 4-bit noise, short periods | *Ray of Hope* / *Numen* case | | 4 | high-pass: channels 1 and 3 at AUDF `$3B`/`$3C`, machine clock | the sawtooth example | | 5 | STIMER at each of 28 consecutive cycles against a 64 kHz note | slow-clock phase | | 6 | SKCTL 0 then 3 at each of 114 consecutive offsets, 15 kHz timer interrupt | init phase | | 7 | fast pot scan with crossings at cycles 0, 1, 2, 100, 228, 229, never | pot edge cases | | 8 | one slow pot scan, crossings on tick edges and one cycle either side | the same, slow | | 9 | a 5200 key (four aliased codes), debounce off then on | the 5200 keypad | | 10 | an 8-bit key press and release with debounce on; Break; Shift alone | the computer keyboard | | 11 | two-tone with timer 1 at the machine clock | T+8, +14, +20 | | 12 | one byte out and one byte in at 19,200 baud (mode 010, then 001) | SIO | | 13 | volume-only steps on all four channels, total 0 to 60 | the mix curve | | 14 | AcidSAP's POKEY tests, if the harness exists | hardware expectations | Full runs (10 million cycles and more per rung) only at rung exits. ## Open decisions for Aubrey > **Decided 2026-11-12.** Aubrey answered "yes to all the recommendations". > For every item below, the option marked as recommended is now the decision. > The options are kept as written, as the record of what was asked. Each with options and a recommendation. 1, 2 and 7 shape the first commit. 1. **Names.** The task proposed package `pokey`, class `POKEY`. The three sibling sound cores import as `_python` (`sn76489_python`, `ay8910_python`, `gb_apu_python`); the CPU cores use bare names (`huc6280`). Options: (a) `pokey`; (b) `pokey_python`. **Recommend (b)** for consistency with the sound cores and because `pokey` is a short common word on PyPI (not checked: no request was made); class `POKEY`, variant `C012294`. The examples above write `pokey` only because that was the proposal. 2. **The serial port in the first build.** (a) All of it, rung 7 as written. (b) First build: the parts audio depends on (two-tone resync, asynchronous mode holding timers 3+4, the SKCTL clock reset, IRQST bit 3 idle, SID on SKSTAT bit 4), with the shifters stubbed idle; the rest when the 8-bit computer board starts. **Recommend (b)**: the 5200 and 7800 connect nothing to the serial pins, the VHDL's serial part is the part its author did not test, and the Acid serial tests that need an SIO device cannot run before that board exists. The interface above already has the pins, so nothing changes for a board later. 3. **Output form.** (a) Four codes per cycle plus `mix()`, as proposed. (b) Also a sample on each half cycle, for the high-pass half-cycle pulses (U3). (c) A resampled buffer inside the core. **Recommend (a)**, with U3 measured in rung 3 by sampling the VHDL on both edges; move to (b) only if a stream shows a pulse that (a) loses. Never (c): resampling is the board's. 4. **Pot pins.** (a) Pin-true only: the board answers `pot_level(n)` and reads `dump_active` (what a5200-python asked for). (b) Also ship `pokey.rc`, a small capacitor model (charge time in cycles from the stick position, discharge while dumped, charge kept through fast scan), so the 5200, the 8-bit computers and paddles on other boards do not each write one. **Recommend (b)**, as an optional module that the chip class never imports. 5. **The DAC curve for `mix()`.** No permitted source gives a numeric curve (Phase 0 named the contents of two GPL files here; struck in the restart, see provenance.md); the Altirra manual gives the shape in words. Options: (a) default linear, no curve, until someone measures a chip; (b) fit a curve to the manual's description (single channel near linear with wider steps at 3-4, 7-8, 11-12; two channels at 15 about 1.5x one; full range about 2x the single-channel range) and label it as a fit; (c) take a measured table as data with attribution after Aubrey decides measurements are facts, not code. **Recommend (b) now, as `C012294.dac`, with linear available as a second variant row**, and (c) as Aubrey's call; the judge compares codes, not volts, so no rung depends on it. 6. **The AcidSAP harness in this repository's tests** (6502-python as a dev dependency; WSYNC, VCOUNT and the VBI stubbed, about 150 lines, tests only). For: eleven hardware-stated POKEY tests against the core before any board exists. Against: a sliver of ANTIC in a chip core's test folder. **Recommend yes**, kept under `tests/` with an import-boundary test that `src/` never imports it; Acid5200 on a5200-python remains the board-level check. 7. **Which reference is the judge.** (a) The split judge of validation.md: hardware numbers for latency, Mikstas's VHDL for streams. (b) First build our own gate-level netlist from ijor's schematics and judge everything against that (tier 1, weeks of work, needs the by-hand PDF). (c) Altirra as the reference (not possible here: Windows, GPL, an emulator). **Recommend (a) now**, with U1 closed first; consider (b) if U1 will not close or if the serial port's judge proves too thin. 8. **The power-on state** (U7; the chip has none defined). Options: all registers 0, IRQEN 0, counters loaded from 0, as if `SKCTL = 0` had been written (in init mode); or seeded random as a board option. **Recommend init mode with everything zero as the default, and `power_on(seed=...)` that randomises what the data sheet says is undefined**, so a board can test that its software initialises the chip. 9. **Fetch ijor's PDF by hand** (reading order, item 9), and whether to ask ijor or Nick Mikstas anything. Nothing is posted anywhere by this work; contacting either is Aubrey's decision. Mikstas's repository has no licence: if this core ever wants to ship a referee build script that others run, a licence question to him would be the polite step. **Recommend: fetch the PDF; no contact until rung 2 shows whether U1 is our stimulus or his model.** 10. **Public or local.** The sibling chip cores went public for free CI once they held certified code and no third-party files. **Recommend local until rung 3 passes.** ## Decided by the user - **2026-11-12**: every recommendation above adopted (package `pokey_python`; serial port only its audio-affecting parts first; four codes per cycle plus `mix()`; optional `rc` helper; the DAC curve fitted to the Altirra manual's words; the AcidSAP harness in `tests/`; the split judge; power-on in init mode, all zero, plus a seeded option; local until rung 3). - **2026-11-14**: restart under [restart.md](restart.md). What it changes in this brief: (1) no GPL/LGPL/unlicensed source is read, so the closed box is measured only through its pins and its values are `OBSERVED`; (2) ijor's PDF is not used until the owner rules on it (decision 9 is open again in that form); per-channel streams come from decoding the audio pin with volumes 1, 2, 4, 8, not from internal signals; (3) the rung 7 scope of decision 2 (b) stands. Every change made to the Phase 0 documents is in [provenance.md](provenance.md).