#!/usr/bin/env python3 """Run a ColecoVision cartridge on a libretro core headless and save its last frame. A ctypes host for the libretro ABI, with no window and no audio device. The core is Gearcoleco, run as a program: the core built here before 2026-11-24 at ``reference/build-gearcoleco/gearcoleco_libretro.so``, or a shipped libretro build. Its source is not fetched (Aubrey, 2026-11-24; docs/validation.md). python -I scripts/libretro_run.py CORE.so CART.col --system BIOSDIR --frames 600 --png out.png ``--system`` is the directory the core reads its BIOS from; Gearcoleco wants ``colecovision.rom`` there (bring your own: SHA-1 45bedc4c...). The frame is converted from the pixel format the core negotiates (RGB565 or XRGB8888) and written as a PNG with the standard library alone. ``--hash`` prints the SHA-256 of the last frame's RGB bytes, for comparing runs. """ from __future__ import annotations import argparse import ctypes as C import hashlib import struct import sys import zipfile import zlib from pathlib import Path SET_PIXEL_FORMAT = 10 GET_SYSTEM_DIRECTORY = 9 GET_SAVE_DIRECTORY = 31 GET_VARIABLE = 15 FORMAT_XRGB8888, FORMAT_RGB565 = 1, 2 class GameInfo(C.Structure): _fields_ = [("path", C.c_char_p), ("data", C.c_void_p), ("size", C.c_size_t), ("meta", C.c_char_p)] class Variable(C.Structure): _fields_ = [("key", C.c_char_p), ("value", C.c_char_p)] def write_png(path: Path, width: int, height: int, rgb: bytes) -> None: def chunk(kind: bytes, body: bytes) -> bytes: return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body)) rows = b"".join(b"\0" + rgb[y * width * 3 : (y + 1) * width * 3] for y in range(height)) path.write_bytes( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"") ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("core", type=Path) parser.add_argument("content", type=Path) parser.add_argument("--frames", type=int, default=300) parser.add_argument("--system", type=Path, default=Path(".")) parser.add_argument("--png", type=Path) parser.add_argument("--hash", action="store_true") parser.add_argument("--input", action="append", default=[], help="START:END:p1.CONTROL (repeatable)") parser.add_argument("--snap", help="comma-separated frame numbers (0-based) to save") parser.add_argument("--snap-dir", type=Path, default=Path(".")) args = parser.parse_args() lib = C.CDLL(str(args.core.resolve())) system = C.c_char_p(str(args.system.resolve()).encode()) state = {"format": 0, "frame": None, "pressed": set()} @C.CFUNCTYPE(C.c_bool, C.c_uint, C.c_void_p) def environment(command: int, data: int) -> bool: command &= 0xFFFF if command == SET_PIXEL_FORMAT: state["format"] = C.cast(data, C.POINTER(C.c_int))[0] return True if command in (GET_SYSTEM_DIRECTORY, GET_SAVE_DIRECTORY): C.cast(data, C.POINTER(C.c_char_p))[0] = system return True if command == GET_VARIABLE: C.cast(data, C.POINTER(Variable))[0].value = None return False return False @C.CFUNCTYPE(None, C.c_void_p, C.c_uint, C.c_uint, C.c_size_t) def video(data: int, width: int, height: int, pitch: int) -> None: if data: state["frame"] = (C.string_at(data, pitch * height), width, height, pitch) @C.CFUNCTYPE(None, C.c_int16, C.c_int16) def audio_sample(left: int, right: int) -> None: return None @C.CFUNCTYPE(C.c_size_t, C.c_void_p, C.c_size_t) def audio_batch(data: int, frames: int) -> int: return frames @C.CFUNCTYPE(None) def input_poll() -> None: return None @C.CFUNCTYPE(C.c_int16, C.c_uint, C.c_uint, C.c_uint, C.c_uint) def input_state(port: int, device: int, index: int, ident: int) -> int: pressed = state["pressed"] if ident == 256: # RETRO_DEVICE_ID_JOYPAD_MASK return sum(1 << i for p, i in pressed if p == port) return 1 if (port, ident) in pressed else 0 lib.retro_set_environment(environment) lib.retro_init() lib.retro_set_video_refresh(video) lib.retro_set_audio_sample(audio_sample) lib.retro_set_audio_sample_batch(audio_batch) lib.retro_set_input_poll(input_poll) lib.retro_set_input_state(input_state) if args.content.suffix.lower() == ".zip": # read the image in place, from memory with zipfile.ZipFile(args.content) as archive: image = archive.read(archive.namelist()[0]) else: image = args.content.read_bytes() buffer = C.create_string_buffer(image, len(image)) info = GameInfo(str(args.content.resolve()).encode(), C.cast(buffer, C.c_void_p), len(image), None) lib.retro_load_game.restype = C.c_bool if not lib.retro_load_game(C.byref(info)): print("the core refused the content (is the BIOS in --system?)") return 1 schedule = [parse_input(text) for text in args.input] snaps = {int(f) for f in args.snap.split(",")} if args.snap else set() if snaps: args.snap_dir.mkdir(parents=True, exist_ok=True) for k in range(args.frames): state["pressed"] = {(port, ident) for start, end, port, ident in schedule if start <= k < end} lib.retro_run() if k in snaps and state["frame"] is not None: width, height, rgb = frame_rgb(state) write_png(args.snap_dir / f"frame-{k:05d}.png", width, height, rgb) if state["frame"] is None: print("no frame was delivered") return 1 width, height, rgb = frame_rgb(state) colours = len({bytes(rgb[i : i + 3]) for i in range(0, len(rgb), 3)}) print(f"{args.frames} frames, last frame {width}x{height}, {colours} colours") if args.hash: print(hashlib.sha256(rgb).hexdigest()) if args.png: write_png(args.png, width, height, bytes(rgb)) lib.retro_unload_game() lib.retro_deinit() return 0 #: Gearcoleco's libretro joypad map (platforms/libretro/libretro.cpp, its input #: descriptors): control name -> RETRO_DEVICE_ID_JOYPAD_* number. JOYPAD = { "up": 4, "down": 5, "left": 6, "right": 7, "fire_left": 0, "fire_right": 8, "1": 1, "2": 9, "3": 10, "4": 11, "5": 12, "6": 13, "7": 14, "8": 15, "*": 3, "#": 2, } # fmt: skip def parse_input(text: str) -> tuple[int, int, int, int]: """``START:END:pN.CONTROL``: held during frames START..END-1 (port N = 1 or 2).""" start, end, control = text.split(":", 2) port, name = control.split(".", 1) return int(start), int(end), int(port[1:]) - 1, JOYPAD[name] def frame_rgb(state: dict) -> tuple[int, int, bytes]: raw, width, height, pitch = state["frame"] rgb = bytearray() for y in range(height): row = raw[y * pitch : y * pitch + width * (2 if state["format"] == FORMAT_RGB565 else 4)] if state["format"] == FORMAT_RGB565: for (value,) in struct.iter_unpack("> 11) * 255 // 31, (value >> 5 & 63) * 255 // 63, (value & 31) * 255 // 31) ) else: for blue, green, red, _ in struct.iter_unpack("4B", row): rgb += bytes((red, green, blue)) return width, height, bytes(rgb) if __name__ == "__main__": sys.exit(main())