#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The board's picture against a detector's, every visible colour clock of every frame. Milestone 4's detectors at the board level (docs/handoff-brief.md): Gopher2600 and Stella, each run from the pinned local build (docs/validation.md). This script only drives them and reads what they write, so none of their code is used here; they are detectors, never judges, and a disagreement goes to a higher tier (the die, scripts/die_trace.py) before a run is extended. **Gopher2600** (``--detector gopher``) runs HEADLESS and is sent, per frame, ``STEP FRAME``, ``TV FRAME`` and ``SCREENSHOT``. The screenshot is its frame cropped to the 160 visible colour clocks and its visible scanlines, scaled by nearest neighbour to 1,026 pixels wide and three times its bottom row tall; the scale follows from the image size and ``TV FRAME``'s top and bottom (a size that does not fit them stops the run), and sampling each source pixel's centre recovers the colour of every visible colour clock exactly. Its screenshot k shows its frame k-1, counted from power-on as the board's are. **Stella** (``--detector stella``) runs the SDL build's debugger on a script of ``frame 1`` and ``saveSnap`` per frame, with 1x snapshots (each colour clock two pixels wide, 228 lines of a window Stella chooses) and the power-on fixed (``-seed 1``, RAM and CPU randomisation off), so the run is repeatable; the libretro core cannot fix it, and its runs disagree with each other (Pitfall!'s copyright line, River Raid's start). **The board** runs the same cartridge with no input (both detectors' default panel), and :class:`~a2600_python.television.Television` cuts its frames when VSYNC ends. **Alignment.** The frame numberings and the vertical position are found once and held fixed for the run: the row offset from where the lines' shapes (where the colour changes along each line, which does not depend on the palette) agree best on ``--align-frame``, the frame offset (-10 to 10) from the most frames whose every line has the same shape on the board, a tie keeping the offset expected (Gopher2600 -1; Stella 0): a picture that never moves cannot tell offsets apart, and then it does not matter which. A frame that only agrees at another offset is a divergence like any other. Frames before the program's start-up has settled (two frames after the last one the board's television cut for want of VSYNC) are not compared: each television cuts runaway frames at its own length, so their numbers do not line up. **Explaining a divergence.** ``--delay-writes GRP0,GRP1:3`` makes the board act on those writes three half clocks late (the run only; never the board). A detector that then agrees on every frame differs from the board in that write's timing and nothing else the run shows; which of the two is right is the die's question. **Colours** are compared through a map built as the run goes: each of the board's colours (``TIA.pixels`` D7-D1; blank is black, as is colour $00) must always meet the same RGB value and no two may share one, so a wrong colour register, object or pixel shows. Only a frame that agrees adds to the map, so a divergent frame cannot teach it a wrong pair. A mismatch is reported with the pixel's board line and visible clock (0-159). python scripts/picture_compare.py "ROM.zip" --detector gopher --frames 600 Exit status 0 when every compared frame agrees. """ from __future__ import annotations import argparse import os import re import struct import subprocess import sys import time import zipfile import zlib from dataclasses import replace from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a2600_python import MACHINES, VCS_NTSC, System # noqa: E402 from a2600_python.cartridge import read_image # noqa: E402 from a2600_python.television import MAX_LINES, Television # noqa: E402 GOPHER = ROOT / "reference" / "build-gopher2600" / "gopher2600" RUNS = ROOT / "tests" / "detector_runs" BASE = VCS_NTSC # the machine row the board runs (--machine) VISIBLE = 160 FRAME_INFO = re.compile(r"top: (\d+), bottom: (\d+), total: (\d+)") BLACK = 0x100 # the board's blank, compared as its own colour Frame = dict[int, list[int]] # a detector's scanline -> 160 packed RGB values # -- Gopher2600 ------------------------------------------------------------ def gopher_path(rom: Path) -> str: """Gopher2600 opens a zip member as ``file.zip/member``.""" if rom.suffix.lower() != ".zip": return str(rom) with zipfile.ZipFile(rom) as archive: members = [n for n in archive.namelist() if not n.endswith("/")] if len(members) != 1: raise SystemExit(f"{rom}: expected one member, found {members}") return f"{rom}/{members[0]}" def read_png(path: Path) -> tuple[int, int, list[bytes]]: """Decode an 8-bit RGB or RGBA PNG (Go's encoder) into rows of RGB triples.""" data = path.read_bytes() pos, idat = 8, [] width = height = channels = 0 while pos < len(data): length, kind = struct.unpack(">I4s", data[pos : pos + 8]) body = data[pos + 8 : pos + 8 + length] if kind == b"IHDR": width, height, depth, colour = struct.unpack(">IIBB", body[:10]) if depth != 8 or colour not in (2, 6): raise ValueError(f"{path}: unsupported PNG (depth {depth}, colour type {colour})") channels = 3 if colour == 2 else 4 elif kind == b"IDAT": idat.append(body) pos += 12 + length raw = zlib.decompress(b"".join(idat)) stride = width * channels rows, previous = [], bytearray(stride) for y in range(height): start = y * (stride + 1) kind, line = raw[start], bytearray(raw[start + 1 : start + 1 + stride]) for i in range(stride): a = line[i - channels] if i >= channels else 0 b = previous[i] if kind == 1: line[i] = (line[i] + a) & 0xFF elif kind == 2: line[i] = (line[i] + b) & 0xFF elif kind == 3: line[i] = (line[i] + ((a + b) >> 1)) & 0xFF elif kind == 4: c = previous[i - channels] if i >= channels else 0 p = a + b - c pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF rows.append(bytes(line)) previous = line if channels == 4: rows = [bytes(v for i, v in enumerate(row) if i % 4 != 3) for row in rows] return width, height, rows class Gopher: name = "Gopher2600" expected_offset = -1 first = 1 def power_on(self, rom: Path): """The board's own power-on: Gopher2600's (INTIM $00, T1024T, RAM and registers not randomised) differs only where no game here looks.""" return BASE def __init__(self, rom: Path, frames: int, reuse: bool) -> None: self.out = RUNS / "gopher" / rom.stem.replace(" ", "_") windows = self.out / "windows.txt" if reuse and windows.exists(): self.windows = [tuple(map(int, w.split())) for w in windows.read_text().splitlines()] else: self.windows = self._run(rom, frames) windows.write_text("".join(f"{t} {b}\n" for t, b in self.windows)) self.last = min(len(self.windows), frames) def _run(self, rom: Path, frames: int) -> list[tuple[int, int]]: self.out.mkdir(parents=True, exist_ok=True) commands = [] for k in range(1, frames + 1): commands += ["STEP FRAME", "TV FRAME", f"SCREENSHOT {self.out / f'g{k:04d}.png'}"] commands.append("QUIT") result = subprocess.run( [str(GOPHER), "HEADLESS", gopher_path(rom)], input="\n".join(commands) + "\n", capture_output=True, text=True, check=True, ) # fmt: skip windows = [(int(m[1]), int(m[2])) for m in FRAME_INFO.finditer(result.stdout)] if len(windows) != frames: raise SystemExit( f"Gopher2600 reported {len(windows)} frames of {frames}:\n{result.stdout[-2000:]}" ) return windows def frame(self, k: int) -> Frame: top, bottom = self.windows[k - 1] path = self.out / f"g{k:04d}.png" width, height, rows = read_png(path) lines = bottom + 1 - top if height != 3 * (bottom + 1) - top or width != int((68 + VISIBLE) * 2 * 3 * 0.8) - 68: raise SystemExit(f"{path}: {width}x{height} does not fit top {top}, bottom {bottom}") frame = {} for j in range(lines): row = rows[int((j + 0.5) * height / lines)] values = [] for i in range(VISIBLE): x = 3 * int((i + 0.5) * width / VISIBLE) values.append(row[x] << 16 | row[x + 1] << 8 | row[x + 2]) frame[top + j] = values return frame # -- Stella ------------------------------------------------------------------ # The board's console, not the one Stella's database names: joysticks in both # ports (it would plug paddles in for Breakout, keypads for BASIC), both # difficulties B, colour, ports unswapped, no phosphor blending of one frame # into the next (Amidar, Sea Hawk), and a television that keeps vertical sync # when the frame length changes (Stella's player default rolls the picture for # several frames, as after Maze Craze's 54 frames without VSYNC). CONSOLE = ( "-bc", "JOYSTICK", "-ld", "B", "-rd", "B", "-tv", "COLOR", "-sp", "NO", "-pp", "NO", "-plr.tv.jitter", "0", ) # fmt: skip class Stella: """The SDL build's debugger: ``frame 1`` + ``saveSnap`` per frame, 1x snapshots (each colour clock two pixels wide), registers and RAM fixed by ``-seed 1 -plr.ramrandom 0 -plr.cpurandom ""``. The power-on timer is not: two runs of one cartridge can start INTIM at $93 and at $DE (Berzerk), and a game that draws its randomness from INTIM then plays differently. So the run's own first ``riot`` dump gives the board its INTIM.""" name = "Stella" expected_offset = 0 first = 0 def __init__(self, rom: Path, frames: int, reuse: bool) -> None: self.out = RUNS / "stella" / rom.stem.replace(" ", "_") snaps = self.out / "snaps" report = self.out / "run.script.output.txt" console = self.out / "console.txt" # the CONSOLE flags the snaps were made with if not (reuse and snaps.is_dir() and any(snaps.iterdir()) and report.exists() and INTIM.search(report.read_text(errors="replace")) and console.exists() and console.read_text() == " ".join(CONSOLE)): # fmt: skip self._run(rom, frames, snaps) console.write_text(" ".join(CONSOLE)) # The names are a millisecond clock in hex, so they sort in order. self.files = sorted(snaps.glob("*.png"), key=lambda p: (len(p.name), p.name)) self.last = min(len(self.files), frames) - 1 def power_on(self, rom: Path): """The board powered on as this Stella run is: registers and RAM zero (randomisation off), the run's power-on INTIM from its debugger's first RIOT dump, T1024T, and Stella's phase (its first instruction starts a line and it runs no reset sequence), as scripts/lockstep_stella.py does.""" report = (self.out / "run.script.output.txt").read_text(errors="replace") intim = int(INTIM.search(report).group(1), 16) reset = 7 # 6502-python's reset sequence power = replace( BASE.power_on, a=0, x=0, y=0, s=0, p=0x20, ram_fill=0, timer_value=intim, timer_divider=1024, timer_first_decrement=1024 + reset - 1, hclock=((454 - 6 * reset) % 456) // 2, ) # fmt: skip return replace(BASE, power_on=power) def _run(self, rom: Path, frames: int, snaps: Path) -> None: snaps.mkdir(parents=True, exist_ok=True) for old in snaps.glob("*.png"): old.unlink() (self.out / "home").mkdir(exist_ok=True) script = self.out / "run.script" script.write_text("riot\n" + "frame 1\nsaveSnap\n" * frames + "exitRom\n") stella = ROOT / "reference" / "build-stella-sdl" / "stella" / "stella" libs = [ str(d) for d in (ROOT / "reference" / "build-stella-sdl" / "sdl3").glob("lib*") if d.is_dir() ] env = dict( os.environ, SDL_VIDEODRIVER="dummy", SDL_AUDIODRIVER="dummy", LD_LIBRARY_PATH=":".join(libs), ) cart, copy = rom, None if ( rom.suffix.lower() == ".7z" ): # Stella reads zips, not 7z: a temporary copy, removed after copy = self.out / "cart.bin" copy.write_bytes(read_image(rom)[0]) cart = copy command = [ str(stella), "-basedir", str(self.out / "home"), "-userdir", str(self.out), "-snapsavedir", str(snaps), "-ss1x", "1", "-plr.timemachine", "0", "-seed", "1", "-plr.ramrandom", "0", "-plr.cpurandom", "", *CONSOLE, "-dbg.logexec", "1", "-debug", "-dbg.script", str(script), str(cart), ] # fmt: skip try: subprocess.run(command, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1800, check=False) # fmt: skip finally: if copy is not None: copy.unlink() def frame(self, k: int) -> Frame: width, _, rows = read_png(self.files[k]) if width != 2 * VISIBLE: raise SystemExit(f"{self.files[k]}: {width} wide, not {2 * VISIBLE}") # The last row is the debugger's: grey where it stopped the beam. frame = {y: [row[6 * i] << 16 | row[6 * i + 1] << 8 | row[6 * i + 2] for i in range(VISIBLE)] for y, row in enumerate(rows[:-1])} # fmt: skip # Below a frame shorter than the snapshot the debugger leaves rows of # #060606, a colour in neither palette: no scanline was drawn there. while frame and all(c == UNDRAWN for c in frame[len(frame) - 1]): del frame[len(frame) - 1] return frame UNDRAWN = 0x060606 INTIM = re.compile(r"INTIM=([0-9a-f]{2})") DETECTORS = {"gopher": Gopher, "stella": Stella} # -- the board and the comparison ------------------------------------------- WRITE_NAMES = { "VSYNC": 0x00, "VBLANK": 0x01, "NUSIZ0": 0x04, "NUSIZ1": 0x05, "COLUP0": 0x06, "COLUP1": 0x07, "COLUPF": 0x08, "COLUBK": 0x09, "CTRLPF": 0x0A, "REFP0": 0x0B, "REFP1": 0x0C, "PF0": 0x0D, "PF1": 0x0E, "PF2": 0x0F, "GRP0": 0x1B, "GRP1": 0x1C, "ENAM0": 0x1D, "ENAM1": 0x1E, "ENABL": 0x1F, "HMP0": 0x20, "HMP1": 0x21, "HMM0": 0x22, "HMM1": 0x23, "HMBL": 0x24, "VDELP0": 0x25, "VDELP1": 0x26, "VDELBL": 0x27, "HMOVE": 0x2A, "HMCLR": 0x2B, } # fmt: skip def delay_writes(tia, delays: dict[int, int]) -> None: """Make ``tia`` act on writes to these registers ``steps`` half clocks late. Not a board option: an explanation for a divergence. A detector that agrees with the board once the board is made to act on a write later differs from it in that write's timing and in nothing else the run shows. """ queue: list[list] = [] # [steps left, (address, value)] step = tia.step def delayed(write=None): if write is not None and (write[0] & 0x3F) in delays: queue.append([delays[write[0] & 0x3F], write]) write = None for item in queue: item[0] -= 1 due = [item for item in queue if item[0] <= 0] if due: if write is not None or len(due) > 1: raise RuntimeError("two writes on one half clock under --delay-writes") queue.remove(due[0]) write = due[0][1] step(write) tia.step = delayed class BoardRun: """The board from power-on: its frames, where each starts, and every TIA write (for naming the register near a divergence).""" def __init__(self, rom: Path, delays: dict[int, int] | None = None, machine=VCS_NTSC) -> None: self.system = System.from_rom(rom, machine) tia = self.tia = self.system.board.tia if delays: delay_writes(tia, delays) self.starts: list[int] = [] # each frame's first line, counted from power-on self.writes: list[tuple[int, int, int, int]] = [] # (line, visible clock, register, value) self.system.board.bus_observers.append(self._observe) def _observe(self, kind: str, address: int, value: int, cycle: int) -> None: if kind == "W" and not address & 0x1080: self.writes.append( (self.tia.line, self.tia.step_in_line // 2 - 68, address & 0x3F, value) ) def frames(self): """Yield the frames, each a list of 160-value lines.""" tia = self.tia television = Television(tia) done: list[list[bytes]] = [] cut = tia.on_line self.starts.append(tia.line) def line(pixels: bytearray) -> None: # every frame the television cuts, runaway ones too before = television.frames_seen cut(pixels) if television.frames_seen != before: done.append(television.frame) self.starts.append(tia.line) # this line opens the next frame tia.on_line = line while True: self.system.run_cycles(76) while done: yield [[v >> 1 if v & 1 else BLACK for v in line] for line in done.pop(0)] def writes_near(self, frame: int, line: int, clock: int, reach: int = 12) -> list[str]: names = {v: k for k, v in WRITE_NAMES.items()} at = self.starts[frame] + line return [f"{names.get(r, f'${r:02X}')}=${v:02X}@{c}" for g, c, r, v in self.writes if g == at and abs(c - clock) <= reach] # fmt: skip def settled(frames: list[list[list[int]]]) -> int: """The first frame after the program's start-up: two frames after the last one the television had to cut for want of VSYNC (Television's MAX_LINES). Before it, each television cuts runaway frames at its own length, so frame numbers do not line up.""" runaway = [i for i, frame in enumerate(frames) if len(frame) >= MAX_LINES] return runaway[-1] + 3 if runaway else 0 class ColourMap: """Board colour -> RGB, learnt as the run goes; one to one unless ``shared`` (PAL and SECAM palettes give several colour values one RGB).""" def __init__(self, shared: bool = False) -> None: self.shared = shared self.to_rgb: dict[int, int] = {} self.to_board: dict[int, int] = {} def copy(self) -> ColourMap: other = ColourMap(self.shared) other.to_rgb, other.to_board = dict(self.to_rgb), dict(self.to_board) return other def agrees(self, colour: int, rgb: int) -> bool: known = self.to_rgb.get(colour) if known is None: if ( not self.shared and self.to_board.get(rgb, colour) != colour and not self._both_black(colour, rgb) ): return False self.to_rgb[colour] = rgb self.to_board.setdefault(rgb, colour) return True return known == rgb def _both_black(self, colour: int, rgb: int) -> bool: # The board's blank and its colour $00 are both black on a television. return {colour, self.to_board.get(rgb)} == {BLACK, 0} def compare(board: list[list[int]], frame: Frame, row_offset: int, colours: ColourMap): """Mismatched pixels as (board line, clock, board colour, detector RGB).""" bad = [] for scanline, values in frame.items(): line = scanline + row_offset if not 0 <= line < len(board): if any(v != frame_black(frame) for v in values): bad.extend((line, i, None, v) for i, v in enumerate(values)) continue for i, (b, g) in enumerate(zip(board[line], values)): if not colours.agrees(b, g): bad.append((line, i, b, g)) return bad def frame_black(frame: Frame) -> int: """The detector's black: the commonest value of its first and last rows.""" rows = frame[min(frame)] + frame[max(frame)] return max(set(rows), key=rows.count) def shape(line: list[int]) -> tuple[int, ...]: """Where the colour changes along a line: the same whatever the palette.""" return tuple(i for i in range(1, len(line)) if line[i] != line[i - 1]) OFFSETS = range(-10, 11) # frame offsets tried def same_shape(ours: list[tuple[int, ...]], theirs: list[tuple[int, tuple[int, ...]]]) -> bool: """Every detector line (board line, shape) has that shape on the board; a line beyond the board's frame must be plain.""" return all((ours[line] if 0 <= line < len(ours) else ()) == shaped for line, shaped in theirs) def row_offset( pairs: list[tuple[list[tuple[int, ...]], list[tuple[int, tuple[int, ...]]]]], search: range ) -> int: """The row offset under which the most lines have the same shape, over pairs of (board frame's line shapes, detector frame's (scanline, shape)).""" best = None for offset in search: same = sum( 1 for shapes, theirs in pairs for s, v in theirs if 0 <= s + offset < len(shapes) and shapes[s + offset] == v ) if best is None or same > best[1]: best = (offset, same) return best[0] def main(argv: list[str] | None = None) -> int: global RUNS, BASE parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("rom", type=Path) parser.add_argument("--detector", choices=sorted(DETECTORS), default="gopher") parser.add_argument( "--machine", default="Atari VCS (NTSC)", choices=sorted(MACHINES), help="the board's row" ) parser.add_argument("--frames", type=int, default=600) parser.add_argument( "--align-frame", type=int, default=30, help="first detector frame the row offset is found on (with the middle and last frames)", ) parser.add_argument("--from", dest="first", type=int, default=5, help="first detector frame compared (power-on's partial frame and Stella's " "randomised start come before)") # fmt: skip parser.add_argument("--keep-going", action="store_true", help="compare past a divergent frame") parser.add_argument( "--pixels", type=int, default=0, metavar="N", help="list the first N differing pixels of each divergent frame", ) parser.add_argument( "--reuse", action="store_true", help="reuse the detector output of a previous run" ) parser.add_argument( "--runs", type=Path, default=RUNS, help="where detector output goes (default: %(default)s)" ) parser.add_argument("--delay-writes", metavar="REG[,REG...]:STEPS", action="append", default=[], help="explain a divergence: the board acts on these writes STEPS half clocks late " "(e.g. GRP0,GRP1:2); never a board option") # fmt: skip args = parser.parse_args(argv) RUNS = args.runs BASE = MACHINES[args.machine] started = time.time() detector = DETECTORS[args.detector](args.rom, args.frames, args.reuse) detector_seconds = time.time() - started name = detector.name delays = {} for spec in args.delay_writes: names, _, steps = spec.partition(":") delays.update({WRITE_NAMES[n]: int(steps) for n in names.split(",")}) if delays: print( f"explaining: writes delayed {', '.join(f'{s}' for s in args.delay_writes)} half clocks" ) run = BoardRun(args.rom, delays, detector.power_on(args.rom)) produced = run.frames() board: list[list[list[int]]] = [] def board_frame(index: int) -> list[list[int]] | None: while len(board) <= index: board.append(next(produced)) return board[index] if index >= 0 else None # A 50 Hz program (more than 290 lines a frame) is shown with a PAL or # SECAM palette, where colour values share RGB values. shared = len(board_frame(args.align_frame)) > 290 # The row offset from one frame's line shapes; then the frame offset from # every frame: the one under which the most frames have the same shape # signature, a tie keeping the expected offset. A picture that stands # still cannot tell offsets apart, and then it does not matter which. # Each frame offset gets its own row offset: in a picture that scrolls a # line a frame (Bump 'n' Jump's road), the wrong frame matches best one # row off, so a row offset found under the expected frame offset alone # can be wrong (milestone 4's sweep). search = range(-40, 41) if args.detector == "gopher" else range(-120, 121) first = max(args.first, detector.first) shapes = { k: [(s, shape(v)) for s, v in detector.frame(k).items()] for k in range(first, detector.last + 1) } board_frame(detector.last + OFFSETS[-1]) # the board frames the offsets reach # Only frames after the start-up count: before it each television cuts # runaway frames at its own length (Maze Craze strobes no VSYNC for 54 # frames), so an offset found there is wrong for the rest. start = settled(board) # After a start-up the two televisions have cut different numbers of # runaway frames, so the offset can be far from the expected one. offsets = OFFSETS if not start else range(-60, 61) board_frame(detector.last + offsets[-1]) align = min(max(args.align_frame, start + offsets[-1]), detector.last) # Three frames spread over the run: one frame can stand still at every # row offset (Coco Nuts's blank start, then a picture from frame 39). samples = sorted({align, (align + detector.last) // 2, detector.last}) ours = [ [shape([0 if v == BLACK else v for v in line]) for line in frame] for frame in board ] # blank is black candidates = [] for frame_offset in offsets: pairs = [ (ours[k + frame_offset], shapes[k]) for k in samples if 0 <= k + frame_offset < len(ours) ] if not pairs: continue offset = row_offset(pairs, search) same = sum(1 for k, lines in shapes.items() if start <= k + frame_offset < len(ours) and same_shape(ours[k + frame_offset], [(s + offset, v) for s, v in lines])) # fmt: skip candidates.append( (-same, abs(frame_offset - detector.expected_offset), frame_offset, offset) ) candidates.sort() tied = [c for c in candidates if c[0] == candidates[0][0]] if len(tied) > 1: # Shapes tie where the picture stands still; then colours decide: a # change of colour alone (Hangman's background) shows the frame. def agreeing(frame_offset: int, offset: int) -> int: colours, count = ColourMap(shared), 0 for k in range(first, detector.last + 1): if start <= k + frame_offset < len(board): trial = colours.copy() if not compare(board[k + frame_offset], detector.frame(k), offset, trial): colours, count = trial, count + 1 return count tied.sort(key=lambda c: (-agreeing(c[2], c[3]), c[1])) same, _, frame_offset, rows = tied[0] print( f"aligned: {name} frame k = board frame k{frame_offset:+d}, scanline s = board line s{rows:+d} " f"({-same} of {len(shapes)} frames have the same shape there)", flush=True, ) colours = ColourMap(shared) agreed = compared = skipped = 0 first_bad = None for k in range(max(args.first, detector.first), detector.last + 1): candidate = board_frame(k + frame_offset) if candidate is None or k + frame_offset < start: skipped += 1 continue trial = colours.copy() # a divergent frame teaches the map nothing bad = compare(candidate, detector.frame(k), rows, trial) compared += 1 if not bad: colours = trial agreed += 1 continue line, clock, b, g = bad[0] lines = sorted({x[0] for x in bad}) print(f"frame {k}: {len(bad)} pixels differ on {len(lines)} lines; first at board line {line} " f"clock {clock}: board {'blank' if b == BLACK else 'no line' if b is None else f'${b << 1:02X}'}, " f"{name} #{g:06X}; writes near: {' '.join(run.writes_near(k + frame_offset, line, clock)) or 'none'}", flush=True) # fmt: skip for line, clock, b, g in bad[: args.pixels]: known = trial.to_rgb.get(b) print( f" line {line} clock {clock}: board {'blank' if b == BLACK else 'no line' if b is None else f'${b << 1:02X}'}" f" (seen as {f'#{known:06X}' if known is not None else 'nothing yet'}), {name} #{g:06X}" f" (the board's {f'${trial.to_board[g] << 1:02X}' if g in trial.to_board else 'nothing yet'})" ) first_bad = first_bad or k if not args.keep_going: break seconds = time.time() - started print( f"{args.rom.name}: {agreed} of {compared} frames agree with {name} at every visible colour clock " f"({skipped} start-up frames not compared; {len(colours.to_rgb)} colours; " f"{name} {detector_seconds:.0f} s, total {seconds:.0f} s)" ) return 0 if first_bad is None else 1 if __name__ == "__main__": sys.exit(main())