#!/usr/bin/env python3 """Compare the board's picture with NanoBoyAdvance 1.8.3's after the same number of frames. A detector, not a judge (docs/validation.md): NanoBoyAdvance is emulator-derived, so a difference is a question for hardware evidence, never a verdict. Each ROM runs N frames on the board (PyPy, retail BIOS read in place) and on ``reference/build/nba/nba_driver``; the two 240x160 frames are compared pixel for pixel. On a difference both frames and a diff image (differing pixels white) are written under ``tests/frame_runs/``. python scripts/frame_diff.py ROM[.zip] ... [--frames 600] [--keys FRAME:MASK]... python scripts/frame_diff.py --judges # the PPU judge ROMs and the GAMES boots python scripts/frame_diff.py --write ... # record agreed frames in tests/frames_pass.txt """ from __future__ import annotations import argparse import hashlib import struct import subprocess import sys import tempfile import zipfile import zlib from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from referee_run import bios_args # noqa: E402 from gba_python.bios import nointro_dir # noqa: E402 ROOT_NOINTRO = nointro_dir() NBA = ROOT / "reference" / "build" / "nba" / "nba_driver" RUNS = ROOT / "tests" / "frame_runs" PASS = ROOT / "tests" / "frames_pass.txt" #: (ROM, frames): picture judges with hardware photographs, plus jsmolka/alyosha-tas pictures JUDGES = [ ("reference/src/gba-tests/ppu/hello.gba", 320), ("reference/src/gba-tests/ppu/shades.gba", 320), ("reference/src/gba-tests/ppu/stripes.gba", 320), ("reference/src/gba-tests-alyosha/ppu/hello.gba", 320), ("reference/src/gba-tests-alyosha/ppu/shades.gba", 320), ("reference/src/gba-tests-alyosha/ppu/stripes.gba", 320), ("reference/src/gba-tests-alyosha/ppu/stripes_x_offset.gba", 320), ("reference/src/hw-test/ppu/bgpd/bgpd.gba", 400), ("reference/src/hw-test/ppu/bgx/bgx.gba", 400), ("reference/src/hw-test/ppu/dispcnt-latch/dispcnt-latch.gba", 400), ("reference/src/hw-test/ppu/greenswap/greenswap.gba", 400), ("reference/src/hw-test/ppu/sprite-hmosaic/sprite-hmosaic.gba", 400), ] #: (No-Intro name, frames): commercial boots from the local set, a detector over real scenes. #: The later frames are past where NBA's driver used to slip a frame (it ran 280,896 cycles per #: frame from its last overrun; nba_driver now counts pictures, docs/validation.md rung 3). GAMES = [ ("Advance Wars (USA).zip", 600), ("Advance Wars (USA).zip", 900), ("Castlevania - Aria of Sorrow (USA).zip", 900), ("F-Zero - Maximum Velocity (USA, Europe).zip", 600), ("F-Zero - Maximum Velocity (USA, Europe).zip", 1200), ("Golden Sun (USA, Europe).zip", 1200), ("Kirby - Nightmare in Dream Land (USA).zip", 900), ("Legend of Zelda, The - The Minish Cap (USA).zip", 900), ("Mario Kart - Super Circuit (Europe).zip", 900), ] def decode_png(data: bytes) -> list[tuple[int, int, int]]: """RGB pixels of an 8-bit RGB or RGBA PNG (every filter type).""" position = 8 idat = b"" width = height = channels = 0 while position < len(data): (length,) = struct.unpack(">I", data[position : position + 4]) kind = data[position + 4 : position + 8] body = data[position + 8 : position + 8 + length] if kind == b"IHDR": width, height, _, color_type = struct.unpack(">IIBB", body[:10]) channels = 4 if color_type == 6 else 3 elif kind == b"IDAT": idat += body position += 12 + length raw = zlib.decompress(idat) stride = width * channels previous = bytearray(stride) pixels = [] for y in range(height): start = y * (stride + 1) kind = raw[start] line = bytearray(raw[start + 1 : start + 1 + stride]) for i in range(stride): left = line[i - channels] if i >= channels else 0 up = previous[i] corner = previous[i - channels] if i >= channels else 0 if kind == 1: line[i] = (line[i] + left) & 255 elif kind == 2: line[i] = (line[i] + up) & 255 elif kind == 3: line[i] = (line[i] + ((left + up) >> 1)) & 255 elif kind == 4: p = left + up - corner pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner) predictor = left if pa <= pb and pa <= pc else up if pb <= pc else corner line[i] = (line[i] + predictor) & 255 pixels.extend((line[i], line[i + 1], line[i + 2]) for i in range(0, stride, channels)) previous = line return pixels def encode_png(pixels: list[tuple[int, int, int]]) -> bytes: rows = bytearray() for y in range(160): rows.append(0) for r, g, b in pixels[y * 240 : y * 240 + 240]: rows += bytes((r, g, b)) def chunk(kind: bytes, body: bytes) -> bytes: return ( struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body)) ) return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 240, 160, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(bytes(rows), 9)) + chunk(b"IEND", b"") ) def rom_file(path: Path, scratch: Path) -> Path: if path.suffix != ".zip": return path with zipfile.ZipFile(path) as archive: name = next(n for n in archive.namelist() if n.lower().endswith(".gba")) target = scratch / "rom.gba" target.write_bytes(archive.read(name)) return target def board_frame(rom: Path, frames: int, keys: list[str]) -> bytes: command = [ str(ROOT / ".venv-pypy" / "bin" / "python"), "-m", "gba_python", str(rom), "--frames", str(frames), "--no-stop", ] for key in keys: command += ["--keys", key] with tempfile.TemporaryDirectory() as scratch: png = Path(scratch) / "board.png" subprocess.run([*command, "--png", str(png)], capture_output=True, check=True, cwd=ROOT) return png.read_bytes() def nba_frame(rom: Path, frames: int, keys: list[str]) -> bytes: with tempfile.TemporaryDirectory() as scratch: bios = bios_args(str(_retail()), Path(scratch)) png = Path(scratch) / "nba.png" extra = [] for key in keys: extra += ["--keys", key] subprocess.run( [str(NBA), str(rom), *bios, "--frames", str(frames), *extra, "--png", str(png)], capture_output=True, check=False, timeout=900, ) return png.read_bytes() def _retail() -> Path: from gba_python import bios as bios_module return Path(bios_module.find(None).source) def compare(job: tuple[str, int, list[str]]) -> dict: name, frames, keys = job path = (ROOT / name) if not Path(name).is_absolute() else Path(name) with tempfile.TemporaryDirectory() as scratch: rom = rom_file(path, Path(scratch)) board_png = board_frame(rom, frames, keys) nba_png = nba_frame(rom, frames, keys) board, nba = decode_png(board_png), decode_png(nba_png) differ = [i for i, (a, b) in enumerate(zip(board, nba, strict=True)) if a != b] result = { "rom": name, "frames": frames, "keys": keys, "differ": len(differ), "sha256": hashlib.sha256(bytes(c for p in board for c in p)).hexdigest()[:16], } if differ: RUNS.mkdir(parents=True, exist_ok=True) stem = f"{path.stem}-{frames}" (RUNS / f"{stem}-board.png").write_bytes(board_png) (RUNS / f"{stem}-nba.png").write_bytes(nba_png) marks = set(differ) diff = [(255, 255, 255) if i in marks else (0, 0, 0) for i in range(240 * 160)] (RUNS / f"{stem}-diff.png").write_bytes(encode_png(diff)) rows = sorted({i // 240 for i in differ}) result["rows"] = f"{rows[0]}-{rows[-1]} ({len(rows)} rows)" return result def pass_name(rom: str) -> str: """How tests/frames_pass.txt names a ROM: repository-relative, or ``nointro:NAME.zip``.""" path = Path(rom) games = ROOT_NOINTRO / "Nintendo - Game Boy Advance" if path.is_absolute() and path.parent == games: return f"nointro:{path.name}" return rom def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("roms", nargs="*") parser.add_argument("--frames", type=int, default=600) parser.add_argument("--keys", action="append", default=[]) parser.add_argument("--judges", action="store_true") parser.add_argument("--write", action="store_true") parser.add_argument("--jobs", type=int, default=12) args = parser.parse_args() jobs = [(rom, frames, []) for rom, frames in JUDGES] if args.judges else [] games = ROOT_NOINTRO / "Nintendo - Game Boy Advance" if args.judges and games.exists(): jobs += [(str(games / name), frames, []) for name, frames in GAMES] jobs += [(rom, args.frames, args.keys) for rom in args.roms] with ProcessPoolExecutor(args.jobs) as pool: results = list(pool.map(compare, jobs)) agreed = [] for result in results: verdict = ( "same" if not result["differ"] else f"{result['differ']} px differ, rows {result['rows']}" ) print(f"{result['rom']} @{result['frames']}: {verdict} [{result['sha256']}]") if not result["differ"]: agreed.append(f"{pass_name(result['rom'])}\t{result['frames']}\t{result['sha256']}") if args.write: PASS.write_text("\n".join(agreed) + "\n") return 0 if __name__ == "__main__": sys.exit(main())