#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 2 (d): the board's frames against ProSystem's, both started without a BIOS. ProSystem (GPL-2.0) is run only as a black box through ``prosystem_run.py`` (ctypes; its source is not opened): it starts a cartridge directly, so the board is started the same way (``start="direct"``, labelled "BIOS skipped"). The two starts are not the same instant of the frame, so the comparison searches, once per title on the first compared frame, the frame offset (ProSystem frame n against board frame n + d, |d| <= 4) and the line offset (|v| <= 12) that fit best, and then keeps them for every frame. ProSystem gives RGB, the board colour bytes. A frame pair is **pixel-exact under one colour map** when every board colour byte maps to one RGB value and every RGB value to one byte; a pixel that breaks the majority map in either direction is counted as differing. python scripts/frames_prosystem.py ".../Asteroids (USA).zip" --frames 600 --every 20 Seeded fault: ``--fault shift`` moves the board's window one line after the alignment is fixed: every frame with content must then differ. """ from __future__ import annotations import argparse import collections import struct import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a7800_python.system import System # noqa: E402 from a7800_python.television import FIRST_CLOCK, WIDTH, Television # noqa: E402 BOARD_FIRST, BOARD_LINES = 10, 250 # a wider window than the crop, for the line search def prosystem_frames(cart: Path, frames: int, every: int, out: Path) -> dict[int, list[bytes]]: raw = out / "prosystem.raw" raw.unlink(missing_ok=True) subprocess.run([sys.executable, str(ROOT / "scripts" / "prosystem_run.py"), str(cart), "--frames", str(frames), "--every", str(every), "--raw", str(raw)], check=True, stdout=subprocess.DEVNULL) # fmt: skip result = {} data = raw.read_bytes() at = 0 while at < len(data): n, w, h = struct.unpack_from(" int | None: """Pixels breaking the majority colour map, board rows shifted by v; None if out of range.""" h = len(ps) if v < 0 or v + h > len(board_rows): return None forward: dict[int, collections.Counter] = collections.defaultdict(collections.Counter) backward: dict[bytes, collections.Counter] = collections.defaultdict(collections.Counter) pairs = collections.Counter() for y in range(h): row, prow = board_rows[v + y], ps[y] for x in range(min(len(row), len(prow))): pairs[row[x], prow[x]] += 1 for (b, c), k in pairs.items(): forward[b][c] += k backward[c][b] += k fmap = {b: cs.most_common(1)[0][0] for b, cs in forward.items()} bmap = {c: bs.most_common(1)[0][0] for c, bs in backward.items()} if where is not None: for y in range(h): row, prow = board_rows[v + y], ps[y] for x in range(min(len(row), len(prow))): if fmap[row[x]] != prow[x] or bmap[prow[x]] != row[x]: where.append((y, x, row[x], prow[x].hex())) return sum(k for (b, c), k in pairs.items() if fmap[b] != c or bmap[c] != b) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--frames", type=int, default=600) parser.add_argument("--every", type=int, default=20) parser.add_argument("--first", type=int, default=60, help="first compared ProSystem frame") parser.add_argument("--out", type=Path, default=ROOT / "tests" / "detector_runs" / "prosystem") parser.add_argument("--fault", choices=["shift"]) parser.add_argument("--where", action="store_true", help="locate the first difference") parser.add_argument("--offsets", type=int, default=4, help="largest frame offset searched") parser.add_argument("--frame-offset", type=int, help="fix the frame offset instead of fitting it (a static first frame " "fits every offset; session 7 fixes it from the RAM alignment)") # fmt: skip args = parser.parse_args() args.out.mkdir(parents=True, exist_ok=True) began = time.monotonic() ps = prosystem_frames(args.cart, args.frames, args.every, args.out) system = System.from_rom(args.cart, start="direct") tv = Television(system.board.maria, keep=1, first_line=BOARD_FIRST, lines=BOARD_LINES) board: dict[int, list[bytes]] = {} span = range(-args.offsets, args.offsets + 1) wanted = {n + d for n in ps for d in span} seen = 0 while tv.count < args.frames + args.offsets: system.step() if tv.count != seen: seen = tv.count if seen in wanted: board[seen] = tv.frames[-1] # alignment on the first compared frame with content compared = sorted(n for n in ps if n >= args.first) best = None for n in compared: for d in span if args.frame_offset is None else [args.frame_offset]: if n + d not in board: continue for v in range(0, 2 * 12 + 1): k = differing(board[n + d], ps[n], v) if k is not None and (best is None or k < best[0]): best = (k, d, v) if best is not None and len({p for row in ps[n] for p in row}) > 1: break _, d, v = best if args.fault == "shift": v += 1 rows = [(n, differing(board[n + d], ps[n], v)) for n in compared if n + d in board] if args.where: # where the differing pixels of the first differing frame lie n = next((n for n, k in rows if k), None) if n is not None: spots: list = [] differing(board[n + d], ps[n], v, spots) print(f"frame {n}: rows {collections.Counter(y for y, *_ in spots).most_common(6)}; " f"columns {collections.Counter(x for _, x, *_ in spots).most_common(6)}; " f"first {spots[:4]}") # fmt: skip same = sum(1 for _, k in rows if k == 0) line = BOARD_FIRST + v print(f"{args.cart.name}: {system.description.summary()}; ProSystem frame n = board frame " f"n{d:+d} (direct starts), ProSystem's first row = board line {line}, clocks " f"{FIRST_CLOCK}-{FIRST_CLOCK + WIDTH - 1}; {time.monotonic() - began:.0f} s") # fmt: skip print( f"{len(rows) - same} of {len(rows)} frames differ" + (f" (seeded fault {args.fault})" if args.fault else "") ) for n, k in rows: if k: print(f" frame {n}: {k} pixels") return 0 if same == len(rows) else 1 if __name__ == "__main__": sys.exit(main())