# SPDX-License-Identifier: MIT """Run ROMs on both detectors (MAME 0.285, Mesen2) and count differing pixels. EMU_TOOLS_GPL=... python3 -I scripts/detectors_compare.py ROM.sfc [ROM.sfc ...] [--jobs 8] Each ROM runs 5 s on MAME (scripts/mame_trace.py) and 300 frames on Mesen2 (mesen2-runner, ``$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes --region auto``, a GPL tool run as a separate program; scripts/emu_tools.py); the last frames are compared at 5 bits per channel over the 224 visible lines. MAME's snapshot is 512 wide (every second column is taken) and has its extra line at the bottom; Mesen2's 239-line frame starts 7 rows above MAME's first line (validation.md, 2026-10-21). A non-zero count means at least one detector is wrong there, and a console run decides (undocumented-behavior U1). Needs Pillow. """ from __future__ import annotations import argparse import concurrent.futures import subprocess import sys import tempfile from pathlib import Path from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) # run with -I: the script directory is not on the path import emu_tools # noqa: E402 (finds mesen2-runner through EMU_TOOLS_GPL) MESEN_TOP = 7 def frames(rom: Path, work: Path) -> tuple[Image.Image, Image.Image] | str: mame_out = work / "mame" subprocess.run([sys.executable, "-I", str(ROOT / "scripts" / "mame_trace.py"), "snes", str(rom), "--no-trace", "--seconds", "5", "--out", str(mame_out)], capture_output=True, check=False) mesen_png = emu_tools.mesen2_frames(rom, [300], work / "mesen", region="auto")[300] snaps = sorted((mame_out / "snap").rglob("*.png")) if not snaps or mesen_png is None: return "no frame" mame = Image.open(snaps[-1]).convert("RGB") if mame.width == 512: mame = mame.resize((256, mame.height), Image.Resampling.NEAREST) mesen = Image.open(mesen_png).convert("RGB") return mame.crop((0, 0, 256, 224)), mesen.crop((0, MESEN_TOP, 256, MESEN_TOP + 224)) def differing(rom: Path) -> tuple[Path, int | str]: with tempfile.TemporaryDirectory() as tmp: got = frames(rom, Path(tmp)) if isinstance(got, str): return rom, got a, b = (img.tobytes() for img in got) n = sum(1 for i in range(0, len(a), 3) if any((a[i + k] >> 3) != (b[i + k] >> 3) for k in range(3))) return rom, n def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("roms", type=Path, nargs="+") parser.add_argument("--jobs", type=int, default=8) args = parser.parse_args() emu_tools.require(emu_tools.MESEN2_RUN) # exit 3, naming EMU_TOOLS_GPL, without it with concurrent.futures.ThreadPoolExecutor(args.jobs) as pool: for rom, n in pool.map(differing, args.roms): print(f"{n!s:>7} {rom.name}") if __name__ == "__main__": main()