#!/usr/bin/env python3 """Milestone 7: run every cartridge of a romset on our system and on MAME, and compare the frame each shows after N seconds. MAME is a detector (docs/validation.md): a differing frame is a question, not a verdict. Each cartridge is run on the MAME driver below for ``--seconds`` and its exit snapshot kept; ours runs from MAME's power-on VDP phase (solved from the locksteps, docs/mame-oracle.md) and through the same BIOS, to the same cycle, and the last complete frame is compared as colours (as ``replay_mame_io.py`` does). python scripts/compat_sweep.py mastersystem --seconds 10 --jobs 30 python scripts/compat_sweep.py sg1000 --limit 20 Results go to ``tests/compat/.csv`` (gitignored): name, board, status (same / differs / unsupported / error; mame-board when MAME runs the image on another board, see mame_media.py; sms-mode, missing), differing pixels, seconds. """ from __future__ import annotations import argparse import csv import shutil import subprocess import sys import tempfile import time import traceback import zipfile from concurrent.futures import ProcessPoolExecutor, as_completed 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 lockstep_mame import load_bios # noqa: E402 from mame_media import cart_arguments, mame_board # noqa: E402 from replay_mame_io import compare_frame # noqa: E402 from romsets import MAME_ROMPATH # noqa: E402 from romsets import carts as romset # noqa: E402 from sms_python.board import MACHINES # noqa: E402 from sms_python.cartridge import BOARDS, Cartridge, board_for, load_image # noqa: E402 from sms_python.system import System # noqa: E402 MAME = "/usr/games/mame" ROMPATH = str(MAME_ROMPATH) # romset directory -> (MAME driver, our machine, MAME's power-on VDP phase in mclocks, # where our active picture sits in MAME's snapshot). The offsets were found by full # search on the replays; a search per cartridge can pick a wrong one on a mostly # uniform picture. SYSTEMS = { "sg1000": ("sg1000", "sg1000", 139460, (12, 12)), "mastersystem": ("sms", "sms2", 142245, (2, 16)), "gamegear": ("gamegear", "gamegear", 114877, (0, 0)), } CLOCK = 3_579_545 # MAME's Game Gear blends each frame with the last ("LCD Persistence Hack", on by # default in sms.cpp); off here, so its snapshot is the frame the VDP drew. NO_PERSISTENCE_LUA = """\ local port = manager.machine.ioport.ports[":PERSISTENCE"] if port then port.fields["LCD Persistence Hack"].user_value = 0 end """ def _image_suffix(path: Path) -> str: with zipfile.ZipFile(path) as archive: return Path(archive.namelist()[0]).suffix.lower() def mame_power_on_status(vdp) -> None: """Reproduce a MAME artefact for diagnosis, never for the record. MAME 0.285's 315_5124 device_reset sets its pending-flags timer to "never", so the frame and overflow flags of the first frame are not committed before the first status read, which returns $C0 where the VDP tests' timing gives $9F (docs/undocumented-behavior.md, open item 7). With this, a cartridge that differs only because of that one read shows as the same. """ read_status = vdp.read_status def first_read() -> int: vdp.read_status = read_status value = read_status() return 0xC0 if value & 0x80 else value vdp.read_status = first_read # A disk takes longer to start than a cartridge: Disk BASIC is ready at about 15 s. DISK_SECONDS = 30 def run_disk(image: bytes, row: dict, seconds: int) -> None: """An SF-7000 disk: MAME's ``sf7000`` and ours, both booting it through the IPL.""" _, _, phase, offset = SYSTEMS["sg1000"] row["board"] = "sf7000" with tempfile.TemporaryDirectory() as work: work_path = Path(work) disk = work_path / "disk.sf" disk.write_bytes(image) subprocess.run( [MAME, "sf7000", "-rompath", ROMPATH, "-flop", str(disk), "-homepath", work, "-snapshot_directory", str(work_path / "snap"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", str(seconds)], cwd=work, check=True, capture_output=True, timeout=600, ) # fmt: skip snapshots = sorted((work_path / "snap").glob("*/*.png")) if not snapshots: row["status"] = "error: no MAME snapshot" return system = System( MACHINES["sf7000"], None, load_bios("sf7000"), audio=False, vdp_phase=phase, disk=bytearray(image), ) # fmt: skip system.run_cycles(seconds * CLOCK) system.run_frame() wrong, total, _ = compare_frame(system.board, snapshots[-1], None, offset) row["status"] = "same" if wrong == 0 else "differs" row["differ"] = f"{wrong}/{total}" def run_one(path: Path, system_name: str, seconds: int, mame_quirks: bool = False) -> dict: driver, machine_name, phase, offset = SYSTEMS[system_name] row = {"name": path.stem, "board": "", "status": "", "differ": "", "seconds": ""} started = time.time() other_board, theirs = False, "" if not path.exists(): # A mirror being synced can drop a file between the listing and the run. row["status"] = "missing" return row try: # A mirror being synced can also hide a file for a moment: retry. for attempt in range(5): try: image = load_image(path) break except FileNotFoundError: if attempt == 4: raise time.sleep(5) if _image_suffix(path) in (".sf", ".sf7"): run_disk(image, row, max(seconds, DISK_SECONDS)) return row board = board_for(image) row["board"] = board if board not in BOARDS: row["status"] = "unsupported" return row # An unlisted image can be put on another board by MAME's guess (mame_media.py); # if its frame then differs, or MAME fails, MAME was not running the same # machine, and that is the result. theirs = mame_board(image, driver) other_board = theirs != board with tempfile.TemporaryDirectory() as work: work_path = Path(work) cart = work_path / ( "cart" + {"sg1000": ".sg", "gamegear": ".gg"}.get(system_name, ".sms") ) cart.write_bytes(image) if system_name == "gamegear" and _image_suffix(path) == ".sms": # SMS-compatibility mode: MAME squeezes 256x192 onto the 160x144 LCD # by a filter of its own; how the real Game Gear does it is not # documented (msvdp section 14), so there is nothing to compare. row["status"] = "sms-mode" return row # Always an autoboot script: MAME soft-resets after running one, and the # VDP phases above were solved from runs that had one (mame_trace.py). lua = work_path / "setup.lua" lua.write_text(NO_PERSISTENCE_LUA, encoding="utf-8") extra = ["-autoboot_script", str(lua)] media = cart_arguments(image, driver, work_path, cart, ROMPATH) subprocess.run( [MAME, driver, *media, "-homepath", work, "-snapshot_directory", str(work_path / "snap"), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", str(seconds), *extra], cwd=work, check=True, capture_output=True, timeout=600, ) # fmt: skip snapshots = sorted((work_path / "snap").glob("*/*.png")) if not snapshots: row["status"] = "error: no MAME snapshot" return row # Keep MAME's snapshot for later analysis (scripts/fit_phase.py). cache = ROOT / "tests" / "compat" / "snaps" / system_name cache.mkdir(parents=True, exist_ok=True) shutil.copyfile(snapshots[-1], cache / f"{path.stem}.png") system = System( MACHINES[machine_name], Cartridge.from_file(cart, board=board), load_bios(driver), audio=False, vdp_phase=phase, ) system.board.vdp.render = False if mame_quirks: mame_power_on_status(system.board.vdp) target = seconds * CLOCK # MAME's -seconds_to_run finishes the frame in progress before its exit # snapshot (a one-frame offset found on Halley Wars, GG), so compare our # first frame completed after the target time. Render only near the end. system.run_cycles(max(0, target - 2 * 59_736) - system.cycles) system.board.vdp.render = True system.run_cycles(target - system.cycles) system.run_frame() wrong, total, _ = compare_frame(system.board, snapshots[-1], None, offset) row["status"] = "same" if wrong == 0 else "differs" row["differ"] = f"{wrong}/{total}" if wrong and other_board: row["status"], row["differ"] = "mame-board", f"{wrong}/{total}, MAME: {theirs}" except subprocess.CalledProcessError as error: if other_board: row["status"], row["differ"] = "mame-board", f"MAME failed, MAME: {theirs}" else: row["status"] = f"error: {type(error).__name__}: {error}"[:200] except Exception as error: # a crash is a result too row["status"] = f"error: {type(error).__name__}: {error}"[:200] traceback.print_exc(file=sys.stderr) finally: row["seconds"] = f"{time.time() - started:.1f}" return row def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("system", choices=sorted(SYSTEMS)) parser.add_argument("--seconds", type=int, default=10) parser.add_argument("--jobs", type=int, default=16) parser.add_argument("--limit", type=int, help="only the first N cartridges") parser.add_argument("--match", help="only cartridges whose name contains this") parser.add_argument( "--mame-quirks", action="store_true", help="reproduce MAME's power-on status read (diagnosis only; see mame_power_on_status)", ) parser.add_argument( "--rerun", nargs="?", const="error", metavar="STATUS", help="re-run only the last CSV's rows with this status (default: error)", ) args = parser.parse_args() carts = [ p for p in romset(args.system) if args.match is None or args.match.lower() in p.name.lower() ] # fmt: skip if args.limit: carts = carts[: args.limit] record = ROOT / "tests" / "compat" / f"{args.system}.csv" record.parent.mkdir(parents=True, exist_ok=True) # Diagnosis runs never overwrite the record. out = record.with_stem(f"{args.system}-mame-quirks") if args.mame_quirks else record rows = [] if args.rerun: previous = list(csv.DictReader(record.open(encoding="utf-8"))) again = {r["name"] for r in previous if r["status"].startswith(args.rerun)} rows = [r for r in previous if r["name"] not in again] carts = [c for c in carts if c.stem in again] elif (args.match or args.limit) and out.exists(): # A partial run replaces its own rows and keeps the rest of the record. chosen = {c.stem for c in carts} previous = list(csv.DictReader(out.open(encoding="utf-8"))) rows = [r for r in previous if r["name"] not in chosen] with ProcessPoolExecutor(args.jobs) as pool: futures = { pool.submit(run_one, cart, args.system, args.seconds, args.mame_quirks): cart for cart in carts } for done, future in enumerate(as_completed(futures), 1): row = future.result() rows.append(row) print(f"[{done}/{len(carts)}] {row['status']:<12} {row['differ']:>12} {row['name']}", flush=True) # fmt: skip if not rows: print("no cartridges") return 0 rows.sort(key=lambda r: r["name"]) with out.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) counts: dict[str, int] = {} for row in rows: key = row["status"].split(":")[0] counts[key] = counts.get(key, 0) + 1 print(f"{len(rows)} cartridges: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items()))) print(f"written to {out}") return 0 if __name__ == "__main__": sys.exit(main())