#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run the port-race probe (probes/port_race) on the board or on Mesen2 and keep its save. python -I scripts/port_race_run.py probe-pack/00-OURS/port-race.sfc --on board --out board.srm python3 -I scripts/port_race_run.py probe-pack/00-OURS/port-race.sfc --on mesen --out mesen.srm python -I scripts/port_race_run.py ROM --on board --out board.srm --check-periods The console writes its .srm through the EverDrive; this gives the board's prediction and Mesen2's answer for scripts/port_race_results.py to set beside it. A run ends when the probe's run state (battery RAM byte $0009) reads 2, or at --frames. ``--on board`` is the reference board in this process, with the S-SMP running: it needs the IPL ROM (``--ipl``, else ``$SNES_IPL``; bring your own, never committed). ``--machine sfc-v1`` is the console's own row (CPU version 1, its refresh position), ``--apu-hz`` overrides the S-SMP resonator (the console measured +2,700 to +2,990 ppm, U8). ``--check-periods`` also records the master clock of every S-CPU write to $2141 and prints, per write loop and speed, the gaps between writes the board's bus gave, to check the M the ROM states. ``--on mesen`` runs mesen2-runner (``$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes --lua``), a GPL tool run as a separate program (its own README is the interface; its code is not read); Mesen2 carries its own IPL. Its values are OBSERVED (Mesen2 b9fa69d via mesen2-runner 0.2.0), never hardware facts. """ from __future__ import annotations import argparse import os import subprocess import sys import tempfile import time from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT.parent / "src")) SRAM_SIZE = 0x2000 STATE = 9 NEXT = 0x10 CELLS = 0x40 CELL = 12 DONE = "PORT RACE RUN DONE" MESEN_LUA = """\ local frames = 0 local finished = false emu.addEventCallback(function() if finished then return end frames = frames + 1 if emu.read({state}, emu.memType.snesSaveRam) == 2 or frames >= {frames} then finished = true local parts = {{}} for i = 0, {size} - 1 do parts[#parts + 1] = string.format("%02x", emu.read(i, emu.memType.snesSaveRam)) end emu.log("SRAM " .. table.concat(parts)) emu.log("FRAMES " .. frames) emu.log("{done}") end end, emu.eventType.endFrame) """ def run_mesen( rom: Path, frames: int, timeout: float, reset_at: int | None = None ) -> tuple[bytes, int]: tools = os.environ.get("EMU_TOOLS_GPL") runner = Path(tools) / "tools" / "mesen2" / "run.py" if tools else None if runner is None or not runner.exists(): raise SystemExit("EMU_TOOLS_GPL is not set or has no tools/mesen2/run.py") with tempfile.TemporaryDirectory() as tmp: script = Path(tmp) / "port_race.lua" script.write_text( MESEN_LUA.format(state=STATE, frames=frames, size=SRAM_SIZE, done=DONE), encoding="utf-8", ) out = Path(tmp) / "run" subprocess.run( [sys.executable, "-I", str(runner), "--machine", "snes", "--rom", str(rom.resolve()), "--out", str(out), "--frames", str(frames), "--lua", str(script), "--region", "ntsc", "--timeout", str(timeout), *(["--reset-at", str(reset_at)] if reset_at else [])], capture_output=True, check=False, ) # fmt: skip log_file = out / "script-log.txt" log = log_file.read_text(encoding="utf-8") if log_file.exists() else "" if DONE not in log: raise SystemExit("Mesen2 run did not finish (mesen2-runner: see its manifest's status)") lines = log.splitlines() sram = bytes.fromhex(next(x for x in lines if x.startswith("SRAM ")).split()[1]) ran = int(next(x for x in lines if x.startswith("FRAMES ")).split()[1]) return sram, ran def run_board( rom: Path, frames: int, machine: str, ipl: bytes, apu_hz: float | None, check: bool ) -> tuple[bytes, int]: from dataclasses import replace from snes_python.board import SNES from snes_python.cartridge import Cartridge from snes_python.machines import MACHINES row = MACHINES[machine.replace("-", "_")] if apu_hz is not None: row = replace(row, apu_hz=apu_hz) snes = SNES(Cartridge(rom.read_bytes()), row, ipl=ipl) gaps: dict[int, Counter] = defaultdict(Counter) if check: apu_write = snes.apu.cpu_write last = [None, None] # the cell, the clock of its last $2141 write def write(port: int, value: int, master_clock: int) -> None: if port & 3 == 1: cell = int.from_bytes(snes.cart.sram[NEXT : NEXT + 2], "little") if last[0] == cell and last[1] is not None: gaps[cell][master_clock - last[1]] += 1 last[0], last[1] = cell, master_clock apu_write(port, value, master_clock) snes.apu.cpu_write = write ran = 0 began = time.monotonic() while ran < frames: snes.run_frames(1) ran += 1 if snes.cart.sram[STATE] == 2: break if ran % 300 == 0: cell = int.from_bytes(snes.cart.sram[NEXT : NEXT + 2], "little") print(f" frame {ran}, cell {cell}, {time.monotonic() - began:.0f} s", flush=True) sram = bytes(snes.cart.sram) if check: seen: dict[tuple[int, int], tuple[int, Counter]] = {} for cell, counter in gaps.items(): o = CELLS + CELL * cell loop, speed = sram[o], sram[o + 1] m = int.from_bytes(sram[o + 5 : o + 7], "little") if (loop, speed) not in seen: seen[loop, speed] = (m, Counter()) seen[loop, speed][1].update(counter) print("loop speed M(ROM) gaps the board gave (clocks x count, most common 3)") for (loop, speed), (m, counter) in sorted(seen.items()): top = ", ".join(f"{g} x{n}" for g, n in counter.most_common(3)) flag = "" if counter.most_common(1)[0][0] == m else " <- differs" print(f"{loop:4} {'fast' if speed else 'slow':5} {m:6} {top}{flag}") return sram, ran def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("rom", type=Path) parser.add_argument("--on", choices=("board", "mesen"), required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--frames", type=int, default=6000) parser.add_argument("--timeout", type=float, default=900.0, help="Mesen2 wall-clock seconds") parser.add_argument("--machine", default="ntsc", help="board: ntsc or sfc-v1") parser.add_argument("--apu-hz", type=float, default=None, help="board: S-SMP resonator, Hz") parser.add_argument("--ipl", type=Path, default=None, help="board: the IPL ROM ($SNES_IPL)") parser.add_argument("--check-periods", action="store_true", help="board: gaps per loop") parser.add_argument("--reset-at", type=int, default=None, help="Mesen2: press reset at the end of this frame (tests resuming)") args = parser.parse_args() began = time.monotonic() if args.on == "mesen": sram, ran = run_mesen(args.rom, args.frames, args.timeout, args.reset_at) else: from snes_python.smp import load_ipl ipl = load_ipl(args.ipl) if ipl is None: raise SystemExit("the board's S-SMP needs the IPL ROM: --ipl or SNES_IPL") sram, ran = run_board(args.rom, args.frames, args.machine, ipl, args.apu_hz, args.check_periods) # fmt: skip args.out.write_bytes(sram) state = "complete" if sram[STATE] == 2 else f"state {sram[STATE]}" print(f"{args.on}: {ran} frames in {time.monotonic() - began:.1f} s, run {state} -> {args.out}") return 0 if __name__ == "__main__": raise SystemExit(main())