#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Read the verdict jsmolka's and alyosha-tas's test ROMs print on screen. Why not r12: the shared library's ``m_test_eval reg`` saves r0-r12, prints "All tests passed" or "Failed test NNN" from ``reg``, then restores r0-r12. So r12 after the evaluation is whatever the ROM held in r12 before it, not the verdict: jsmolka's thumb.gba evaluates r7 and leaves r12 = 0 while its screen says "Failed test 230" (seen on mGBA fd9dc5c, 2026-11-19). A ROM that hangs before its evaluation also leaves r12 = 0. The picture is the verdict. The text is drawn in background mode 4 with the library's 8x8 font at y = 76: "All tests passed" from x = 56, "Failed test NNN" from x = 60 (reference/src/gba-tests/lib/macros.inc, ``m_test_eval``). The glyph masks are read at run time from the fetched ``lib/glyphs.asm`` (MIT, Julian Smolka; the font itself is tonclib's), so nothing of it is copied here. Each ROM is run through a closed-box driver (scripts/referee_run.py's drivers) for ``--frames`` frames, its last frame decoded, and the band read character by character. Verdicts: ``pass``, ``fail N``, or ``no verdict`` (neither text on screen: the ROM hung, crashed or had not finished). python scripts/judge_text.py --emu nba --bios path/to/bios.zip python scripts/judge_text.py --emu mgba reference/src/gba-tests/arm/arm.gba python scripts/judge_text.py --emu board --jobs 8 --bios path/to/bios.zip ``--emu board`` runs this repository's board (``python -m gba_python``, with the interpreter running this script, so run it from the PyPy environment) and reads its picture the same way: the verdict is the screen, never r12. """ from __future__ import annotations import argparse import json import os import re import struct import subprocess import sys import tempfile import zlib from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import referee_run ROOT = Path(__file__).resolve().parents[1] GLYPHS = ROOT / "reference" / "src" / "gba-tests" / "lib" / "glyphs.asm" TREES = ("reference/src/gba-tests", "reference/src/gba-tests-alyosha") TEXT_Y = 76 TEXT_X = (56, 60) # pass, fail (m_text_pos in m_test_eval) # Built on the library but loop for ever drawing a picture (their t001 ends in # "b t001"); judged by eye, not here. PICTURE_ONLY = ("Sprite_Disable_Midline", "Sprite_Disable_on_VRAM_Access") def load_glyphs() -> dict[bytes, str]: """8x8 masks (one byte per row, bit 0 = leftmost dot) keyed to characters from ' '.""" words = [int(w, 16) for w in re.findall(r"0x([0-9A-Fa-f]{8})", GLYPHS.read_text())] glyphs = {} for index in range(len(words) // 2): rows = struct.pack(" tuple[int, int, list[bytes], int]: """A minimal PNG reader for the drivers' output: 8-bit RGB or RGBA, no interlace.""" assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG" pos, idat, width, height, channels = 8, b"", 0, 0, 3 while pos < len(data): (length,) = struct.unpack(">I", data[pos : pos + 4]) kind, body = data[pos + 4 : pos + 8], data[pos + 8 : pos + 8 + length] if kind == b"IHDR": width, height, depth, color = struct.unpack(">IIBB", body[:10]) assert depth == 8 and color in (2, 6), f"unsupported PNG ({depth}, {color})" channels = 3 if color == 2 else 4 elif kind == b"IDAT": idat += body pos += 12 + length raw, stride, rows, previous = ( zlib.decompress(idat), width * channels, [], bytes(width * channels), ) for y in range(height): start = y * (stride + 1) kind, line = raw[start], 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) & 0xFF elif kind == 2: line[i] = (line[i] + up) & 0xFF elif kind == 3: line[i] = (line[i] + (left + up) // 2) & 0xFF elif kind == 4: p = left + up - corner pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner) pred = left if pa <= pb and pa <= pc else (up if pb <= pc else corner) line[i] = (line[i] + pred) & 0xFF rows.append(bytes(line)) previous = line return width, height, rows, channels def read_band(png: Path, glyphs: dict[bytes, str]) -> list[str]: width, _, rows, channels = decode_png(png.read_bytes()) band = [rows[TEXT_Y + dy] for dy in range(8)] dots = [bytes(row[x * channels : x * channels + 3]) for row in band for x in range(width)] # The background is the band's commonest colour: some ROMs repaint the palette # (alyosha-tas memory/PAL_8_bit_writes leaves magenta text on black). background = max(set(dots), key=dots.count) texts = [] for x0 in TEXT_X: chars = [] for cell in range(x0, width - 7, 8): mask = bytearray(8) for dy in range(8): row = band[dy] for dx in range(8): x = cell + dx if bytes(row[x * channels : x * channels + 3]) != background: mask[dy] |= 1 << dx chars.append(glyphs.get(bytes(mask), "?")) texts.append("".join(chars).strip()) return texts def verdict(texts: list[str]) -> str: for text in texts: if text.startswith("All tests passed"): return "pass" match = re.match(r"Failed test (\d+)", text) if match: return f"fail {int(match.group(1))}" return "no verdict" def roms_in_trees() -> list[Path]: """ROMs whose own source evaluates with m_test_eval. The picture tests beside them (ppu/hello, shades, stripes, stripes_x_offset) print no verdict and are judged by eye. A ROM without a source of its own (alyosha-tas prefetcher/bounday_test_1.gba) counts when its folder's sources use the library. """ roms = [] for tree in TREES: for rom in sorted((ROOT / tree).rglob("*.gba")): if rom.stem in PICTURE_ONLY: continue own = rom.with_suffix(".asm") sources = [own] if own.exists() else 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 board_command() -> list[str]: """The board under test: this interpreter running ``-m gba_python``, niced.""" return ["nice", sys.executable, "-m", "gba_python"] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "roms", nargs="*", type=Path, help="default: every ROM built on the library" ) parser.add_argument("--emu", choices=(*referee_run.DRIVERS, "board"), default="mgba") parser.add_argument("--bios", default="free", help="free (default), hle (mGBA only), or a path") parser.add_argument("--frames", type=int, default=600) parser.add_argument("--jobs", type=int, default=1, help="ROMs run at once") parser.add_argument("--json", type=Path, help="also write the results here") parser.add_argument("--set", action="append", default=[], help="board: module.NAME=value") args = parser.parse_args() if args.emu == "board": program = board_command() for setting in args.set: program += ["--set", setting] else: driver = referee_run.DRIVERS[args.emu] if not driver.exists(): print("build it first: python scripts/build_referees.py --nba") return 1 program = [str(driver)] glyphs = load_glyphs() env = dict(os.environ, PYPY_GC_NURSERY="1M") with tempfile.TemporaryDirectory() as scratch: bios = referee_run.bios_args(args.bios, Path(scratch)) roms = [rom.resolve() for rom in (args.roms or roms_in_trees())] def judge(numbered: tuple[int, Path]) -> dict: number, rom = numbered png = Path(scratch) / f"frame{number}.png" command = [*program, str(rom), *bios, "--frames", str(args.frames)] command += ["--png", str(png), "--reg", "r12"] out = subprocess.run( command, capture_output=True, text=True, timeout=7200, env=env, check=False ).stdout reg = re.search(r"^REG r12 ([0-9A-F]+)$", out, re.MULTILINE) texts = read_band(png, glyphs) if png.exists() else [] status = verdict(texts) name = str(rom.relative_to(ROOT)) if rom.is_relative_to(ROOT) else str(rom) r12 = int(reg.group(1), 16) if reg else None print(f"{status:12} r12={r12!s:10} {name}", flush=True) png.unlink(missing_ok=True) return {"rom": name, "status": status, "r12": r12, "screen": texts} with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool: results = list(pool.map(judge, enumerate(roms))) passed = sum(r["status"] == "pass" for r in results) silent = sum(r["status"] == "no verdict" for r in results) print(f"{passed}/{len(results)} pass, {silent} without a verdict on screen") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())