#!/usr/bin/env python3 """Run the test ROMs on mGBA or NanoBoyAdvance (detectors) through their drivers. scripts/mgba_driver.c and scripts/nba_driver/ share one command line and one output format; ``--emu`` picks which runs (mGBA by default). Three result protocols, all read without looking at the screen: - ``r12``: jsmolka's convention, shared by alyosha-tas's tests built on his library: the evaluation leaves 0 in r12 when every test passed, else the number of the first failed test. Any ROM whose source uses ``m_test_eval``. - ``suite``: endrift's mGBA suite writes "END: passes/total" for each of its 14 sub-suites through mGBA's debug port; the runner selects each sub-suite with the D-pad and A, as a player would. - ``shot``: everything else (NBA hw-test, destoer, Hades-Tests, AGBEEG, the AGS aging cartridge): run a fixed number of frames and save the last frame as a PNG under tests/referee_runs/, to be compared by eye with the hardware photograph or the expected screenshot (docs/validation.md). The BIOS is chosen with ``--bios``: ``free`` (Cult-of-GBA's MIT BIOS, the default), ``hle`` (mGBA's built-in high-level emulation, no BIOS file) or a path to your own dump (``.zip`` read in place). Nintendo's BIOS is never fetched or committed. python scripts/referee_run.py r12 python scripts/referee_run.py suite --bios ~/bios/gba_bios.bin python scripts/referee_run.py shot tests/test_roms/agbeeg/AGBEEG_AGING_CARTRIDGE.gba --frames 900 """ from __future__ import annotations import argparse import json import re import subprocess import sys import tempfile import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] DRIVERS = { "mgba": ROOT / "reference" / "build" / "mgba" / "mgba_driver", "nba": ROOT / "reference" / "build" / "nba" / "nba_driver", } DRIVER = DRIVERS["mgba"] FREE_BIOS = ROOT / "reference" / "src" / "bios-cult-of-gba" / "bios.bin" RUNS = ROOT / "tests" / "referee_runs" R12_TREES = ("reference/src/gba-tests", "reference/src/gba-tests-alyosha") SUITE = ROOT / "tests" / "test_roms" / "mgba-suite" / "suite.gba" # The order of suites[] in mgba-emu/suite src/main.c. SUITES = ( "Memory tests", "I/O read tests", "Timing tests", "Timer count-up tests", "Timer IRQ tests", "Shifter tests", "Carry tests", "Multiply long tests", "BIOS math tests", "DMA tests", "SIO register R/W tests", "SIO timing tests", "Misc. edge case tests", "Video tests", ) KEY_A, KEY_DOWN = 0x001, 0x080 BOOT_FRAMES = 300 def bios_args(choice: str, scratch: Path) -> list[str]: if choice == "hle": return [] path = FREE_BIOS if choice == "free" else Path(choice).expanduser() if path.suffix == ".zip": # Read the user's own dump in place: unpack to a temporary file only. with zipfile.ZipFile(path) as archive: name = next(n for n in archive.namelist() if not n.endswith("/")) target = scratch / "bios.bin" target.write_bytes(archive.read(name)) path = target return ["--bios", str(path)] def drive(rom: Path, bios: list[str], frames: int, extra: list[str]) -> str: command = [str(DRIVER), str(rom), *bios, "--frames", str(frames), *extra] return subprocess.run(command, capture_output=True, text=True, check=False, timeout=600).stdout def r12_roms() -> list[Path]: roms = [] for tree in R12_TREES: for rom in sorted((ROOT / tree).rglob("*.gba")): sources = list(rom.parent.glob("*.asm")) if any("m_test_eval" in s.read_text(errors="replace") for s in sources): roms.append(rom) return roms def run_r12(bios: list[str], frames: int) -> list[dict]: results = [] for rom in r12_roms(): out = drive(rom, bios, frames, ["--reg", "r12"]) match = re.search(r"^REG r12 ([0-9A-F]+)$", out, re.M) value = int(match.group(1), 16) if match else None status = "pass" if value == 0 else ("no-result" if value is None else f"fail {value}") results.append({"rom": str(rom.relative_to(ROOT)), "status": status}) print(f"{status:12} {rom.relative_to(ROOT)}") return results def run_suite(bios: list[str], frames: int) -> list[dict]: results = [] for index, name in enumerate(SUITES): # Nintendo's BIOS plays its logo for about 3 s; wait it out whatever the BIOS. keys, frame = ["--keys", "0:0"], BOOT_FRAMES for _ in range(index): keys += ["--keys", f"{frame}:{KEY_DOWN}", "--keys", f"{frame + 2}:0"] frame += 4 keys += ["--keys", f"{frame}:{KEY_A}", "--keys", f"{frame + 2}:0"] out = drive(SUITE, bios, frames, keys) begin = re.search(r"BEGIN: (.+)$", out, re.M) end = re.search(r"END: (\d+)/(\d+)", out) passes, total = (int(end.group(1)), int(end.group(2))) if end else (None, None) # mGBA logs "LOG GBA Debug: ...", NanoBoyAdvance "mGBA log: ...". fails = re.findall(r"^(?:LOG GBA Debug|mGBA log): FAIL: (.+)$", out, re.M) results.append( { "suite": name, "ran": begin.group(1) if begin else None, "passes": passes, "total": total, "fails": fails, } ) shown = f"{passes}/{total}" if end else "no END line" print(f"{name:26} {shown}") return results def unzip_rom(rom: Path, scratch: Path) -> Path: """A .zip (a No-Intro dump, read in place) becomes a temporary .gba.""" if rom.suffix != ".zip": return rom with zipfile.ZipFile(rom) as archive: name = next(n for n in archive.namelist() if n.lower().endswith(".gba")) target = scratch / Path(name).name target.write_bytes(archive.read(name)) return target def run_shot(rom: Path, bios: list[str], frames: int, keys: list[str]) -> Path: RUNS.mkdir(parents=True, exist_ok=True) png = RUNS / f"{rom.stem}-{DRIVER.name.split('_')[0]}.png" extra = ["--png", str(png)] for key in keys: extra += ["--keys", key] drive(rom, bios, frames, extra) print(png.relative_to(ROOT)) return png def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("mode", choices=("r12", "suite", "shot")) parser.add_argument("roms", nargs="*", type=Path, help="shot mode: the ROMs") parser.add_argument("--emu", choices=tuple(DRIVERS), default="mgba") parser.add_argument("--bios", default="free", help="free (default), hle (mGBA only), or a path") parser.add_argument("--frames", type=int, help="frames to run (default per mode)") parser.add_argument("--keys", action="append", default=[], help="shot mode: FRAME:MASK") parser.add_argument("--json", type=Path, help="also write the results here") args = parser.parse_args() global DRIVER DRIVER = DRIVERS[args.emu] if not DRIVER.exists(): print("build it first: python scripts/build_referees.py") return 1 with tempfile.TemporaryDirectory() as scratch: bios = bios_args(args.bios, Path(scratch)) if args.mode == "r12": results = run_r12(bios, args.frames or 300) passed = sum(r["status"] == "pass" for r in results) print(f"{passed}/{len(results)} ROMs pass") elif args.mode == "suite": results = run_suite(bios, args.frames or 4300) else: roms = [unzip_rom(rom, Path(scratch)) for rom in args.roms] results = [str(run_shot(rom, bios, args.frames or 600, args.keys)) for rom in roms] if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())