#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a referee libretro core headless and save chosen frames as PNG. A minimal libretro frontend (ctypes) for the cores ``scripts/build_referees.py`` builds (Genesis Plus GX, BlastEm) and sega32x-python's PicoDrive. Start on pad 1 is the only input; no sound kept. Environment calls are answered only as far as a core needs: the system and save directories point at ``--work`` (so no save data is read from or written to ``~/.config``), the pixel format is accepted, core options come from ``--option KEY=VALUE``, and anything else is refused so the core uses its defaults. **BIOS.** Both cores look for ``bios_CD_U.bin``, ``bios_CD_E.bin`` and ``bios_CD_J.bin`` in the system directory. ``--bios FILE`` copies your own BIOS there under all three names; ``--bios-is-verificator`` puts KRIKzz's mcd-verificator there instead (its readme's option 1, "replace CD bios with mcd-verificator"), which needs no Sega code. Nothing is copied into the repository: ``--work`` defaults to ``runs/`` (ignored). python scripts/libretro_run.py gpgx DISC.cue --bios-is-verificator --frames 600,3600 python scripts/libretro_run.py blastem DISC.chd --bios ~/bios/us_scd1.bin --frames 1500 python scripts/libretro_run.py gpgx CART.bin --bios BIOS --option \ "genesis_plus_gx_add_on=sega/mega cd" --frames 1200 # mode 1 (cartridge) """ from __future__ import annotations import argparse import ctypes as C import shutil import struct import sys import zlib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CORES = { "gpgx": ROOT / "reference/build/Genesis-Plus-GX/genesis_plus_gx_libretro.so", "blastem": ROOT / "reference/build/blastem/blastem_libretro.so", # Built by sega32x-python's scripts/build_referees.py (a sibling clone): the one # referee that runs a CD and a 32X together. "picodrive": ROOT.parent / "sega32x-python/reference/build/picodrive/picodrive_libretro.so", } DEVICE_JOYPAD, JOYPAD_START = 1, 3 VERIFICATOR = ROOT / "reference/src/mcd-verificator/mcd-verificator/mcd-verificator.bin" ENV_GET_CAN_DUPE = 3 ENV_GET_SYSTEM_DIRECTORY = 9 ENV_SET_PIXEL_FORMAT = 10 ENV_GET_VARIABLE = 15 ENV_GET_VARIABLE_UPDATE = 17 ENV_GET_LOG_INTERFACE = 27 ENV_GET_SAVE_DIRECTORY = 31 PIXEL_0RGB1555, PIXEL_XRGB8888, PIXEL_RGB565 = 0, 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)) # fmt: skip class Variable(C.Structure): _fields_ = (("key", C.c_char_p), ("value", C.c_char_p)) class AVInfo(C.Structure): _fields_ = (("base_width", C.c_uint), ("base_height", C.c_uint), ("max_width", C.c_uint), ("max_height", C.c_uint), ("aspect", C.c_float), ("fps", C.c_double), ("sample_rate", C.c_double)) # fmt: skip def write_wav(path: Path, rate: int, stereo: bytes) -> None: """16-bit stereo PCM.""" header = struct.pack("<4sI4s4sIHHIIHH4sI", b"RIFF", 36 + len(stereo), b"WAVE", b"fmt ", 16, 1, 2, rate, rate * 4, 4, 16, b"data", len(stereo)) # fmt: skip path.write_bytes(header + stereo) ENVIRONMENT = C.CFUNCTYPE(C.c_bool, C.c_uint, C.c_void_p) VIDEO = C.CFUNCTYPE(None, C.c_void_p, C.c_uint, C.c_uint, C.c_size_t) AUDIO = C.CFUNCTYPE(None, C.c_int16, C.c_int16) AUDIO_BATCH = C.CFUNCTYPE(C.c_size_t, C.c_void_p, C.c_size_t) INPUT_POLL = C.CFUNCTYPE(None) INPUT_STATE = C.CFUNCTYPE(C.c_int16, C.c_uint, C.c_uint, C.c_uint, C.c_uint) #: retro_log_printf_t is variadic; only the format string is shown (enough to see why a #: core refuses content). LOG = C.CFUNCTYPE(None, C.c_int, 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) & 0xFFFFFFFF) ) stride = width * 3 raw = b"".join(b"\0" + rgb[y * stride : (y + 1) * stride] 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(raw, 6)) + chunk(b"IEND", b"") ) def to_rgb(frame: bytes, width: int, height: int, pitch: int, fmt: int) -> bytes: out = bytearray(width * height * 3) o = 0 for y in range(height): row = frame[y * pitch : y * pitch + pitch] if fmt == PIXEL_XRGB8888: for x in range(width): b, g, r = row[4 * x], row[4 * x + 1], row[4 * x + 2] out[o : o + 3] = bytes((r, g, b)) o += 3 else: for x in range(width): v = row[2 * x] | (row[2 * x + 1] << 8) if fmt == PIXEL_RGB565: r, g, b = (v >> 11) & 31, (v >> 5) & 63, v & 31 out[o : o + 3] = bytes((r * 255 // 31, g * 255 // 63, b * 255 // 31)) else: r, g, b = (v >> 10) & 31, (v >> 5) & 31, v & 31 out[o : o + 3] = bytes((r * 255 // 31, g * 255 // 31, b * 255 // 31)) o += 3 return bytes(out) def run(core_path: Path, content: Path, work: Path, frames: list[int], options: dict[str, str], press_at: list[int] = (), press_for: int = 10, wav: Path | None = None, on_frame=None) -> list[Path]: # fmt: skip """``on_frame(n, width, height, rgb)``: given each wanted frame instead of a PNG being written (scripts/referee.py).""" core = C.CDLL(str(core_path)) system = str(work / "system").encode() save = str(work / "save").encode() keep: list[object] = [] # buffers the core may hold pointers to state = {"fmt": PIXEL_0RGB1555, "frame": None, "n": 0} def input_state(port: int, device: int, index: int, ident: int) -> int: """Start on pad 1 for ``press_for`` frames from each of ``press_at``.""" if port or device != DEVICE_JOYPAD or ident != JOYPAD_START: return 0 return int(any(0 <= state["n"] - at < press_for for at in press_at)) def environment(cmd: int, data: int) -> bool: cmd &= 0xFFFF if cmd in (ENV_GET_SYSTEM_DIRECTORY, ENV_GET_SAVE_DIRECTORY): # A buffer that outlives the call: the core keeps the pointer. value = C.create_string_buffer(system if cmd == ENV_GET_SYSTEM_DIRECTORY else save) keep.append(value) C.cast(data, C.POINTER(C.c_void_p))[0] = C.addressof(value) return True if cmd == ENV_SET_PIXEL_FORMAT: state["fmt"] = C.cast(data, C.POINTER(C.c_int))[0] return state["fmt"] in (PIXEL_0RGB1555, PIXEL_XRGB8888, PIXEL_RGB565) if cmd == ENV_GET_LOG_INTERFACE: C.cast(data, C.POINTER(C.c_void_p))[0] = C.cast(log_callback, C.c_void_p) return True if cmd == ENV_GET_CAN_DUPE: C.cast(data, C.POINTER(C.c_bool))[0] = True return True if cmd == ENV_GET_VARIABLE: var = C.cast(data, C.POINTER(Variable))[0] key = var.key.decode() if var.key else "" if key in options: value = C.create_string_buffer(options[key].encode()) keep.append(value) C.cast(data, C.POINTER(C.c_void_p))[1] = C.addressof(value) return True return False if cmd == ENV_GET_VARIABLE_UPDATE: C.cast(data, C.POINTER(C.c_bool))[0] = False return True return False log_callback = LOG( lambda level, text: ( print(f"core: {text.decode(errors='replace').rstrip()}", file=sys.stderr) if level >= 1 else None ) ) def video(data: int, width: int, height: int, pitch: int) -> None: if data: state["frame"] = (C.string_at(data, pitch * height), width, height, pitch) sound: list[bytes] = [] def audio_batch(data: int, n: int) -> int: if wav is not None and data: sound.append(C.string_at(data, n * 4)) return n def audio_sample(left: int, right: int) -> None: if wav is not None: sound.append(struct.pack(" int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("core", choices=sorted(CORES)) parser.add_argument("content", type=Path, help="a disc (.cue/.chd) or a cartridge") parser.add_argument("--frames", required=True, help="comma-separated frame numbers; A-B:STEP for a run of them") # fmt: skip parser.add_argument("--press-at", default="", help="frames to press Start at (pad 1)") parser.add_argument("--wav", type=Path, help="keep the core's sound, from frame 1") parser.add_argument("--press-for", type=int, default=10, help="frames a press lasts") parser.add_argument("--work", type=Path, default=None, help="default runs/") bios = parser.add_mutually_exclusive_group() bios.add_argument("--bios", type=Path, help="your own Sega CD BIOS (never committed)") bios.add_argument("--bios-is-verificator", action="store_true", help="put mcd-verificator in the BIOS's place") # fmt: skip parser.add_argument("--option", action="append", default=[], help="core option KEY=VALUE") args = parser.parse_args() work = (args.work or ROOT / "runs" / args.core).resolve() for sub in ("system", "save"): (work / sub).mkdir(parents=True, exist_ok=True) source = VERIFICATOR if args.bios_is_verificator else args.bios if source is not None: for name in ("bios_CD_U.bin", "bios_CD_E.bin", "bios_CD_J.bin"): shutil.copyfile(source, work / "system" / name) options = dict(option.split("=", 1) for option in args.option) frames: set[int] = set() for part in args.frames.split(","): span, _, step = part.partition(":") first, _, last = span.partition("-") frames.update(range(int(first), int(last or first) + 1, int(step or 1))) press_at = [int(n) for n in args.press_at.split(",") if n] written = run(CORES[args.core], args.content.resolve(), work, sorted(frames), options, press_at, args.press_for, args.wav) # fmt: skip print(f"{len(written)} frames in {work / 'frames'}") return 0 if __name__ == "__main__": sys.exit(main())