#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 2, exit (d): the board's frames against MAME 0.285's snapshots. Both machines start from the NTSC BIOS with no input pressed (the "scripted start" is no input: the titles' attract modes) and run ``--frames`` frames; MAME saves a snapshot every ``--every`` frames (Lua ``video:snapshot``), the board keeps the same frames through its television stage. Colours are compared without any palette: the board emits colour bytes, MAME RGB, so two frames are the same picture when one consistent map from colour byte to RGB, built over the whole run, explains every pixel of both. A frame differs when its pixels need a second RGB for a colour byte already mapped (or the layout differs). The first differing frame is written as two PNGs for inspection. MAME is a detector: a difference is a question. python scripts/frames_mame.py ".../Atari - Atari 7800 (BIN)/Asteroids (USA).zip" --frames 760 """ from __future__ import annotations import argparse import os import struct import subprocess import sys import zlib from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) import harness # noqa: E402 from mame_trace import BIOS_DIR, HASH_DIR, MAME, softlist, zip_crc # noqa: E402 from a7800_python.system import System # noqa: E402 from a7800_python.television import Television, frame_png # noqa: E402 LUA = """ local frames = 0 local snaplog = io.open("snaps.txt", "w") local script = {SCRIPT} local fields = { up = {":joysticks", "P1 Up"}, down = {":joysticks", "P1 Down"}, left = {":joysticks", "P1 Left"}, right = {":joysticks", "P1 Right"}, b1 = {":buttons", "P1 Button 1"}, b2 = {":buttons", "P1 Button 2"}, reset = {":console_buttons", "Reset"}, select = {":console_buttons", "Select"}, pause = {":console_buttons", "Pause"}, } local function set(name, on) local f = fields[name] manager.machine.ioport.ports[f[1]].fields[f[2]]:set_value(on and 1 or 0) end emu.register_frame_done(function() frames = frames + 1 local actions = script[frames + 1] -- applied as frame frames + 1 starts if actions then for _, a in ipairs(actions) do if a == "none" or a == "b1" or a == "b2" or a == "b12" or a == "up" or a == "down" or a == "left" or a == "right" then for _, n in ipairs({"up", "down", "left", "right", "b1", "b2"}) do set(n, false) end if a == "b1" or a == "b12" then set("b1", true) end if a == "b2" or a == "b12" then set("b2", true) end if fields[a] and a ~= "b1" and a ~= "b2" then set(a, true) end elseif a == "switches-off" then set("reset", false); set("select", false); set("pause", false) else set(a, true) end end end if frames % EVERY == 0 or AT[frames] then manager.machine.video:snapshot() snaplog:write(frames .. "\\n"); snaplog:flush() if RAMDUMP then local space = manager.machine.devices[":maincpu"].spaces["program"] local parts = {} for a = 0x1800, 0x27ff do parts[#parts + 1] = string.format("%02X", space:read_u8(a)) end local ramlog = io.open("ram.txt", "a") ramlog:write(frames .. " " .. table.concat(parts) .. "\\n"); ramlog:close() end end if frames >= LAST then manager.machine:exit() end end) """ ACTIONS = ("up", "down", "left", "right", "b1", "b2", "b12", "none", "reset", "select", "pause", "switches-off") # fmt: skip def parse_script(items: list[str]) -> dict[int, list[str]]: """``FRAME:ACTION`` items as controller_run.py takes them (ProLine port 0 and the console switches; a direction or button item releases the others).""" script: dict[int, list[str]] = {} for item in items: frame, action = item.split(":", 1) if action not in ACTIONS: raise SystemExit(f"unknown action {action!r}") script.setdefault(int(frame), []).append(action) return script def apply_board(system, actions: list[str]) -> None: """The board side of one frame's script items.""" board = system.board for action in actions: if action in ("reset", "select", "pause", "switches-off"): # SWCHB D0 / D1 / D3, active low bit = {"reset": 1, "select": 2, "pause": 8, "switches-off": 0}[action] if action == "switches-off": board.riot.input_b |= 0x0B else: board.riot.input_b &= ~bit elif action in ("b1", "b2", "b12", "none"): system.controllers.set(0, left_button=action in ("b1", "b12"), right_button=action in ("b2", "b12")) # fmt: skip else: system.controllers.set(0, **{action: True}) def lua_script(script: dict[int, list[str]]) -> str: return ", ".join(f"[{f}] = {{{', '.join(repr(a).replace(chr(39), chr(34)) for a in acts)}}}" for f, acts in sorted(script.items())) # fmt: skip def read_png(path: Path) -> tuple[int, int, list[bytes]]: """A minimal PNG reader for MAME's 8-bit RGB/RGBA snapshots: (width, height, rows of RGB).""" data = path.read_bytes() pos, idat, width = 8, b"", 0 while pos < len(data): length, kind = struct.unpack(">I4s", data[pos : pos + 8]) body = data[pos + 8 : pos + 8 + length] if kind == b"IHDR": width, height, _depth, colour = struct.unpack(">IIBB", body[:10]) channels = {2: 3, 6: 4}[colour] elif kind == b"IDAT": idat += body pos += 12 + length raw = zlib.decompress(idat) stride = width * channels rows, previous = [], bytearray(stride) for y in range(height): kind = raw[y * (stride + 1)] line = bytearray(raw[y * (stride + 1) + 1 : (y + 1) * (stride + 1)]) for x in range(stride): a = line[x - channels] if x >= channels else 0 b = previous[x] c = previous[x - channels] if x >= channels else 0 if kind == 1: line[x] = (line[x] + a) & 0xFF elif kind == 2: line[x] = (line[x] + b) & 0xFF elif kind == 3: line[x] = (line[x] + (a + b) // 2) & 0xFF elif kind == 4: p = a + b - c pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) line[x] = (line[x] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF previous = line rows.append(bytes(line) if channels == 3 else b"".join(bytes(line[i : i + 3]) for i in range(0, stride, channels))) # fmt: skip return width, height, rows def mame_snapshots(cart: Path, frames: int, every: int, out: Path, driver: str = "a7800", script: dict[int, list[str]] | None = None, at: list[int] | None = None, ram: bool = False) -> list[Path]: # fmt: skip software = softlist(HASH_DIR)[zip_crc(cart)][0] link_dir = out / "softlist" / "a7800" link_dir.mkdir(parents=True, exist_ok=True) link = link_dir / f"{software}.zip" if not link.is_symlink(): os.symlink(cart, link) at_table = "{" + ", ".join(f"[{f}] = true" for f in (at or [])) + "}" (out / "frames.lua").write_text(LUA.replace("EVERY", str(every)).replace("LAST", str(frames)) .replace("{SCRIPT}", "{" + lua_script(script or {}) + "}") .replace("AT[", "(" + at_table + ")[") .replace("RAMDUMP", "true" if ram else "false")) # fmt: skip (out / "ram.txt").unlink(missing_ok=True) snap = out / "snap" for stale in snap.rglob("*.png"): # MAME's %i numbering skips names already taken stale.unlink() subprocess.run([MAME, driver, software, "-hashpath", HASH_DIR, "-rompath", f"{BIOS_DIR};{out / 'softlist'}", "-homepath", str(out), "-snapshot_directory", str(snap), "-snapname", "%i", "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-autoboot_script", str(out / "frames.lua")], cwd=out, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # fmt: skip link.unlink() return sorted(snap.rglob("*.png"), key=lambda p: int(p.stem) if p.stem.isdigit() else 0) def snapshot_frames(out: Path) -> list[int]: """The frame number of each snapshot, in order (the Lua's own log).""" return [int(x) for x in (out / "snaps.txt").read_text().split()] STACK_PAGE = range(0x900, 0xA00) # $2100-$21FF in the board's $1800-$27FF array (page 1) def ram_differs(ours: bytes, theirs: bytes) -> list[int]: """Offsets into $1800-$27FF where the two RAMs differ, the stack page left out (interrupt return addresses: where a DLI landed, C1/C4).""" return [i for i in range(len(ours)) if ours[i] != theirs[i] and i not in STACK_PAGE] def pairs(frame: list[bytes], rows: list[bytes], scale: int): for y in range(min(len(rows), len(frame))): row, mrow = frame[y], rows[y] for x in range(320): yield row[x], mrow[3 * x * scale : 3 * x * scale + 3] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cart", type=Path) parser.add_argument("--frames", type=int, default=760) parser.add_argument("--every", type=int, default=20) parser.add_argument("--skip", type=int, default=160, help="frames before comparing (the BIOS)") parser.add_argument("--offsets", type=int, default=2, help="also compare MAME's frame N with the board's N-k..N+k; report the best") parser.add_argument("--mame-switches", action="store_true", help="harness.mame_switches") parser.add_argument("--mask-tia-undriven", action="store_true", help="harness: C17 exclusion") parser.add_argument("--mask-open-bus", action="store_true", help="harness: C18 exclusion") parser.add_argument("--timer-log", type=Path, help="a mame_trace.py error.log of the same run: force its 6532 timer " "reads on the board (C11/C12 exclusion, counted)") # fmt: skip parser.add_argument("--c23-mame", action="store_true", help="detector setting: MAME's rule for C23 (diagnostic, named)") parser.add_argument("--tag", default="", help="suffix for the run directory (parallel runs)") parser.add_argument("--script", nargs="*", default=[], help="FRAME:ACTION items on both machines (up/down/left/right, b1/b2/b12/" "none, reset/select/pause, switches-off)") # fmt: skip parser.add_argument("--at", default="", help="extra snapshot frames, comma-separated") parser.add_argument("--fault", action="append", default=[], help="a seeded board fault") parser.add_argument("--ram", action="store_true", help="also compare the game state: $1800-$27FF outside the stack page " "at each snapshot frame (MAME by Lua read_u8), best offset") # fmt: skip args = parser.parse_args() cart = args.cart.resolve() name = cart.stem.split(" (")[0].replace(" ", "_") out = ROOT / "tests" / "detector_runs" / f"frames-{name}{args.tag}" out.mkdir(parents=True, exist_ok=True) script = parse_script(args.script) at = [int(x) for x in args.at.split(",") if x] snap_paths = mame_snapshots(cart, args.frames, args.every, out, script=script, at=at, ram=args.ram) # fmt: skip mame_ram = {} if args.ram: for line in (out / "ram.txt").read_text().splitlines(): number, hexed = line.split() mame_ram[int(number)] = bytes.fromhex(hexed) ram_mine = {} numbers = snapshot_frames(out) snaps = dict(zip(numbers, snap_paths)) system = System.from_rom(cart) board = system.board notes = [] if args.mame_switches: harness.mame_switches(board) notes.append("switches as MAME's defaults (difficulty A)") if args.fault: board.faults |= set(args.fault) notes.append(f"seeded faults {sorted(args.fault)}") if args.c23_mame: board.faults.add("c23-mame") notes.append("C23 as MAME: no DLI from the DLL entry read on the last DMA line") masked = harness.mask_tia_undriven(board) if args.mask_tia_undriven else None open_bus = harness.mask_open_bus(board) if args.mask_open_bus else None forced = (harness.force_timer(board, harness.mame_timer_reads(args.timer_log)) if args.timer_log else None) # fmt: skip tv = Television(board.maria, keep=1) wanted = {number + d for number in snaps for d in range(-args.offsets, args.offsets + 1)} mine = {} while tv.count < args.frames + args.offsets: before = tv.count if script: apply_board(system, script.pop(tv.count + 1, [])) while tv.count == before: system.step() if tv.count in wanted: mine[tv.count] = tv.frames[-1] if args.ram: ram_mine[tv.count] = bytes(board.ram) mame = {} scale = width = height = 0 for number, path in sorted(snaps.items()): if number > args.skip and number in mine: width, height, rows = read_png(path) scale = width // 320 mame[number] = (path, rows) # One map from colour byte to RGB for the whole run, by majority over every # pixel of every compared frame at offset 0; a pixel differs when its RGB # is not its byte's majority colour (MAME's palette is not the board's). votes: dict[int, Counter] = defaultdict(Counter) for number, (_, rows) in mame.items(): for byte, rgb in pairs(mine[number], rows, scale): votes[byte][rgb] += 1 mapping = {byte: c.most_common(1)[0][0] for byte, c in votes.items()} def bad(number: int, d: int) -> int | None: frame = mine.get(number + d) if frame is None: return None return sum(mapping.get(b) != rgb for b, rgb in pairs(frame, mame[number][1], scale)) compared = differing = ram_compared = ram_equal = 0 first = None offset_wins: Counter = Counter() for number in sorted(mame): counts = {d: bad(number, d) for d in range(-args.offsets, args.offsets + 1)} counts = {d: c for d, c in counts.items() if c is not None} best = min(counts, key=lambda d: (counts[d], abs(d))) offset_wins[best] += 1 compared += 1 print(f"frame {number}: {counts[0]} pixels differ at offset 0; best offset {best:+d} " f"({counts[best]})") # fmt: skip if args.ram and number in mame_ram: state = {d: ram_differs(ram_mine[number + d], mame_ram[number]) for d in range(-args.offsets, args.offsets + 1) if number + d in ram_mine} # fmt: skip d_best = min(state, key=lambda d: (len(state[d]), abs(d))) ram_equal += not state[d_best] ram_compared += 1 print(f" RAM outside the stack page: {len(state[d_best])} bytes differ at offset " f"{d_best:+d}" + (f" (first ${0x1800 + state[d_best][0]:04X})" if state[d_best] else "")) # fmt: skip if counts[0]: differing += 1 (out / f"board-{number}.png").write_bytes(frame_png(mine[number])) if first is None: first = number print(f" first differing frame: MAME's snapshot {mame[number][0]}, " f"board's {out / f'board-{number}.png'}") # fmt: skip if masked is not None: notes.append(f"C17 exclusion: {masked['reads']:,} TIA reads, {masked['differed']:,} " f"changed") # fmt: skip if open_bus is not None: notes.append(f"C18 exclusion: {open_bus['reads']:,} undriven reads, " f"{open_bus['differed']:,} changed") # fmt: skip if forced is not None: firsts = " ".join(f"{b:02X}->{m:02X}" for b, m in forced.get("first", [])) notes.append(f"timer reads forced: {forced['n']}, {forced['differed']} changed " f"(first, board->MAME: {firsts})") # fmt: skip print(f"{cart.name}: {compared} frames compared (every {args.every} after frame {args.skip}), " f"{differing} differ; best offsets {dict(offset_wins)}; MAME snapshot " f"{width}x{height}; {'; '.join(notes) or 'no harness settings'}") # fmt: skip if args.ram: print(f"game state: RAM outside the stack page equal in {ram_equal} of {ram_compared} " f"compared frames (best offset within +-{args.offsets})") # fmt: skip return 0 if differing == 0 and compared else 1 if __name__ == "__main__": sys.exit(main())