# SPDX-License-Identifier: MIT """The board's gates as functions, so another board can run them on its own chips. The Atari 7800 board runs the whole 2600 in its 2600 mode, with its own TIA and RIOT objects (they have served its BIOS first) and its own clocking. These are the judges this repository passes, callable from outside (docs/api.md). Each takes ``root=``, an a2600-python checkout whose references are fetched (``python scripts/fetch_references.py``) and whose locally recorded die traces and test ROMs sit where its scripts put them; romsets come from ``NO_INTRO_DIR`` as everywhere else. The candidate is supplied as a factory: - ``tia_factory()``: a fresh TIA for a die-trace replay (the die gate); - ``system_factory(cartridge, machine)``: a :class:`System`, for the timer ROMs, the serial tables, frame hashes and lockstep: powered on, or built on handed-in chips and a CPU that has been running (``System(..., board=Board(..., tia=, riot=, cycles=), cpu=)``), as a host's 2600 mode starts. Nothing here changes what the 2600 does: the scripts and tests of this repository call the same functions with the default factories. """ from __future__ import annotations import hashlib import os import struct import zipfile from collections.abc import Callable, Iterable from itertools import pairwise from pathlib import Path from .cartridge import load, read_image from .cartridge.connector import Cartridge from .machine import VCS_NTSC, Machine from .system import System from .tia import TIA SystemFactory = Callable[[Cartridge, Machine], System] def _default_system(cartridge: Cartridge, machine: Machine) -> System: return System(cartridge, machine) # -- the die: Sim2600 traces replayed pin by pin -------------------------------- # The trace format: DOC: tia-fpga sim/README.md (gen_trace.py's columns). PINS = ("ph0", "rdy", "sync", "lum", "col", "blank", "dbdrv", "au0", "au1") COLUMNS = ( "clk0", "clk2", "rw", "cs0", "cs3", "ab", "db", "inpt", "ph0", "rdy", "sync", "lum", "col", "blank", "au0", "au1", "dbdrv", ) # fmt: skip # Where the board follows hardware over the die, the half clocks it differs # by, exactly: hmove_cycles' two HMOVEs on cycle 74, where seven consoles set # the comb latch and Sim2600 clears it (docs/undocumented-behavior.md C27); # hmove_resp0 has the same tie in its HMOVE-on-cycle-74 block. KNOWN_DEPARTURES = { "hmove_cycles.trace": {"lum": 230, "col": 220, "blank": 32}, "hmove_resp0.trace": {"lum": 2638, "col": 2638, "blank": 352}, } def load_trace(path: Path) -> list[tuple[int, ...]]: """A die trace's records, one tuple of hex fields per half clock (``COLUMNS``).""" records = [] with path.open() as lines: for line in lines: if line.startswith("#") or not line.strip(): continue records.append(tuple(int(v, 16) for v in line.split())) return records def console_wiring(records) -> bool: """With the console's wiring CLK2 falls one record after PH0 falls.""" votes = sum( 1 for k in range(1, min(len(records), 20000)) if records[k - 1][1] == 1 and records[k][1] == 0 and records[k - 1][8] == 0 ) # fmt: skip falls = sum( 1 for k in range(1, min(len(records), 20000)) if records[k - 1][1] and not records[k][1] ) return votes > falls // 2 def replay_trace( records, *, warm: int = 2000, audio: bool = True, report: int = 0, stop_after: int | None = None, tia_factory: Callable[[], TIA] = TIA, ): """(records scored, mismatches per pin, first mismatch per pin, console wiring). The recorded inputs go into a fresh TIA from ``tia_factory`` and every output pin is compared at every half clock (scripts/die_trace.py has the rules: writes land where CLK2 falls; scoring starts at the first HBLANK rise after record ``warm``).""" console = console_wiring(records) tia = tia_factory() tia.rising = records[0][0] == 1 start = next( (k for k in range(max(warm, 1), len(records)) if records[k][13] and not records[k - 1][13]), len(records), ) mismatches = dict.fromkeys(PINS, 0) first: dict[str, int] = {} shown = 0 bus = records[0] # the bus as the die sees it (held while CLK2 is low, console wiring) scored = 0 pins = PINS if audio else PINS[:7] for k, rec in enumerate(records): clk0, clk2 = rec[0], rec[1] if not console or clk2: bus = rec if tia.rising != (clk0 == 1): raise ValueError(f"record {k}: CLK0 does not alternate") prev_clk2 = records[k - 1][1] if k else 0 write = None selected = bus[3] == 0 and bus[4] == 0 if prev_clk2 and not clk2 and selected and bus[2] == 0: write = (bus[5], bus[6]) tia.inputs = rec[7] tia.step(write) if k < start: continue scored += 1 dbdrv = 0 if selected and bus[2] == 1 and clk2: d = tia.read(bus[5]) dbdrv = (8 if d & 0x80 else 4) | (2 if d & 0x40 else 1) ours = { "ph0": int(tia.ph0), "rdy": int(tia.rdy_low), "sync": int(tia.sync_low), "lum": tia.lum, "col": tia.col, "blank": int(tia.blank), "dbdrv": dbdrv, "au0": tia.au0, "au1": tia.au1, } # fmt: skip theirs = dict(zip(COLUMNS[8:], rec[8:], strict=True)) theirs["sync"] = rec[10] theirs["blank"] = rec[13] bad = [p for p in pins if ours[p] != theirs[p]] if bad: for p in bad: mismatches[p] += 1 first.setdefault(p, k) if shown < report: detail = ", ".join(f"{p} {ours[p]}/{theirs[p]}" for p in bad) print(f" record {k} (line step {tia.step_in_line}): {detail} (ours/die)") shown += 1 if stop_after is not None and shown >= stop_after: break return scored, mismatches, first, console def die_trace_paths(root: Path) -> list[Path]: """Every die trace under ``root``: tia-fpga's (both wirings) and the local ones.""" root = Path(root) fpga = sorted((root / "reference/src/tia-fpga/sim/traces").glob("**/*.trace")) local = sorted((root / "tests/die_traces").glob("**/*.trace")) return fpga + local def die_traces( root: Path, *, tia_factory: Callable[[], TIA] = TIA, paths: Iterable[Path] | None = None ) -> dict[str, tuple[int, dict[str, int], bool]]: """Each trace: (records scored, mismatches per pin, whether it passes). A trace passes when its mismatches are exactly its known departures (none for all but the two C27 traces). Trace names are relative to ``root``.""" root = Path(root) results = {} for path in paths if paths is not None else die_trace_paths(root): scored, mismatches, _, _ = replay_trace(load_trace(path), tia_factory=tia_factory) bad = {p: n for p, n in mismatches.items() if n} expected = KNOWN_DEPARTURES.get(path.name, {}) if "die_traces" in path.parts else {} name = str(path.relative_to(root)) if path.is_relative_to(root) else str(path) results[name] = (scored, bad, bad == expected) return results # -- the RIOT timer ROMs, against console results -------------------------------- TIMER_SET_606 = tuple( f"TimerTest_{interval}_{access}_{wrap}_WRAP.bin" for interval in ("TIM8T", "TIM64T", "T1024T") for access in ("READ", "WRITE") for wrap in ("1st", "2nd") ) def _ram_after( archive: Path, member: str, factory: SystemFactory, machine: Machine, frames: int = 2 ) -> bytes: with zipfile.ZipFile(archive) as z: cartridge = load(z.read(member)).cartridge system = factory(cartridge, machine) system.run_frames(frames) return bytes(system.board.riot.ram) def timer_roms( root: Path, *, system_factory: SystemFactory = _default_system, machine: Machine = VCS_NTSC ) -> dict[str, bool]: """The Stella-issue timer ROMs (#108, #606): whether each shows the console's result. The rules and the console results are tests/test_timer_roms.py's (docs/validation.md "Milestone 3"). The results were captured on NTSC consoles; ``machine`` is handed to the factory as the other gates do, and a pass on another row means the NTSC console's result reproduced on that row, nothing more.""" issues = Path(root) / "tests/test_roms/stella-issues" t108, t606 = issues / "108-078-TIMER.zip", issues / "606-129-TimerTest.zip" results = {} ram = _ram_after(t108, "TIMER/test1.bas.bin", system_factory, machine) results["108 test1.bas"] = ram[0x13:0x16] == bytes.fromhex("128246") ram = _ram_after(t108, "TIMER/testTIMINT_withDelay.bin", system_factory, machine) results["108 testTIMINT_withDelay"] = (ram[0x05], ram[0x06], ram[0x03]) == (0x00, 0x80, 0x00) rows = 24 for member in TIMER_SET_606: ram = _ram_after(t606, member, system_factory, machine) middle, right = ram[rows : 2 * rows], ram[2 * rows : 3 * rows] results[f"606 {member}"] = all((a - b) & 0xFF == 5 for a, b in pairwise(middle)) and all( (a - b) & 0xFF <= 1 for a, b in pairwise(right) ) return results # -- ale-79's serial tables (Stella #699), one console at a time ----------------- BAUD = 57600 # DOC: ale-79's #699 issue text, 57,600 baud 7N1 on SWCHA D7 SWCHA = 0x280 # DOC: SPG SERIAL_FRAME_CYCLES = 262 * 76 # the ROMs send no VSYNC: time is counted in these def serial_record( rom: bytes, machine: Machine, *, system_factory: SystemFactory = _default_system, frames: int = 20000, idle_frames: int = 30, ) -> tuple[list[tuple[int, int]], float]: """(SWCHA D7 levels as (cycle, level), CPU cycles per bit) after RESET is pressed.""" system = system_factory(load(rom, scheme="4K").cartridge, machine) riot = system.board.riot levels: list[tuple[int, int]] = [(0, 1)] write = riot.write def watching(address: int, value: int, cycle: int) -> None: write(address, value, cycle) if address & 0x2FF == SWCHA and riot.ddr_a & 0x80: level = value >> 7 if level != levels[-1][1]: levels.append((cycle, level)) riot.write = watching riot.input_b &= ~0x01 # RESET pressed system.run_cycles(4 * SERIAL_FRAME_CYCLES) riot.input_b |= 0x01 idle = 0 for _ in range(frames): count = len(levels) system.run_cycles(SERIAL_FRAME_CYCLES) idle = idle + 1 if len(levels) == count else 0 if idle >= idle_frames and len(levels) > 1: break del riot.write return levels, machine.timing.cpu_hz / BAUD def serial_decode(levels: list[tuple[int, int]], period: float) -> str: """The pin's levels read as a 7N1 UART would: each bit sampled in its middle.""" def level_at(cycle: float) -> int: lo, hi = 0, len(levels) - 1 while lo < hi: # the last change at or before ``cycle`` mid = (lo + hi + 1) // 2 if levels[mid][0] <= cycle: lo = mid else: hi = mid - 1 return levels[lo][1] out = [] k = 1 while k < len(levels): start, level = levels[k] if level: k += 1 continue bits = [level_at(start + period * (i + 1.5)) for i in range(7)] if not level_at(start + period * 8.5): out.append("�") # framing error: no stop bit out.append(chr(sum(b << i for i, b in enumerate(bits)))) stop = start + period * 9 while k < len(levels) and levels[k][0] < stop: k += 1 return "".join(out) def table_cells(text: str) -> list[list[str]]: return [line.split() for line in text.replace("\r", "").split("\n") if line.strip()] def compare_table(ours: str, table: str) -> tuple[int, int, list[tuple[int, int, str | None, str]]]: """(cells matched, cells, misses as (row, cell, board's, console's)), every cell.""" ours_rows, rows = table_cells(ours), table_cells(table) matched = total = 0 misses = [] for r, row in enumerate(rows): for c, theirs in enumerate(row): total += 1 mine = ours_rows[r][c] if r < len(ours_rows) and c < len(ours_rows[r]) else None if mine == theirs: matched += 1 else: misses.append((r, c, mine, theirs)) return matched, total, misses # The seven ROMs and where each console's table is, under root (all pinned). SERIAL_ROMS = { "early_HMOVE": ( "reference/hardware/stella-issues/699-HMOVE_TEST.zip", "HMOVE_TEST/early_HMOVE.bin", ), "HMOVE_RESPx": ( "reference/hardware/stella-issues/699-HMOVE_RESPx_test.zip", "HMOVE_RESPx_test/HMOVE_RESPx.bin", ), **{ f"HMOVE_RESPx_{o}": ( "tests/test_roms/stella-issues/699-140-HMOVE_RESPx_v2.zip", f"HMOVE_RESPx_{o}.bin", ) for o in ("P0", "P1", "M0", "M1", "BL") }, } # fmt: skip CONSOLES = ("PAL_7800", "PAL_JR_84", "PAL_JR_91", "PAL_L6", "PAL_VADER", "SECAM_WOODY") def serial_table_text(root: Path, rom: str, console: str) -> str: """One console's pinned result table for one of the seven ROMs.""" root = Path(root) if rom == "early_HMOVE": member = {"PAL_VADER": "PAL_vader", "SECAM_WOODY": "SECAM_woody"}.get(console, console) archive, name = root / SERIAL_ROMS[rom][0], f"HMOVE_TEST/{member}.txt" elif rom == "HMOVE_RESPx": archive = root / SERIAL_ROMS[rom][0] name = f"HMOVE_RESPx_test/Results/HMOVE_RESPx_{console}.txt" else: archive = root / "reference/hardware/stella-issues/699-results.zip" name = f"test_{rom.rsplit('_', 1)[1]}_{console}.txt" with zipfile.ZipFile(archive) as z: return z.read(name).decode("latin-1") def serial_rom(root: Path, rom: str) -> bytes: archive, member = SERIAL_ROMS[rom] with zipfile.ZipFile(Path(root) / archive) as z: return z.read(member) def serial_tables( root: Path, machine: Machine, console: str, *, roms: Iterable[str] = tuple(SERIAL_ROMS), system_factory: SystemFactory = _default_system, ) -> dict[str, tuple[int, int, list]]: """Each ROM decoded from the board running ``machine``, against ``console``'s table: (cells matched, cells, misses). Every cell counts.""" results = {} for rom in roms: levels, period = serial_record( serial_rom(root, rom), machine, system_factory=system_factory ) text = serial_decode(levels, period) results[rom] = compare_table(text, serial_table_text(root, rom, console)) return results # -- frame hashes and lockstep against this board -------------------------------- NO_INTRO_SET = "Atari - Atari 2600" def dump_path(name: str) -> Path: base = os.environ.get("NO_INTRO_DIR") if not base: raise RuntimeError("set NO_INTRO_DIR to the No-Intro root") return Path(base) / NO_INTRO_SET / f"{name}.zip" SMOKE_LIST = "tests/smoke_dumps.txt" def smoke_names(root: Path) -> list[str]: """The smoke list, ``tests/smoke_dumps.txt`` under ``root``: No-Intro dump names in file order ('#' starts a comment). The dumps worth rerunning after a change, before a full sweep (methodology, "Smoke before sweep"); scripts/sweep_stella.py and a transcription's lockstep read it here.""" text = (Path(root) / SMOKE_LIST).read_text() lines = (line.partition("#")[0].strip() for line in text.splitlines()) return [line for line in lines if line] def run_hashes(system: System, frames: int) -> dict[str, str]: """SHA-256 of every finished line's pixels, every audio sample and the 6507's registers and cycle count at each frame's end, over ``frames`` frames.""" tia, cpu = system.board.tia, system.cpu pixels, audio, registers = hashlib.sha256(), hashlib.sha256(), hashlib.sha256() previous = tia.on_line def line(row: bytearray) -> None: pixels.update(row) if previous is not None: previous(row) tia.on_line = line try: for _ in range(frames): system.run_frames(1) samples = tia.audio.take_samples() audio.update(struct.pack(f"<{len(samples)}d", *samples)) registers.update( struct.pack( " str: """The line ``tests/frame_hashes.tsv`` keeps for a run.""" return ( f"{name}\t{frames}\t{hashes['run'][:16]}\t{hashes['pixels'][:16]}" f"\t{hashes['audio'][:16]}\t{hashes['registers'][:16]}" ) def recorded_hashes(root: Path) -> dict[str, str]: """``tests/frame_hashes.tsv`` under ``root``: dump name -> recorded line.""" rows = {} for row in (Path(root) / "tests/frame_hashes.tsv").read_text().splitlines(): if row and not row.startswith("#"): rows[row.split("\t")[0]] = row return rows def frame_hashes( root: Path, *, names: Iterable[str] | None = None, system_factory: SystemFactory = _default_system, machine: Machine = VCS_NTSC, ) -> dict[str, bool]: """Each recorded dump run on the candidate: whether its line equals the record.""" expected = recorded_hashes(root) results = {} for name in names if names is not None else expected: frames = int(expected[name].split("\t")[1]) cartridge = load(dump_path(name)).cartridge system = system_factory(cartridge, machine) results[name] = hash_row(name, frames, run_hashes(system, frames)) == expected[name] return results def lockstep( rom: str | Path | bytes, *, system_factory: SystemFactory, machine: Machine = VCS_NTSC, cycles: int = 1_000_000, ) -> tuple[int, tuple | None]: """The candidate and this board side by side, every bus cycle compared. Returns (cycles that agreed, the first difference as (index, ours, theirs) or None). A cycle is (kind, address, value) as ``Board.bus_observers`` sees it, counted from power-on on each side (halted cycles make no access); both run from the same cartridge image and machine row.""" image = rom if isinstance(rom, bytes) else read_image(rom)[0] def build(factory: SystemFactory) -> tuple[System, list]: log: list = [] system = factory(load(image).cartridge, machine) system.board.bus_observers.append(lambda k, a, v, c: log.append((k, a, v))) return system, log ours, ours_log = build(_default_system) theirs, theirs_log = build(system_factory) agreed = 0 while agreed < cycles: ours.step() theirs.step() n = min(len(ours_log), len(theirs_log)) for k in range(n): if ours_log[k] != theirs_log[k]: return agreed + k, (agreed + k, ours_log[k], theirs_log[k]) agreed += n del ours_log[:n], theirs_log[:n] return agreed, None