#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Drive a locally built ProSystem libretro core headless: frame digests, a PNG, RAM. ProSystem (GPL-2.0, Greg Stanton's emulator as maintained by libretro) is the detector that does **not** descend from MAME's a7800 driver. It is run as an external shared library through ``ctypes``; none of its logic is in this file. The core is a program at ``reference/build-prosystem/prosystem_libretro.so``: the one built here before 2026-11-24 (sha1 e0cebbf6), or a shipped libretro build. Its source (https://github.com/libretro/prosystem-libretro @ 8a88014287c7a01cd568067e5a557d0a2b2a051f) is not fetched (Aubrey, 2026-11-24; docs/validation.md "Detectors"). The cartridge is handed over **in memory** (``need_fullpath`` is false), so a No-Intro zip or a 7z member is read in place and nothing is written. The core runs without a BIOS (it starts the cartridge directly), and types a headerless dump from its own MD5 database, falling back to a size rule: its answer for the cart type is therefore an emulator's, not a fact (docs/cartridge.md). python scripts/prosystem_run.py ".../Atari - Atari 7800 (BIN)/Asteroids (USA).zip" --frames 300 python scripts/prosystem_run.py cart.zip --frames 600 --png tests/detector_runs/out.png Prints one line per ``--every`` frames: frame number, width x height, SHA-1 of the frame's pixels as XRGB8888 (converted when the core gives RGB565); then a digest of the console RAM at the end. """ from __future__ import annotations import argparse import ctypes import hashlib import struct import subprocess import sys import zipfile import zlib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CORE = ROOT / "reference" / "build-prosystem" / "prosystem_libretro.so" ENV_GET_SYSTEM_DIRECTORY = 9 ENV_SET_PIXEL_FORMAT = 10 ENV_GET_VARIABLE = 15 ENV_GET_VARIABLE_UPDATE = 17 PIXEL_XRGB8888 = 1 PIXEL_RGB565 = 2 MEMORY_SYSTEM_RAM = 2 DEVICE_JOYPAD = 1 # libretro's RetroPad ids for the stick are the API's own (UP 4, DOWN 5, LEFT 6, # RIGHT 7); which ids the core reads as the 7800's buttons and console switches # was found from its behaviour (session 8, docs/build-progress.md), not its source. # Joust's title, an id held at frames 300-310: 9 starts a game as Reset does, # 2 gives "TWO PLAYER EXPERT" as Select does, 0 and 8 start it as a button does # (a one-button title: which is the left button is not told apart), 1 and # 10-15 do nothing; 3 does nothing on the title (taken as Pause, unconfirmed). JOYPAD = {"up": 4, "down": 5, "left": 6, "right": 7, "b1": 0, "b2": 8, "reset": 9, "select": 2, "pause": 3} # fmt: skip SWITCHES = ("reset", "select", "pause") class GameInfo(ctypes.Structure): _fields_ = [("path", ctypes.c_char_p), ("data", ctypes.c_void_p), ("size", ctypes.c_size_t), ("meta", ctypes.c_char_p)] # fmt: skip ENVIRONMENT = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_uint, ctypes.c_void_p) VIDEO = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_size_t) AUDIO = ctypes.CFUNCTYPE(None, ctypes.c_int16, ctypes.c_int16) AUDIO_BATCH = ctypes.CFUNCTYPE(ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t) POLL = ctypes.CFUNCTYPE(None) STATE = ctypes.CFUNCTYPE(ctypes.c_int16, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint) def read_image(path: Path) -> bytes: """The one cartridge image in a zip or 7z, or the file itself; never extracted to disk.""" suffix = path.suffix.lower() if suffix == ".zip": with zipfile.ZipFile(path) as z: members = [i for i in z.infolist() if not i.is_dir()] if len(members) != 1: raise SystemExit(f"{path}: expected one member, found {len(members)}") return z.read(members[0]) if suffix == ".7z": return subprocess.run(["7z", "x", "-so", str(path)], capture_output=True, check=True).stdout return path.read_bytes() def png(width: int, height: int, xrgb: bytes) -> bytes: rows = b"" for y in range(height): row = xrgb[y * width * 4 : (y + 1) * width * 4] rows += b"\0" + b"".join(row[i + 2 : i + 3] + row[i + 1 : i + 2] + row[i : i + 1] for i in range(0, len(row), 4)) # fmt: skip def chunk(kind: bytes, data: bytes) -> bytes: return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) # fmt: skip 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=300) parser.add_argument("--every", type=int, default=60) parser.add_argument("--png", type=Path, help="write the last frame here") parser.add_argument("--core", type=Path, default=CORE) parser.add_argument("--raw", type=Path, help="append every printed frame's pixels here " "(frames_prosystem.py reads it)") # fmt: skip parser.add_argument("--dump", help="print RAM bytes START:LENGTH (hex offsets into the core's RAM)") parser.add_argument("--ram-log", type=Path, help="append the core's whole system RAM after every " "frame here (frame number as 4 bytes, then the RAM): per-frame state comparison") # fmt: skip parser.add_argument("--script", nargs="*", default=[], metavar="FRAME:ACTION", help="scripted input as frames_mame.py takes it (stick, b1/b2/b12, reset, " "select, pause, switches-off, none), or idN for libretro joypad id N") # fmt: skip parser.add_argument("--png-dir", type=Path, help="write every printed frame as N.png here") args = parser.parse_args() if not args.core.exists(): raise SystemExit(f"{args.core} is not built; see this script's docstring") image = read_image(args.cart) core = ctypes.CDLL(str(args.core)) last = {} @ENVIRONMENT def environment(command: int, data: int) -> bool: if command == ENV_SET_PIXEL_FORMAT: last["format"] = ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[0] return last["format"] in (PIXEL_XRGB8888, PIXEL_RGB565) if command == ENV_GET_VARIABLE_UPDATE: ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = False return True return False # no system directory (so no BIOS), no core options: the core's defaults @VIDEO def video(data: int, width: int, height: int, pitch: int) -> None: if data: raw = ctypes.string_at(data, pitch * height) if last.get("format") == PIXEL_RGB565: rows = [] for y in range(height): for (v,) in struct.iter_unpack("> 11, v >> 5 & 0x3F, v & 0x1F rows.append(bytes((b << 3 | b >> 2, g << 2 | g >> 4, r << 3 | r >> 2, 0))) last["frame"] = (width, height, b"".join(rows)) else: last["frame"] = (width, height, b"".join(raw[y * pitch : y * pitch + width * 4] for y in range(height))) # fmt: skip @AUDIO def audio(left: int, right: int) -> None: pass @AUDIO_BATCH def audio_batch(data: int, frames: int) -> int: return frames @POLL def poll() -> None: pass held: set[int] = set() script: dict[int, list[str]] = {} for item in args.script: frame_text, action = item.split(":", 1) if action not in JOYPAD and action not in ("none", "switches-off") and not action.startswith("id"): raise SystemExit(f"unknown action {action!r}") script.setdefault(int(frame_text), []).append(action) @STATE def state(port: int, device: int, index: int, ident: int) -> int: return int(port == 0 and device == DEVICE_JOYPAD and ident in held) core.retro_set_environment(environment) core.retro_init() core.retro_set_video_refresh(video) core.retro_set_audio_sample(audio) core.retro_set_audio_sample_batch(audio_batch) core.retro_set_input_poll(poll) core.retro_set_input_state(state) buffer = ctypes.create_string_buffer(image, len(image)) info = GameInfo(str(args.cart).encode(), ctypes.cast(buffer, ctypes.c_void_p), len(image), None) core.retro_load_game.argtypes = [ctypes.POINTER(GameInfo)] core.retro_load_game.restype = ctypes.c_bool if not core.retro_load_game(ctypes.byref(info)): raise SystemExit("the core refused the image") payload = image[128:] if image[1:10] == b"ATARI7800" else image print(f"{args.cart.name}: {len(payload)} payload bytes, md5 {hashlib.md5(payload).hexdigest()}, " f"header {'yes' if len(payload) != len(image) else 'no'}") # fmt: skip raw_out = args.raw.open("wb") if args.raw else None core.retro_get_memory_size.restype = ctypes.c_size_t core.retro_get_memory_data.restype = ctypes.c_void_p ram_out = args.ram_log.open("wb") if args.ram_log else None for frame in range(1, args.frames + 1): for action in script.get(frame, []): # as frames_mame.py: a stick or button item releases the other stick and # button inputs; a switch item adds the switch; switches-off releases them if action == "switches-off": held.difference_update(JOYPAD[s] for s in SWITCHES) elif action.startswith("id"): held.add(int(action[2:])) elif action in SWITCHES: held.add(JOYPAD[action]) else: held.difference_update(JOYPAD[s] for s in JOYPAD if s not in SWITCHES) held.update(JOYPAD[a] for a in {"b12": ("b1", "b2")}.get(action, (action,)) if a in JOYPAD) # fmt: skip core.retro_run() if ram_out is not None: size = core.retro_get_memory_size(MEMORY_SYSTEM_RAM) ram_out.write(struct.pack("