#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The board against a closed-box referee, picture by picture: the same BIOS, disc and presses run here and in a libretro core (Genesis Plus GX by default, run as a program through scripts/libretro_run.py; its source is never read), and each chosen frame of the board compared with the referee's frames around it. A referee is a detector, never a judge (docs/validation.md): an agreement says two emulators agree, a difference says where to look. Two things differ for reasons that are not faults and are factored out: - **time**: the two boards do not reach a screen on the same frame (drive timing, the sub CPU's speed). Each board frame is matched to the referee frame within ``--window`` frames that agrees best, and the offset is reported; - **colour**: each emulator turns the console's colours into RGB its own way. The comparison is of the picture's *partition*: two frames agree where one colour of the board's always meets one colour of the referee's and the other way round. The count is of pixels outside the best such one-to-one pairing. A frame that agrees has 0 differing pixels at some offset. The report gives, per frame, the best offset, the differing pixels at it, and the board's PNG and the referee's for looking at with your own eyes. python scripts/referee.py --bios BIOS --disc DISC.cue --frames 300-3000:300 \\ --out runs/referee/sonic [--backup-ram FORMATTED.brm] [--press-at 4830 ...] python scripts/referee.py --verificator --ram-cart --disc DISC.cue --frames 1600 ... ``--wav`` keeps both boards' sound from frame 1 for scripts/compare_audio.py: the board's mix, without FM unless ``--fm`` (slow). """ from __future__ import annotations import argparse import json import shutil import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import libretro_run # noqa: E402 Frame = tuple[int, int, list[int]] # width, height, pixels as 0xRRGGBB def frames_wanted(text: str) -> list[int]: out: set[int] = set() for part in text.split(","): span, _, step = part.partition(":") first, _, last = span.partition("-") out.update(range(int(first), int(last or first) + 1, int(step or 1))) return sorted(out) def differing(a: Frame, b: Frame) -> int: """Pixels outside the best one-to-one pairing of ``a``'s colours with ``b``'s (all of them when the sizes differ).""" (wa, ha, pa), (wb, hb, pb) = a, b if (wa, ha) != (wb, hb): return wa * ha pairs: dict[tuple[int, int], int] = {} for x, y in zip(pa, pb, strict=True): key = (x, y) pairs[key] = pairs.get(key, 0) + 1 # Greedy one-to-one pairing, most common pairs first. used_a: set[int] = set() used_b: set[int] = set() kept = 0 for (x, y), count in sorted(pairs.items(), key=lambda item: -item[1]): if x in used_a or y in used_b: continue used_a.add(x) used_b.add(y) kept += count return len(pa) - kept def write_png(path: Path, frame: Frame) -> None: width, height, pixels = frame rgb = bytearray() for value in pixels: rgb += bytes(((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)) libretro_run.write_png(path, width, height, bytes(rgb)) def run_referee(core: str, disc: Path, bios: Path, work: Path, wanted: set[int], options: dict[str, str], press_at: list[int], press_for: int, wav: Path | None) -> dict[int, Frame]: # fmt: skip for sub in ("system", "save"): (work / sub).mkdir(parents=True, exist_ok=True) for name in ("bios_CD_U.bin", "bios_CD_E.bin", "bios_CD_J.bin"): shutil.copyfile(bios, work / "system" / name) frames: dict[int, Frame] = {} def keep(n: int, width: int, height: int, rgb: bytes) -> None: frames[n] = (width, height, [(rgb[i] << 16) | (rgb[i + 1] << 8) | rgb[i + 2] for i in range(0, len(rgb), 3)]) # fmt: skip libretro_run.run(libretro_run.CORES[core], disc.resolve(), work, sorted(wanted), options, press_at, press_for, wav, on_frame=keep) # fmt: skip return frames def run_board(args: argparse.Namespace, bios: Path, wanted: list[int], wav: Path | None) -> dict[int, Frame]: # fmt: skip from megadrive_python.io import BUTTONS from megadrive_python.wav import write_wav from segacd_python.console import build from segacd_python.disc import Disc from segacd_python.memory import formatted_backup_ram from segacd_python.ramcart import RAMCartridge disc = Disc.open(args.disc, ROOT / "runs/discs") if args.disc else None backup = args.backup_ram.read_bytes() if args.backup_ram else formatted_backup_ram() system, device = build("genesis", bios.read_bytes(), RAMCartridge() if args.ram_cart else None, disc=disc, backup_ram=backup) # fmt: skip system.board.fm.enabled = args.fm pad = system.board.io.ports[0].device start = BUTTONS["start"] want = set(wanted) frames: dict[int, Frame] = {} audio: list[tuple[int, int]] = [] began = time.time() for n in range(1, wanted[-1] + 1): pad.pressed = start if any(0 <= n - at < args.press_for for at in args.press_at) else 0 # The drawing switch gates only the pixels (megadrive-python state version 2): # frames nobody looks at are not drawn. system.vdp.undrawn_frame = n not in want system.run_frame() if wav is not None: audio.extend(system.take_audio()) else: system.board.fm.take_samples() system.board.psg.take_samples() for source in device.audio_sources: source.take_samples(system.mclk) if n in want: rows = system.vdp.renderer.frame_rgb() frames[n] = (len(rows[0]), len(rows), [value for row in rows for value in row]) if args.report and n % args.report == 0: print(f"[board {n}] {time.time() - began:.0f} s", file=sys.stderr, flush=True) if wav is not None: write_wav(wav, audio, system.audio.sample_rate) return frames def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--core", default="gpgx", choices=sorted(libretro_run.CORES)) bios = parser.add_mutually_exclusive_group(required=True) bios.add_argument("--bios", type=Path, help="your own Sega CD BIOS (never committed)") bios.add_argument("--verificator", action="store_true", help="mcd-verificator in the BIOS's place") # fmt: skip parser.add_argument("--disc", type=Path, help="a .cue (or a zip of one)") parser.add_argument("--ram-cart", action="store_true") parser.add_argument("--backup-ram", type=Path, help="the board's backup RAM image") parser.add_argument("--frames", required=True, help="board frames: N,A-B:STEP") parser.add_argument("--window", type=int, default=60, help="referee frames either side") parser.add_argument("--press-at", type=lambda t: [int(n) for n in t.split(",") if n], default=[], help="frames to press Start at, on both boards") # fmt: skip parser.add_argument("--press-for", type=int, default=6) parser.add_argument("--option", action="append", default=[], help="core option KEY=VALUE") parser.add_argument("--wav", action="store_true", help="keep both boards' sound") parser.add_argument("--fm", action="store_true", help="run the board's FM generator (slow; off, the board's mix " "has no FM, which suits passages that use none)") # fmt: skip parser.add_argument("--report", type=int, default=0) parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() bios_path = libretro_run.VERIFICATOR if args.verificator else args.bios wanted = frames_wanted(args.frames) around = {m for n in wanted for m in range(max(1, n - args.window), n + args.window + 1)} out = args.out out.mkdir(parents=True, exist_ok=True) disc = args.disc if disc is not None and disc.suffix.lower() == ".zip": from segacd_python.disc import Disc # unpacks it beside the cache Disc.open(disc, ROOT / "runs/discs") disc = sorted((ROOT / "runs/discs" / disc.stem).rglob("*.cue"))[0] options = dict(option.split("=", 1) for option in args.option) referee = run_referee(args.core, disc, bios_path, (out / args.core).resolve(), around, options, args.press_at, args.press_for, out / f"{args.core}.wav" if args.wav else None) # fmt: skip board = run_board(args, bios_path, wanted, out / "board.wav" if args.wav else None) rows = [] for n in wanted: mine = board[n] best = None for m in sorted(referee, key=lambda m: (abs(m - n), m)): if abs(m - n) > args.window: continue count = differing(mine, referee[m]) if best is None or count < best[1]: best = (m, count) if count == 0: break write_png(out / f"board.f{n:05d}.png", mine) if best is not None: write_png(out / f"{args.core}.f{best[0]:05d}.png", referee[best[0]]) width, height, _ = mine rows.append({"frame": n, "referee_frame": best[0] if best else None, "offset": best[0] - n if best else None, "differing": best[1] if best else None, "pixels": width * height}) # fmt: skip print(f"frame {n:6d}: best {args.core} frame {best[0] if best else '-':>6} " f"(offset {best[0] - n if best else 0:+d}), differing pixels " f"{best[1] if best else '-'} of {width * height}") # fmt: skip agreeing = sum(1 for row in rows if row["differing"] == 0) print(f"{agreeing} of {len(rows)} frames agree with {args.core} within {args.window} frames") (out / "referee.json").write_text(json.dumps({"core": args.core, "rows": rows}, indent=1)) return 0 if __name__ == "__main__": sys.exit(main())