#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a cartridge on a libretro core (PicoDrive, BlastEm) and save chosen frames as PNG. A minimal libretro frontend (ctypes), the same idea as megadrive-python's ``scripts/blastem_frames.py`` but written for this repository: pad 1 only, held as ``--press`` says (``FRAME:BUTTONS[:HOLD]``, Mega Drive button names), the system and save directories pointed at ``--work``, the pixel format the core asks for accepted, every other environment call refused so the core uses its defaults. Referees are **detectors** here (docs/validation.md). The system directory is where a core looks for boot ROMs. It starts empty, so PicoDrive starts 32X programs by itself (OBSERVED: it runs with no boot ROMs; how it does so is not read here, PicoDrive being a closed box); ``--bios-dir`` copies the user's own boot ROMs in, under the names the core expects. Nothing is fetched. python scripts/libretro_frames.py reference/build/picodrive/picodrive_libretro.so \\ reference/build/testpico/hardware/testpico-30a5783.bin out/ --frames 600,1800 ``--on-change X0,Y0,X1,Y1`` saves, up to the last ``--frames`` frame, every frame on which that rectangle of the picture changes and the frame before it: for a program that shows one test at a time with a counter (Sega's Mars Check Program), the frame before the counter moves is the finished test, with its verdict. ``--reset-at`` calls the core's ``retro_reset`` (its reset button) before the frames named. ``--press-from-picture N:BUTTONS[:HOLD]`` counts N from the first frame that is not one colour, so emulators whose boots take different times get the press at the same point of the program. ``--wav`` keeps the core's sound (16-bit stereo, at the rate ``retro_get_system_av_info`` reports) for milestone 5's PWM comparison; ``--wav-from`` starts it at a frame. """ from __future__ import annotations import argparse import ctypes as C import shutil import struct import sys import tempfile import zlib from pathlib import Path ENV_GET_SYSTEM_DIRECTORY = 9 ENV_SET_PIXEL_FORMAT = 10 ENV_GET_SAVE_DIRECTORY = 31 FORMATS = {0: "0RGB1555", 1: "XRGB8888", 2: "RGB565"} class Timing(C.Structure): _fields_ = [("fps", C.c_double), ("sample_rate", C.c_double)] class Geometry(C.Structure): _fields_ = [(name, C.c_uint) for name in ("base_w", "base_h", "max_w", "max_h")] + [ ("aspect", C.c_float) ] class AVInfo(C.Structure): _fields_ = [("geometry", Geometry), ("timing", Timing)] 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), ] def write_png(path: Path, width: int, height: int, rgb: bytes) -> None: raw = b"".join(b"\0" + rgb[y * width * 3 : (y + 1) * width * 3] for y in range(height)) def chunk(kind: bytes, body: bytes) -> bytes: return ( struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body)) ) 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(raw, 6)) + chunk(b"IEND", b"") ) def write_wav(path: Path, samples: list[tuple[int, int]], rate: int) -> None: """16-bit stereo PCM.""" payload = b"".join(struct.pack(" bytes: out = bytearray() for y in range(height): row = data[y * pitch : y * pitch + width * (4 if fmt == "XRGB8888" else 2)] if fmt == "XRGB8888": for x in range(width): b, g, r, _ = row[4 * x : 4 * x + 4] out += bytes((r, g, b)) else: for x in range(width): v = row[2 * x] | row[2 * x + 1] << 8 if fmt == "RGB565": r, g, b = v >> 11, (v >> 5) & 63, v & 31 out += bytes((r * 255 // 31, g * 255 // 63, b * 255 // 31)) else: r, g, b = (v >> 10) & 31, (v >> 5) & 31, v & 31 out += bytes((r * 255 // 31, g * 255 // 31, b * 255 // 31)) return bytes(out) RETRO_DEVICE_JOYPAD = 1 #: libretro joypad ids for the Mega Drive buttons, per core: each core maps its own, and #: names them in the input descriptors it hands the frontend when a game loads #: (RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS). OBSERVED 2026-11-23 from the running #: builds, PicoDrive (reference/build) and BlastEm (libretro 542164d): PicoDrive A = 1, #: B = 0, C = 8; BlastEm A = 0, B = 8, C = 11. Directions and Start are libretro's. _COMMON = {"up": 4, "down": 5, "left": 6, "right": 7, "start": 3} CORE_BUTTONS = { "picodrive": {**_COMMON, "a": 1, "b": 0, "c": 8}, "blastem": {**_COMMON, "a": 0, "b": 8, "c": 11}, } def core_buttons(core: Path) -> dict[str, int]: for name, mapping in CORE_BUTTONS.items(): if name in core.name.lower(): return mapping return CORE_BUTTONS["picodrive"] def parse_presses(specs: list[str]) -> list[tuple[int, int, tuple[str, ...]]]: """``FRAME:BUTTONS[:HOLD]`` -> (first frame, last frame, buttons).""" presses = [] for spec in specs: parts = spec.split(":") first = int(parts[0]) hold = int(parts[2]) if len(parts) > 2 else 4 buttons = tuple(b.strip().lower() for b in parts[1].split(",") if b.strip()) presses.append((first, first + hold - 1, buttons)) return presses def one_colour(last: tuple, fmt: str) -> bool: """Whether every visible pixel of a frame (data, width, height, pitch) is the same.""" data, width, height, pitch = last size = 4 if fmt == "XRGB8888" else 2 first = data[:size] row = first * width return all(data[y * pitch : y * pitch + width * size] == row for y in range(height)) def held(presses: list[tuple[int, int, tuple[str, ...]]], frame: int) -> set[str]: return {b for first, last, buttons in presses if first <= frame <= last for b in buttons} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("core", type=Path) parser.add_argument("rom", type=Path) parser.add_argument("out", type=Path) parser.add_argument("--frames", required=True, help="comma-separated frame numbers (from 1)") parser.add_argument( "--work", type=Path, help="system/save directory (default: a temporary one)" ) parser.add_argument("--bios-dir", type=Path, help="copy the user's own boot ROMs from here") parser.add_argument("--on-change", help="X0,Y0,X1,Y1: save frames where this region changes") parser.add_argument("--reset-at", default="", help="frames to call retro_reset() before") parser.add_argument( "--press", action="append", default=[], help="FRAME:BUTTONS[:HOLD] -- hold Mega Drive buttons (a,b,c,start,up,down,left,right) " "on pad 1 from FRAME for HOLD frames (default 4); repeatable", ) parser.add_argument( "--press-from-picture", action="append", default=[], help="N:BUTTONS[:HOLD] -- as --press, N frames after the first picture that is not " "one colour (the boot's length differs most between emulators)", ) parser.add_argument("--wav", type=Path, help="write the core's sound here") parser.add_argument("--wav-from", type=int, default=1, help="first frame of --wav") args = parser.parse_args() presses = parse_presses(args.press) from_picture = parse_presses(args.press_from_picture) button_ids = core_buttons(args.core) region = tuple(int(n) for n in args.on_change.split(",")) if args.on_change else None wanted = sorted(int(n) for n in args.frames.split(",")) args.out.mkdir(parents=True, exist_ok=True) work = args.work or Path(tempfile.mkdtemp(prefix="libretro-")) work.mkdir(parents=True, exist_ok=True) if args.bios_dir: for item in args.bios_dir.iterdir(): shutil.copy2(item, work / item.name) work_c = C.c_char_p(str(work).encode()) state = {"fmt": "0RGB1555", "frame": 0, "last": None} audio: list[tuple[int, int]] = [] env_t = C.CFUNCTYPE(C.c_bool, C.c_uint, C.c_void_p) video_t = C.CFUNCTYPE(None, C.c_void_p, C.c_uint, C.c_uint, C.c_size_t) sample_t = C.CFUNCTYPE(None, C.c_int16, C.c_int16) batch_t = C.CFUNCTYPE(C.c_size_t, C.c_void_p, C.c_size_t) poll_t = C.CFUNCTYPE(None) input_t = C.CFUNCTYPE(C.c_int16, C.c_uint, C.c_uint, C.c_uint, C.c_uint) def environment(cmd: int, data: int) -> bool: cmd &= 0xFFFF if cmd in (ENV_GET_SYSTEM_DIRECTORY, ENV_GET_SAVE_DIRECTORY): C.cast(data, C.POINTER(C.c_char_p))[0] = work_c.value return True if cmd == ENV_SET_PIXEL_FORMAT: state["fmt"] = FORMATS[C.cast(data, C.POINTER(C.c_int))[0]] return True return False def keep(left: int, right: int) -> None: if args.wav and state["frame"] >= args.wav_from: audio.append((left, right)) def batch(data: int, frames: int) -> int: if args.wav and state["frame"] >= args.wav_from: pcm = C.cast(data, C.POINTER(C.c_int16)) audio.extend((pcm[2 * i], pcm[2 * i + 1]) for i in range(frames)) return frames def video(data: int, width: int, height: int, pitch: int) -> None: if data: state["last"] = (C.string_at(data, pitch * height), width, height, pitch) callbacks = ( env_t(environment), video_t(video), sample_t(keep), batch_t(batch), poll_t(lambda: None), input_t( lambda port, device, index, ident: int( port == 0 and device == RETRO_DEVICE_JOYPAD and ident in state["held"] ) ), ) state["held"] = set() core = C.CDLL(str(args.core)) core.retro_set_environment(callbacks[0]) core.retro_set_video_refresh(callbacks[1]) core.retro_set_audio_sample(callbacks[2]) core.retro_set_audio_sample_batch(callbacks[3]) core.retro_set_input_poll(callbacks[4]) core.retro_set_input_state(callbacks[5]) core.retro_init() rom = args.rom.read_bytes() buffer = C.create_string_buffer(rom, len(rom)) info = GameInfo(str(args.rom).encode(), C.cast(buffer, C.c_void_p), len(rom), None) core.retro_load_game.restype = C.c_bool if not core.retro_load_game(C.byref(info)): print("the core refused the cartridge", file=sys.stderr) return 1 def save(frame: int, last: tuple) -> None: data, width, height, pitch = last rgb = to_rgb(state["fmt"], data, width, height, pitch) write_png(args.out / f"f{frame:05d}.png", width, height, rgb) print(f"frame {frame}: {width}x{height} {state['fmt']}") def crop(last: tuple) -> bytes: data, _width, _height, pitch = last x0, y0, x1, y1 = region # type: ignore[misc] size = 4 if state["fmt"] == "XRGB8888" else 2 return b"".join(data[y * pitch + x0 * size : y * pitch + x1 * size] for y in range(y0, y1)) previous: tuple | None = None resets = {int(n) for n in args.reset_at.split(",") if n} for frame in range(1, wanted[-1] + 1): if frame in resets: core.retro_reset() print(f"frame {frame}: retro_reset") state["held"] = {button_ids[name] for name in held(presses, frame)} state["frame"] = frame core.retro_run() last = state["last"] if not last: continue if from_picture and not one_colour(last, state["fmt"]): presses += [(frame + a, frame + b, buttons) for a, b, buttons in from_picture] print(f"frame {frame}: first picture; presses from it") from_picture = [] if region is not None: if previous is not None and crop(previous) != crop(last): save(frame - 1, previous) save(frame, last) previous = last if frame in wanted: save(frame, last) if args.wav: av = AVInfo() core.retro_get_system_av_info(C.byref(av)) rate = round(av.timing.sample_rate) write_wav(args.wav, audio, rate) print(f"{len(audio):,} samples at {rate} Hz to {args.wav}") core.retro_unload_game() core.retro_deinit() return 0 if __name__ == "__main__": sys.exit(main())