# SPDX-License-Identifier: MIT """Set the board's frames against the referee's (Nuked-MD), frame by frame: the judge, where ``scripts/compare_frames.py`` sets them against BlastEm, a detector. The referee's frames come from a run with ``NMD_PICS`` (the GPL harness megadrive-nuked-md-harness, ``NUKED_MD_HARNESS``): each record of ``pics.z`` inflates to one frame's raw capture of the VDP's RGB pins, a row per /HSYNC from the /VSYNC fall. Which row is line 0 is FITTED on one frame (``--row0`` to give it); an older driver also wrote the model's internal V counter into each row, a tap removed in provenance wave 2 (2026-11-19). A display pixel x is sample 154 + 2x in H40 (the offset ``scripts/run_output_delay.py`` measured), and the pins' 0-255 levels are the 15 steps of the DAC ramp (normal colours on the even steps, shadow and highlight between), so both sides are compared as ramp steps. ``--offset`` is referee frame minus board frame: -1 for Overdrive 2's aligned runs (docs/worklog.md, Session 13). Each board frame is scored at that offset and at the best offset within ``--window`` of it, so a picture a frame early or late shows as such rather than as a difference. python scripts/compare_referee.py REFEREE_DIR BOARD_DIR OUT.csv [--offset -1] [--jobs 8] """ from __future__ import annotations import argparse import csv import struct import sys import zlib from multiprocessing import Pool from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from megadrive_python.png import read_png from megadrive_python.render import RAMP LINES, SAMPLES, FIRST, WIDTH, HEIGHT = 400, 2048, 154, 320, 224 BOARD_STEP = {level: step for step, level in enumerate(RAMP)} def load_index(directory: Path) -> dict[int, tuple[int, int, int]]: raw = (directory / "pics.idx").read_bytes() index = {} for at in range(0, len(raw) - 23, 24): frame, offset, size, t = struct.unpack(" list | None: """One referee frame as ``HEIGHT`` rows of ramp steps: plot row ``row0 + v`` (rows in /HSYNC order from the /VSYNC fall) is line v.""" offset, size, _ = entry with (directory / "pics.z").open("rb") as file: file.seek(offset) body = zlib.decompress(file.read(size)) counts = struct.unpack(f"<{LINES}H", body[: 2 * LINES]) base = 2 * LINES rows: list[bytes | None] = [] for line in range(row0, row0 + HEIGHT): if line < LINES and counts[line] >= FIRST + 2 * WIDTH: start = base + (line * SAMPLES + FIRST) * 3 samples = body[start : start + WIDTH * 6] rows.append(bytes(round(samples[6 * x + c] * 14 / 255) for x in range(WIDTH) for c in range(3))) # fmt: skip else: rows.append(None) return rows def fit_row0(referee_dir: Path, board_dir: Path, index: dict, n: int, offset: int) -> int: """The plot row that is line 0, FITTED on one frame: the row at which the most pixels of board frame ``n`` match referee frame ``n + offset``. Pins only; it replaces the model's V counter, which an older driver wrote into each row.""" board = board_frame(board_dir / f"f{n:05d}.png") entry = index[n + offset] def score(r: int) -> int: return same(board, referee_frame(referee_dir, entry, r)) return max(range(LINES - HEIGHT), key=score) def board_frame(path: Path) -> list: rows = read_png(path) return [bytes(BOARD_STEP.get((p >> s) & 255, 99) for p in row for s in (16, 8, 0)) for row in rows[:HEIGHT]] # fmt: skip def same(board: list, referee: list) -> int: count = 0 for ours, theirs in zip(board, referee, strict=False): if theirs is None or len(ours) != len(theirs): continue count += sum(1 for x in range(0, len(ours), 3) if ours[x : x + 3] == theirs[x : x + 3]) return count def work(task: tuple) -> dict: referee_dir, board_dir, index, n, offset, window, row0 = task path = board_dir / f"f{n:05d}.png" row = {"frame": n, "at_offset": "", "best": "", "best_offset": "", "pixels": ""} if not path.exists(): return row board = board_frame(path) pixels = sum(len(r) // 3 for r in board) row["pixels"] = pixels scores = {} for d in range(offset - window, offset + window + 1): if n + d in index: scores[d] = same(board, referee_frame(referee_dir, index[n + d], row0)) if scores: best = max(scores, key=lambda d: (scores[d], d == offset)) row.update(at_offset=scores.get(offset, ""), best=scores[best], best_offset=best) return row def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("referee", type=Path) parser.add_argument("board", type=Path) parser.add_argument("out", type=Path) parser.add_argument("--offset", type=int, default=-1) parser.add_argument("--window", type=int, default=3) parser.add_argument("--first", type=int, default=1) parser.add_argument("--last", type=int, default=10**9) parser.add_argument("--every", type=int, default=1) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--row0", type=int, help="the plot row that is line 0 (else fitted)") parser.add_argument("--fit-frame", type=int, help="the board frame to fit --row0 on") args = parser.parse_args() index = load_index(args.referee) row0 = args.row0 if row0 is None: n = args.fit_frame if args.fit_frame is not None else args.first row0 = fit_row0(args.referee, args.board, index, n, args.offset) print(f"row 0 of the referee's plot: {row0} (fitted on board frame {n})") last = min(args.last, max(index) - args.offset - args.window) tasks = [(args.referee, args.board, index, n, args.offset, args.window, row0) for n in range(args.first, last + 1, args.every)] # fmt: skip with Pool(args.jobs) as pool, args.out.open("w", newline="") as file: writer = csv.DictWriter(file, ["frame", "at_offset", "best", "best_offset", "pixels"]) writer.writeheader() for row in pool.imap(work, tasks, chunksize=4): writer.writerow(row) print(f"{len(tasks)} board frames scored into {args.out}") return 0 if __name__ == "__main__": raise SystemExit(main())