#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 3's exit: boot every licensed dump the cart table types with certainty. Every No-Intro zip in the licensed folder whose description comes from the CC0 software list or a confirmed row (``certainty`` "softlist" or "confirmed") is started from its region's BIOS and run to ``--frame``. The board's frame goes on a contact sheet (``contact.png``, placeholder palette); Dumps that MAME can load from its list are compared with MAME 0.285's frame of the same number (``a7800`` for NTSC dumps, ``a7800p`` for PAL ones, in television.py's crop for each), with the harness settings of milestone 2's frame compare (``scripts/harness.py``: MAME's switches, C17, C18; each counted). ``--region`` limits the run to one region. One JSON line per dump in ``results.jsonl``. nice -n 19 python scripts/sweep_boot.py --frame 400 --jobs 4 """ from __future__ import annotations import argparse import json import os import sys import time import zlib from collections import Counter, defaultdict 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 a7800_python import romsets # noqa: E402 LICENSED = romsets.no_intro(romsets.LICENSED_7800) # --out sets A7800_SWEEP_OUT so the worker processes (forkserver) see it too. OUT = Path(os.environ.get("A7800_SWEEP_OUT", ROOT / "tests" / "detector_runs" / "sweep-m3")) def candidates() -> list[tuple[Path, str]]: from a7800_python.cartridge import formats chosen = [] for path in sorted(LICENSED.glob("*.zip")): if "(Unl)" in path.name: continue try: desc = formats.load(path) except Exception: # the documented refusal continue if desc.console == "7800" and desc.certainty in ("softlist", "confirmed"): chosen.append((path, desc.region)) return chosen def run_one(job: tuple[str, str, int]) -> dict: import harness from frames_mame import mame_snapshots, pairs, read_png from mame_trace import HASH_DIR, softlist, zip_crc from a7800_python.machine import NTSC, PAL from a7800_python.system import System from a7800_python.television import Television, crop_for cart, region, frame = Path(job[0]), job[1], job[2] result = {"name": cart.stem, "region": region} began = time.monotonic() try: system = System.from_rom(cart, PAL if region == "pal" else NTSC) except Exception as error: # noqa: BLE001 - recorded, not hidden result["error"] = f"{type(error).__name__}: {error}" return result board = system.board harness.mame_switches(board) tia = harness.mask_tia_undriven(board) bus = harness.mask_open_bus(board) first_line, lines = crop_for(system.machine) tv = Television(board.maria, keep=1, first_line=first_line, lines=lines) try: while tv.count < frame: system.step() except Exception as error: # noqa: BLE001 result["error"] = f"{type(error).__name__}: {error} at frame {tv.count}" return result picture = tv.frames[-1] result.update(seconds=round(time.monotonic() - began, 1), mode=system.mode, colours=len({b for row in picture for b in row}), c17=tia["differed"], c18=bus["differed"]) # fmt: skip safe = "".join(c if c.isalnum() else "_" for c in cart.stem) (OUT / "frames").mkdir(parents=True, exist_ok=True) (OUT / "frames" / f"{safe}.bin").write_bytes(b"".join(picture)) if softlist(HASH_DIR).get(zip_crc(cart)) is None: result["mame"] = "not in MAME's list (cannot load headerless)" return result snaps = mame_snapshots(cart, frame, frame, OUT / "mame" / safe, driver="a7800p" if region == "pal" else "a7800") # fmt: skip if not snaps: result["mame"] = "no snapshot" return result _, _, rows = read_png(snaps[0]) votes: dict[int, Counter] = defaultdict(Counter) for byte, rgb in pairs(picture, rows, 1): votes[byte][rgb] += 1 result["differ"] = sum(sum(c.values()) - c.most_common(1)[0][1] for c in votes.values()) result["mame_black"] = all(r == b"\0" * len(r) for r in rows) return result def contact_sheet(names: list[str], columns: int = 8, scale: int = 2) -> bytes: from a7800_python.television import LINES, WIDTH, rgb palette = [bytes(rgb(c)) for c in range(256)] w, h = WIDTH // scale, LINES // scale count = len(names) rows_n = (count + columns - 1) // columns sheet = [bytearray(b"\x20\x20\x20" * (w * columns)) for _ in range(h * rows_n)] for index, name in enumerate(names): data = (OUT / "frames" / f"{name}.bin").read_bytes() ox, oy = (index % columns) * w, (index // columns) * h for y in range(h): line = data[y * scale * WIDTH : (y * scale + 1) * WIDTH] out = sheet[oy + y] for x in range(w): out[3 * (ox + x) : 3 * (ox + x) + 3] = palette[line[x * scale]] raw = b"".join(b"\0" + bytes(r) for r in sheet) def chunk(kind: bytes, body: bytes) -> bytes: import struct return (struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))) # fmt: skip import struct header = struct.pack(">IIBBBBB", w * columns, h * rows_n, 8, 2, 0, 0, 0) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")) # fmt: skip def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--frame", type=int, default=400) parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--only", help="substrings of the names to run, separated by |") parser.add_argument("--out", type=Path, help="run directory under tests/detector_runs/") parser.add_argument("--region", choices=("ntsc", "pal")) args = parser.parse_args() global OUT if args.out: OUT = args.out.resolve() os.environ["A7800_SWEEP_OUT"] = str(OUT) OUT.mkdir(parents=True, exist_ok=True) jobs = [(str(p), r, args.frame) for p, r in candidates() if (not args.only or any(o in p.name for o in args.only.split("|"))) and (not args.region or r == args.region)] print(f"{len(jobs)} dumps typed with certainty", flush=True) results = [] with ProcessPoolExecutor(max_workers=min(args.jobs, 4)) as pool, \ (OUT / "results.jsonl").open("w") as log: # fmt: skip for result in pool.map(run_one, jobs): results.append(result) log.write(json.dumps(result) + "\n") log.flush() print(json.dumps(result), flush=True) names = ["".join(c if c.isalnum() else "_" for c in r["name"]) for r in results if "error" not in r] # fmt: skip (OUT / "contact.png").write_bytes(contact_sheet(names)) booted = sum("error" not in r for r in results) compared = [r for r in results if "differ" in r] exact = sum(r["differ"] == 0 for r in compared) print(f"booted to frame {args.frame}: {booted} of {len(results)}; compared with MAME: " f"{len(compared)}, pixel-exact {exact}; contact sheet {OUT / 'contact.png'}") return 0 if __name__ == "__main__": sys.exit(main())