# Timing: the colour clock, the CPU cycle, and when things happen Line references are to the pinned copies in `reference/`: Towers `reference/docs/TIA_HW_Notes.txt` (v1.0, 2003, read off the TIA-1A schematics), tia-fpga `reference/src/tia-fpga/README.md` at `7bcd84e` (read off the die netlist and checked against Sim2600 half clock by half clock; its prose only, never its RTL). Stella, Gopher2600 and MAME appear only as closed boxes whose runs were observed (MAME's BSD-3 files excepted, [provenance.md](provenance.md)). Where Towers and the netlist disagree, the netlist wins: Towers worked from the schematic, and says himself that his notes "may include errors, omissions and much that is apocryphal" (line 1110). ## The units and the one timeline - **Colour clock (CLK)**: 3.579545 MHz NTSC. The master unit of the board. - **CPU cycle** = 3 CLK. The TIA divides CLK by 3 and drives the 6507's φ0; per tia-fpga, "Φ0 is a 50 per cent square wave reloaded by the horizontal counter" (README:394-395), which is why the phase is fixed per line. - **Line** = 228 CLK = 76 CPU cycles = 57 counts of the horizontal counter at 1/4 CLK (Towers 120-122). - **Audio tick**: two per line. The TIA runs in **steps of half a colour clock**, 456 to the line, numbered from the step on which HBLANK starts (step 0, a falling edge of the colour clock). Each 6502-python bus callback is one CPU cycle of six steps. Settled against the console-wired die traces in milestone 2 (`sim/traces/phi2/`; tia-fpga found Sim2600's own wiring puts every write on the other half of the colour clock, README:372-384): - **The cycle grid is fixed per line.** PH0 rises on step 0 and every sixth step after (the TIA reloads its divide-by-three at every line start), CLK2 (Φ2) is PH0 one step later, and **a write lands on the step where Φ2 falls: steps 4, 10, 16, … (≡ 4 mod 6)**. The board's cycle is steps 5–10, 11–16, … with the access on the last. Power-on must fall on that grid (`machine.PowerOn.hclock` ≡ 2 mod 3). - **A written register shows from the next step**, except that a colour register (COLUP0–COLUBK) written on a falling edge reaches the colour latch on that same edge (found by this project's `retrigger` die trace, record 17,661: a mid-line COLUBK write shows on the write's own half clock). - **Strobes** (WSYNC, RSYNC, RESxx) have a window of three steps: the write's and the two after (CLK2 low). - **A read** takes the TIA's D7/D6 as driven while Φ2 is high (the cycle's third to fifth steps); the board samples after the fifth. All of this is checked twice: the TIA's pins against the die on every step (`scripts/die_trace.py`, 20 traces), and the whole board against Sim2600's 6507, every TIA write on the die's step (`scripts/die_board.py`, 13 cartridges). ## WSYNC, RDY and the stretched read A write to WSYNC pulls RDY low on the write's own step. The NMOS 6502 ignores RDY on write cycles, so the CPU halts on its next read cycle and repeats it until RDY rises. Settled in milestone 2 (C16): - **Release**: an eight-step pulse starts three steps before HBLANK (step 453) and clears RDY on its first falling-edge step, **454**: the cycle ending there is still halted, and the read resumes in the cycle of steps 455–4, the line's first. Stella's traced beam positions agree (OBSERVED, its `-dbg.logtrace` resumes at line cycle 0); MAME's line origin is one cycle off its own count, absorbed by the power-on phase. - **A strobe that overlaps the pulse takes once the pulse ends; one entirely inside it is lost** (tia-fpga "The bus"). On the cycle grid: a WSYNC landing on step 454 costs nothing; one landing on step 4 sets RDY on step 5 and halts the whole line; one on step 448 halts one cycle. - **Sampling**: Sim2600's 6507 halts a read cycle whose RDY fell on its first step and runs one whose RDY rose on the step before it. RDY only ever changes on a cycle's first or last step, so any sample point from the first step to the fifth fits; the board samples on the third. **The design**, the one famicom-python uses for DMA: 6502-python has no RDY input, and needs none. The board runs each read cycle's first three steps, and while RDY is low runs whole halted cycles; then it performs the read once. Why a single read is enough (measured with a bus log on 6502-python, see the fit check in [validation.md](validation.md)): - STA WSYNC's last cycle is the write, so the stalled read is the next instruction's opcode fetch: cartridge ROM. The only exception is a JSR or BRK whose pushes land in a TIA mirror, where the stall falls on JSR's high operand fetch: cartridge ROM again. The stalled read is never a TIA, RIOT, stack or DPC register read. - Even if it were, INTIM's and TIMINT's read side effects are idempotent, and the fixed-bank hotspots (F8, F6, F4, E0, E7) select the same bank on a repeat. FE (reacts to the access after $01FE) and the Supercharger (counts distinct addresses) would care, and cannot meet the case. - `INC WSYNC` strobes WSYNC twice (RMW dummy write); harmless. - MAME instead burns icount at the write (BSD-3 `tia.cpp:976-984`, and its trace shows the jump: [mame-oracle.md](mame-oracle.md)). The board exposes "cycles spent halted" in its trace so detector diffs can line up with MAME's (which stamps the post-WSYNC instruction at ≡ 2 mod 76) and Stella's. No `dma_stalled` flag is needed: RDY on the 2600 falls only after a write and takes effect on the next read, so the cycle before an SHx/TAS write is never a stalled one. ## The horizontal counter A 6-bit polynomial counter (LFSR) clocked by a two-phase clock at 1/4 CLK (H@1, H@2: Towers 79-91), 57 states per line. Its decodes (Towers 131-206): | HCount | CLK | Event | | ---: | ---: | --- | | 0 | 0 | line start; HBLANK on (from SHB of the previous line) | | 4 | 16 | set HSYNC | | 8 | 32 | reset HSYNC (delayed 4 CLK) | | 12 | 48 | reset colour burst (delayed 4 CLK) | | 16 | 64 | RHB: end HBLANK (delayed 4 CLK: first pixel at 68) | | 18 | 72 | LRHB: late end of HBLANK, used instead of RHB when the HMOVE latch is set (pixel 76) | | 36 | 144 | CNT: centre, start the playfield's right half (copy or reflect) | | 56 | 224 | SHB: HBLANK on, counter resets to 0 four CLK later | Every decode is clocked into its logic during the next H@1–H@2 pair, i.e. **4 CLK late**. The board models the counter as an LFSR with its decode table (the netlist's states, not a binary 0–56 count): edge behaviour depends on it (tia-fpga README:500-507). A 111111 state is illegal and forces a reset (power-up can land there). **RSYNC** (C3, settled): the counter restarts, with HBLANK on and PH0 reloaded, **seven steps after the last step of the strobe's window on which PH0 was low**; one colour clock before that the PH0 divider is cleared. With the console's wiring the restart falls where PH0 was due to rise anyway, so the cycle grid survives an RSYNC (tia-fpga "Clocks and the horizontal counter"). Towers left it "requiring more investigation" (219-226); Stella's trace keeps showing the old line's coordinates after one (OBSERVED, `scripts/lockstep_stella.py`); MAME ignores RSYNC (BSD-3 `tia.cpp:1317-1320`). Every die trace starts with an RSYNC (each cartridge's clear loop writes it), and Donkey Kong strobes it twice at power-on. ## The movable objects Five position counters (P0, P1, M0, M1, BL), the same LFSR circuit, 40 states × 4 CLK = 160 CLK, each with its own two-phase clock (Towers 230-251). They are clocked by **MOTCK** (an inverted CLK) only while HBLANK is off, so they freeze during the 68 (or 76) blank clocks and resume where they were (Towers 329-336, 586-593). That freeze is why a reset position persists from line to line, and why sprites wrap. Decodes, counted from the counter's reset (Towers 252-293, 836-841): | Count | CLK after reset | Player | Missile | Ball | | ---: | ---: | --- | --- | --- | | 3 | 12 | START close copy (NUSIZ 001, 011) | same | | | 7 | 28 | START medium (011, 010, 110) | same | | | 15 | 60 | START far (100, 110) | same | | | 39 | 156 | wrap, START main (always) | same | wrap, START | Each START is decoded 4 CLK late; players latch it one more CLK (the "+1"), so **the visible delay after RESPx is 5 CLK for players and 4 for missiles and ball, relative to the playfield** (Towers 320-327, 982-986). RESPx does not generate a START for the main copy (it appears on the next line, after a wrap), but **RESBL does** (Towers 457-466). A RESxx during HBLANK takes effect at the start of the visible line, placing a player at pixel 1, a missile/ball at 0 (Towers 1056-1059). Towers' CPU-cycle-to-pixel table (971-1053) is the specification for position tests. **How a reset works** (contradiction C4): Towers says RESxx resets the counter ("4 CLK to reset"). The netlist says it **holds the object's two-phase clock in H@1 and sets a latch; the counter clears on the next H@2**, so a copy already decoded survives the reset, and inside HBLANK the clear waits for the first clocks of the visible line (tia-fpga README:513-518). Re-triggering exactly 18, 33, 66 or 162 CLK after a previous reset delays or loses a START by up to 3 CLK because the two-phase clock is reset mid-decode (Towers 895-939). The netlist rule is the one to implement; Towers' examples are the test cases. **Graphics scan counters** (players): 3-bit binary ripple counters, never reset, clocked through a NUSIZ-dependent gate (every 1, 2 or 4 CLK from the two-phase clock: Towers 358-384). NUSIZ, REFPx and VDELPx are read every pixel (Towers 382-411). GRP0 writes copy new P1 to old P1 and vice versa; GRP1 also copies new ENABL to old (Towers 399-404, 540-546). tia-fpga corrected "the size gate of stretched players" on the console wiring (README:381). **A GRP write, and the VDEL copy it makes, acts from the next half clock** like every other register, also while the player draws (C30, settled by this project's `grp_mid_draw` die trace); Gopher2600 and Stella act on it at least three half clocks later (Crystal Castles, milestone 4). So does an ENAM or ENABL write, and the VDELBL copy (C33, the `enable_mid_draw` die trace, which rejects a rule three half clocks late); Stella acts on those at least three half clocks later (24 sweep dumps, milestone 4). And so does a REFP write (C37, `refp_mid_draw`; Stella at least three half clocks later, Strawberry Shortcake). **The stretch gate is caught on HMOVE's stuffed pulses as well as on MOTCK**, so the extra clocks under the comb shift out a wrapped 2x or 4x player's last pixels (C34, `hmove_wrap`; Sea Hawk). **A RESxx hold opens a 2x gate and shuts a 4x one, and the scan counter takes START only on a clock the gate lets through** (C35, `resp_start` and `hmove_wrap`). **Missile and ball width**: the size bits gate the two-phase clock lines (1 CLK, 2 CLK, the 4-CLK START, or START plus its 4-CLK-delayed copy for 8: Towers 943-968). RESMPx resets the missile when the player's scan counter is at %100 on the main copy only (Towers 431-438). **The lock holds the missile's ring on that same step, with no delay**, so a released missile starts four clocks into a 1x player and six into a 2x one (C38, `resmp_release`; Frostbite). ## HMOVE The HMOVE strobe (Towers 604-753): 1. Sets the HMOVE latch, which makes HBLANK end on LRHB instead of RHB: **8 CLK more blank** (the "comb"), which also moves every object 8 pixels right, because their counters start 8 CLK later. The latch clears when the horizontal counter wraps, so an HMOVE late in the line moves objects without the comb (on the board, an HMOVE written late enough to be sampled before the wrap, up to cycle 73 counting from 0; see below), with the values read as (8 + value) left (Towers 729-753; Bradford Mott's measured table, pinned as `reference/stella-list/199804-msg00198.txt`). 2. Starts a 4-bit ripple counter at 15, decremented every 4 CLK; each object gets one extra clock per 4 CLK (on H@1) until its comparator finds no bit in common between the counter and its HMxx (D7 inverted) value. 0–15 extra clocks = 0–15 pixels left of the +8; at most 64 CLK, plus 3–6 CLK to decode and 4 to set the latches: **about 24 CPU cycles** (Towers 641-674). First compare at CLK 15 after the strobe, first decrement at CLK 17 (Towers 672-674); the netlist adds that **the first compare must come before the first decrement**, or HMxx = −8 moves an object sixteen pixels the wrong way (tia-fpga README:396-397). 3. **Writing HMxx during the HMOVE** can leave the "more motion" latch set forever: the object then gets an extra clock every 4 CLK, visible or not, until the next HMOVE. HMCLR does not clear the latches (Towers 693-703). That is the Cosmic Ark starfield ($60 to HMM0 21 cycles after HMOVE; Towers 705-726; Stolberg 1997, pinned `reference/stella-list/199705-msg00024.txt`), and its pattern **differs between TIA revisions** (C9). 4. **HMOVE during the visible line**: the extra pulses "plug" MOTCK gaps instead of adding (Towers 783-808, untested by Towers); the netlist says pulses past HBLANK **merge into the object clocks and show on the pads half a colour clock early** (tia-fpga README:382-383). **Settled on the die in milestone 3** by this project's `hmove_cycles` cartridge (HMOVE written on every cycle of the line, with HMP0 = $80 and $70; 277,643 half clocks match on every pin), at the edges none of tia-fpga's cartridges reaches: - **The comb latch samples the strobe on H@2**, the first H@2 at least five half clocks after the write ("3 CLK after the HMOVE command ... at most 6 CLK depending on the timing of STA HMOVE", Towers), and the counter's wrap (SHB) clears it. So an HMOVE written on cycle 19 still moves HBLANK's end to LRHB, one on cycle 20 does not (no comb, no stuffed pulses), one on cycle 73 is cleared by the wrap (Towers' and Mott's trick: motion without the comb), and one on cycle 75 is set just after the wrap and extends the next line. An HMOVE on cycle 74 sets the latch on the wrap's own half clock: Sim2600 clears it, but seven consoles (Mott's NTSC table and ale-79's six PAL/SECAM ones) give the next line the comb, and the board follows the consoles (C27). The board used to set the latch on the write itself; ale-79's `early_HMOVE` (Stella #699, rows 20-22 and 74-76 in its 1-based count) now matches in every cell the six consoles agree on. - **The motion counter resets to 15 after reaching 0 and rests there** until the next HMOVE (Towers: "64 CLK (including counter reset at the end)"). So after an HMOVE no HMxx value can clear a "more motion" latch left stuck (an HMxx of $70 compares with 0, which the resting counter never shows); only the next HMOVE does. The board's counter used to rest at 0. - **A RESxx during HMOVE's stuffing keeps the pulses that meet it.** Stuffed pulses arrive on the falling edge (H@1, 12 half clocks behind), MOTCK on the rising, and writes on falling edges too; so a stuffed pulse can fall on the strobe's half clocks, which MOTCK never does. One that arrives after the strobe's own half clock and before its hold lets go is not lost: the ring takes it as soon as the hold is over (`hmove_resp0` die trace, RESP0 3-24 cycles after an HMOVE on cycles 72-75 and 0-2; C28). - **The comparators see HMxx as it stood four half clocks before**, so an HMxx write as the motion runs out still counts (C36, `hm_late` die trace: HMP0 $70 to $90 on cycles 18-30 after an HMOVE on cycle 2; two or three half clocks miss it, five or more break tia-fpga's `hmove` trace on its own wiring; BASIC Programming and Stellar Track write there). The comparator timing ("when HMOVE's comparators see a new value") is the fifth rule tia-fpga moved on the console wiring (README:381-382). The board implements the counter, latches and comparators as circuits, not as a lookup of fitted windows (MAME's approach, which is why MAME is CPU-only). ## The playfield 20 bits per half line, 4 CLK each: PF0 D4–D7, PF1 D7–D0, PF2 D0–D7, shifted out from RHB (CLK 64, visible at 68) and restarted at CNT for the right half, as a copy or reflected (CTRLPF D0) (Towers 213-217). Score mode (D1) colours each half's playfield with COLUP0/COLUP1 but not the ball, which keeps COLUPF (C32, the `ball_score` die trace); priority (D2) puts the playfield above players. **When a mid-line playfield write reaches the screen** (C17, settled): each bit is read out of PF0–PF2 on the horizontal counter's H@1 and shown from the next H@2, so a write appears at the next 4-clock bit boundary only if it lands before that boundary's H@1 (tia-fpga "The picture"; the `playfield` die trace). The playfield and blanking reach the pads on the falling edge directly; objects and colours go through a latch on it. SCORE switches to the right-hand colour one colour clock before the second half starts, and PFP turns SCORE off. The playfield index restarts at RHB on every line and counts on from there, also on a line HMOVE's comb blanks until LRHB: **the comb hides the playfield's first two bits but does not move it** (C29, settled by this project's `hmove_playfield` die trace; milestone 2's model restarted it at LRHB, which put Pitfall!'s trees 8 pixels right). ## Collisions Fifteen latches set on the rising edges where two objects' outputs coincide, read in D7/D6 of CXM0P…CXPPMM, cleared by CXCLR. **Neither HBLANK nor VBLANK lets them set** (C24, settled): this project's `vblank_collisions` die trace reads CXPPMM after lines where the two players overlap, and the die drives D7 low under VBLANK. The board gates on the blanking latch VBLANK uses. Collisions during HBLANK (Stella #294, with console photos) are a recorded test. ## Vertical: VSYNC and VBLANK VSYNC D1 drives the composite sync to vertical sync for as long as it is set; VBLANK D1 blanks the output; VBLANK D7 dumps the paddle capacitors; D6 enables the INPT4/INPT5 latches. There is no vertical counter. The board records, per line, VSYNC and VBLANK as the die shows them (tia-fpga's `vertical` trace sets and clears both mid-picture). The `television` stage decides frames: start a frame on VSYNC's rising edge, and bound runaway frames (Stella's player default rolls the picture when the frame length changes, an observed television model, switched off for comparisons: validation.md). ## Audio Two channels, each: a 5-bit frequency divider, then AUDC's waveform from 4-, 5- and 9-bit polynomial counters, times AUDV, ticked twice per line. The netlist found the divider is **a binary counter compared with AUDF, not loaded from it**, so lowering AUDF below the current count makes it run on to 31 before the channel ticks again, and **the two channels are not wired alike** (tia-fpga README:400-407, 506-508). Every AUDC mode on both channels and the volume DAC are in the die traces `audio` and `audio_modes`. The pads are pull-downs only and the two outputs are joined on the console board (README:291-293, 321-329): the mixer is the console's resistor network. **Settled on the die in milestone 3** (`src/a2600_python/audio.py`; both traces match on both audio pads at every half clock, with either wiring): - **When.** Both phases run on the rising edge that latches the sync decodes (the horizontal counter's phase 1): phase A at counts 1 and 19, phase B at counts 9 and 37. The pads change at phase B, on steps 77 and 301 of the line. Phase A can move a count either way without a trace noticing; phase B cannot move a half clock. - **The divider** is exactly as tia-fpga describes; probing the die's own divider wires over the whole `audio` run (`probe_die.py`) shows it equal to the model's on every line. - **No lockup guards.** With AUDC D3-D2 = 3 (AUDC C-F) the pulse counter's feedback is the complement of its bit 1 and nothing more, so from %0000 or %0001 it steps to %1111 and then alternates %1111/%0000: a divide-by-two, not the divide-by-six cycle a lockup guard would give (docs/undocumented-behavior.md C26). The `audio` cartridge reaches it by switching a channel from AUDC B (which holds %1111) to C. The 4-bit polynomial has no %1010 guard either. - **The mix** is derived from the console schematic rather than fitted to an emulator: a 1 kΩ pull-up on the joined pins against pull-downs weighted 30k, 15k, 7.5k and 3.75k gives a swing of v/(30 + v) for v = AUDV0 + AUDV1 (both tones high). Still a fit: the transistors are taken as ideal switches. - **Samples**: one per tick, at phase B, so two a line, 112 and 116 colour clocks apart; `TIA.audio.take_samples()` returns them as 0..1. ## Inputs - **INPT4/5** (fire): latched low while VBLANK D6 is set (Stella Programmer's Guide, VBLANK). The board's latch takes the pads and the `fire` buttons on every half clock, so a press as short as one half clock is held. - **INPT0–3** (paddles): the capacitor charges through the pot from VCC; D7 goes high at the trip voltage. VBLANK D7 discharges it (Programmer's Guide). The netlist-level threshold is not in the die traces (tia-fpga left paddles off the board: README:284-287). The board's model (`controllers.Paddles`) takes R and C from the console schematic (1,800 Ω, 0.068 µF on each of I0-I3), a 0-1 MΩ pot and a half-supply trip point (the last two a fit): the pad reads 1 from (1,800 + R_pot)·C·ln 2 after the dump is released. With no paddle the pads read 0 (C19). - **Keypads**: rows driven from SWCHA (a RIOT output), columns read through INPT0/1/4; the column lines settle with an RC delay games wait out (`controllers.Keypads`; instant here, which a program that waits reads the same). ## The RIOT timer Clocked by φ2 (the CPU cycle). Writing TIMnT loads the counter and selects the interval; the counter decrements once per interval; when it passes 0 it sets the timer flag (TIMINT D7) and thereafter decrements **every cycle** from $FF. Reading INTIM clears the flag and returns to the programmed interval. The edges are contested (C6, C7): - 6532 data sheet: only a read of INTIM clears the flag. MCS6500 Family Hardware Manual p.78 (pinned, `reference/docs/MCS6500_Family_Hardware_Manual.pdf`): a read or write **on the cycle of the interrupt** does not clear it (Stella issue #606). **Settled in milestone 3** by #606's console results: a read or a write on a wrap cycle, the first wrap or a later one, leaves the flag set, and the timer then counts every cycle (after a write, from the written value). The board's twelve #606 screens match Stella's digit for digit (`tests/test_timer_roms.py`). - After underflow, hardware keeps clocking the programmed divider and, after an INTIM read, resumes from whatever phase it is in (Stella #97 tests), not from a fresh interval. - The first decrement comes one cycle after the write: MAME's BSD-3 `mos6530.cpp:315-321` reads that way, Stella's runs agree as a closed box (milestone 1's seeded fault "first decrement a cycle late" fails the Stella lockstep at instruction 1,329), and the #606 console results match with it. Judges: the timer test ROMs of Stella #97/#108/#606 have console results in the issue threads (prose tables and photos), and `test1.bas`'s hardware value 128246; there is no die-level RIOT anywhere ([validation.md](validation.md)). ## Power-up The CPU's reset is 6502-python's (7 cycles, three stack reads, vector $1FFC/$1FFD). Hardware starts with arbitrary TIA latches, RIOT RAM, timer and CPU registers, and an arbitrary CPU/TIA clock phase and horizontal counter state. The board takes all of these as machine parameters with defaults (Stella: random RAM/registers by user option; MAME: the state trap 13 of mame-oracle.md reads off its trace; the 6532 data sheet: I/O registers zeroed at reset, C8). An FE cartridge bank-switches during reset itself (the stack reads at $01FF/$01FE): see [cartridge.md](cartridge.md).