#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Drive a locally built Stella libretro core headless via ctypes (a detector, never a judge). A minimal libretro frontend: load a ROM (a plain file, or a member of a No-Intro zip read in place), run N frames, and write per-frame framebuffer SHA-256 lines, optional PNGs, the audio as a WAV, and RIOT RAM peeks. Our code calls the GPL core at run time; nothing of Stella is copied. python scripts/stella_run.py rom.bin --frames 120 --png-every 60 --out out/ python scripts/stella_run.py "Combat (USA).zip" --frames 60 --peek 0x80-0x8f python scripts/stella_run.py rom.bin --frames 300 --press start@100-110 --poke 30:0x81=0x07 python scripts/stella_run.py rom.bin --debugger --frames 120 --tia-type cosmicark --out out/ ``--debugger`` uses the SDL3 frontend instead (reference/build-stella-sdl, see docs/validation.md): it runs Stella's own debugger on a generated script (frame N, tia, riot, ram, saveSnap, exitRom; ``dump`` answers "missing required argument(s)" for every form in this Stella build) with SDL's dummy video and audio drivers, and can select a TIA variant (``dev.tia.type``) and log every instruction with its frame, scanline, cycle and pixel (``--trace``). Output: ``frames.tsv`` (frame, width, height, SHA-256 of the XRGB8888 pixels with the unused top byte masked), with ``--raw`` those pixels themselves as B, G, R bytes in ``frames.bgr`` (frame after frame, sized as ``frames.tsv`` says), ``frame_NNNNN.png`` where asked, ``audio.wav`` (stereo 16-bit at the core's rate) and ``ram.tsv`` (frame, 128 RAM bytes as hex) when ``--peek`` is given; a summary line goes to stdout. Settings that make the output reproducible are forced: palette standard, no TV filter, phosphor off, no cropping, PAL-60/NTSC-50 detection off. Not reachable through the libretro core: Stella's developer-only TIA variants (``dev.tia.type``; it never sets ``dev.settings``) and its RNG seed. Stella's player defaults randomise RAM and A, X, Y, P at power-on from a clock seed, so the first few frames differ between runs (Pitfall!: frames 1-4 of 120; later frames, RAM and audio identical), and the all-frames digest is not reproducible; compare per-frame hashes after start-up. The SDL frontend takes ``-seed``, ``-plr.ramrandom 0`` and ``-plr.cpurandom ""`` for that. """ from __future__ import annotations import argparse import ctypes as C import hashlib import struct import subprocess import sys import wave import zipfile import zlib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # Built by hand as docs/validation.md describes; never committed. LIB = ROOT / "reference/build-stella/stella/src/os/libretro/stella_libretro.so" SDL_STELLA = ROOT / "reference/build-stella-sdl/stella/stella" SDL_LIBS = ROOT / "reference/build-stella-sdl/sdl3" 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 RETRO_MEMORY_SYSTEM_RAM = 2 PIXEL_FORMAT_XRGB8888 = 1 JOYPAD = { "b": 0, "y": 1, "select": 2, "start": 3, "up": 4, "down": 5, "left": 6, "right": 7, "a": 8, "x": 9, "l": 10, "r": 11, "l2": 12, "r2": 13, "l3": 14, "r3": 15, } # libretro button -> 2600 meaning in this core: b = fire, select = SELECT, start = RESET, # l/r = difficulty A, l2/r2 = difficulty B, l3 = colour, r3 = B/W. OPTIONS = { b"stella_console": b"auto", b"stella_palette": b"standard", b"stella_filter": b"disabled", b"stella_crop_hoverscan": b"disabled", b"stella_crop_voverscan": b"0", b"stella_stereo": b"auto", b"stella_phosphor": b"off", b"stella_detect_pal60": b"disabled", b"stella_detect_ntsc50": b"disabled", b"stella_messages": b"disabled", } class RetroVariable(C.Structure): _fields_ = [("key", C.c_char_p), ("value", C.c_char_p)] class RetroGameInfo(C.Structure): _fields_ = [ ("path", C.c_char_p), ("data", C.c_void_p), ("size", C.c_size_t), ("meta", C.c_char_p), ] class RetroGeometry(C.Structure): _fields_ = [ ("base_width", C.c_uint), ("base_height", C.c_uint), ("max_width", C.c_uint), ("max_height", C.c_uint), ("aspect_ratio", C.c_float), ] class RetroTiming(C.Structure): _fields_ = [("fps", C.c_double), ("sample_rate", C.c_double)] class RetroAvInfo(C.Structure): _fields_ = [("geometry", RetroGeometry), ("timing", RetroTiming)] LOG_CB = C.CFUNCTYPE(None, C.c_int, C.c_char_p) # variadic in C; we print the format only class RetroLogCallback(C.Structure): _fields_ = [("log", LOG_CB)] ENV_CB = C.CFUNCTYPE(C.c_bool, C.c_uint, C.c_void_p) VIDEO_CB = C.CFUNCTYPE(None, C.c_void_p, C.c_uint, C.c_uint, C.c_size_t) AUDIO_CB = C.CFUNCTYPE(None, C.c_int16, C.c_int16) AUDIO_BATCH_CB = C.CFUNCTYPE(C.c_size_t, C.POINTER(C.c_int16), C.c_size_t) POLL_CB = C.CFUNCTYPE(None) STATE_CB = C.CFUNCTYPE(C.c_int16, C.c_uint, C.c_uint, C.c_uint, C.c_uint) def png_bytes(width: int, height: int, rgb: bytes) -> bytes: def chunk(kind: bytes, data: bytes) -> bytes: return ( struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) ) rows = b"".join(b"\0" + rgb[y * width * 3 : (y + 1) * width * 3] for y in range(height)) return ( 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, 6)) + chunk(b"IEND", b"") ) def load_rom(path: Path, member: str | None) -> tuple[str, bytes]: if path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as archive: names = [n for n in archive.namelist() if not n.endswith("/")] name = member or names[0] return name, archive.read(name) if path.suffix.lower() == ".7z": # the retrobat set; 7z's output is the one member's bytes listing = subprocess.run( ["7z", "l", "-slt", str(path)], capture_output=True, text=True, check=True ) names = [line[7:] for line in listing.stdout.splitlines() if line.startswith("Path = ")][1:] name = member or names[0] return name, subprocess.run( ["7z", "x", "-so", str(path), name], capture_output=True, check=True ).stdout return path.name, path.read_bytes() def parse_range(text: str) -> tuple[int, int]: low, _, high = text.partition("-") return int(low, 0), int(high or low, 0) def main() -> int: p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) p.add_argument("rom", type=Path, help="ROM file or zip (read in place)") p.add_argument("--member", help="zip member (default: the first)") p.add_argument("--frames", type=int, default=60) p.add_argument("--out", type=Path, help="directory for frames.tsv, PNGs, audio.wav, ram.tsv") p.add_argument("--png-every", type=int, default=0, help="write a PNG every N frames (0: last)") p.add_argument( "--raw", action="store_true", help="also write every frame's pixels to frames.bgr" ) p.add_argument("--peek", help="RAM range to print each frame, e.g. 0x80-0xff") p.add_argument( "--poke", action="append", default=[], help="FRAME:ADDR=VALUE, written into RIOT RAM before that frame runs", ) p.add_argument( "--press", action="append", default=[], help="BUTTON@FIRST-LAST (player 1 joypad), e.g. start@100-110, b@30", ) p.add_argument("--option", action="append", default=[], help="KEY=VALUE core option override") p.add_argument("--lib", type=Path, default=LIB) p.add_argument("--quiet", action="store_true", help="drop core log lines") p.add_argument("--debugger", action="store_true", help="use the SDL frontend's debugger") p.add_argument( "--tia-type", help="with --debugger: standard, koolaidman, cosmicark, pesco, " "quickstep, matchie, indy500, heman, flashmenu, lightsixer, juniorbug", ) p.add_argument("--trace", action="store_true", help="with --debugger: log every instruction") p.add_argument( "--stella-option", action="append", default=[], metavar="KEY=VALUE", help='with --debugger: a Stella command-line option, e.g. seed=1 or plr.cpurandom=""', ) a = p.parse_args() if a.debugger: return run_debugger(a) options = dict(OPTIONS) for item in a.option: key, _, value = item.partition("=") options[key.encode()] = value.encode() presses = [] for item in a.press: button, _, frames = item.partition("@") presses.append((JOYPAD[button.lower()], *parse_range(frames))) pokes: dict[int, list[tuple[int, int]]] = {} for item in a.poke: frame, _, rest = item.partition(":") addr, _, value = rest.partition("=") pokes.setdefault(int(frame, 0), []).append((int(addr, 0), int(value, 0))) peek = parse_range(a.peek) if a.peek else None out = a.out if out: out.mkdir(parents=True, exist_ok=True) home = (out or Path(".")) / "stella-home" home.mkdir(parents=True, exist_ok=True) home_b = str(home.resolve()).encode() + b"/" keep = [] # ctypes objects that must outlive the calls state = {"frame": 0, "video": None, "audio": bytearray()} def log(level, fmt): if not a.quiet: sys.stderr.write(f"[stella {level}] {fmt.decode(errors='replace')}") log_cb = LOG_CB(log) def environment(cmd, data): cmd &= 0xFFFF # drop the EXPERIMENTAL flag; anything not handled answers False if cmd == ENV_SET_PIXEL_FORMAT: return C.cast(data, C.POINTER(C.c_int)).contents.value == PIXEL_FORMAT_XRGB8888 if cmd == ENV_GET_VARIABLE: var = C.cast(data, C.POINTER(RetroVariable)).contents value = options.get(var.key) if value is None: return False buf = C.c_char_p(value) keep.append(buf) var.value = buf.value return True if cmd == ENV_GET_VARIABLE_UPDATE: C.cast(data, C.POINTER(C.c_bool)).contents.value = False return True if cmd in (ENV_GET_SAVE_DIRECTORY, ENV_GET_SYSTEM_DIRECTORY): C.cast(data, C.POINTER(C.c_char_p)).contents.value = home_b return True if cmd == ENV_GET_LOG_INTERFACE: C.cast(data, C.POINTER(RetroLogCallback)).contents.log = log_cb return True return False def video(data, width, height, pitch): if not data: # frame dupe return raw = C.string_at(data, pitch * height) rows = [raw[y * pitch : y * pitch + width * 4] for y in range(height)] state["video"] = (width, height, b"".join(rows)) def audio_batch(data, frames): state["audio"] += C.string_at(data, frames * 4) return frames def input_state(port, device, index, button): if port != 0 or device != 1: return 0 return int(any(b == button and lo <= state["frame"] <= hi for b, lo, hi in presses)) cbs = [ ENV_CB(environment), VIDEO_CB(video), AUDIO_CB(lambda left, right: None), AUDIO_BATCH_CB(audio_batch), POLL_CB(lambda: None), STATE_CB(input_state), ] core = C.CDLL(str(a.lib)) core.retro_set_environment(cbs[0]) core.retro_set_video_refresh(cbs[1]) core.retro_set_audio_sample(cbs[2]) core.retro_set_audio_sample_batch(cbs[3]) core.retro_set_input_poll(cbs[4]) core.retro_set_input_state(cbs[5]) core.retro_init() name, rom = load_rom(a.rom, a.member) rom_buf = C.create_string_buffer(rom, len(rom)) info = RetroGameInfo(name.encode(), C.cast(rom_buf, C.c_void_p), len(rom), None) core.retro_load_game.restype = C.c_bool if not core.retro_load_game(C.byref(info)): raise SystemExit("retro_load_game failed") av = RetroAvInfo() core.retro_get_system_av_info(C.byref(av)) core.retro_get_memory_data.restype = C.c_void_p core.retro_get_memory_size.restype = C.c_size_t ram_ptr = core.retro_get_memory_data(RETRO_MEMORY_SYSTEM_RAM) ram_size = core.retro_get_memory_size(RETRO_MEMORY_SYSTEM_RAM) tsv = (out / "frames.tsv").open("w") if out else None raw = (out / "frames.bgr").open("wb") if out and a.raw else None ram_tsv = (out / "ram.tsv").open("w") if out and peek else None digest = hashlib.sha256() last = None for frame in range(a.frames): state["frame"] = frame for addr, value in pokes.get(frame, []): C.cast(ram_ptr, C.POINTER(C.c_uint8))[(addr - 0x80) & 0x7F] = value state["video"] = None core.retro_run() if state["video"]: width, height, pixels = state["video"] masked = bytearray(len(pixels) // 4 * 3) # B, G, R per pixel; X dropped masked[0::3], masked[1::3], masked[2::3] = pixels[0::4], pixels[1::4], pixels[2::4] masked = bytes(masked) frame_hash = hashlib.sha256(masked).hexdigest() digest.update(masked) last = (frame, width, height, masked, frame_hash) if tsv: tsv.write(f"{frame}\t{width}\t{height}\t{frame_hash}\n") if raw: raw.write(masked) if out and a.png_every and frame % a.png_every == 0: write_png(out / f"frame_{frame:05d}.png", width, height, masked) if peek: ram = C.string_at(ram_ptr, ram_size) row = ram[(peek[0] - 0x80) & 0x7F : ((peek[1] - 0x80) & 0x7F) + 1] line = f"{frame}\t{row.hex()}" if ram_tsv: ram_tsv.write(f"{frame}\t{ram.hex()}\n") if frame == a.frames - 1 or not out: print(f"ram {peek[0]:#04x}-{peek[1]:#04x} after frame {line}") if out and last and not a.png_every: write_png(out / f"frame_{last[0]:05d}.png", last[1], last[2], last[3]) if out: with wave.open(str(out / "audio.wav"), "wb") as wav: wav.setnchannels(2) wav.setsampwidth(2) wav.setframerate(round(av.timing.sample_rate)) wav.writeframes(bytes(state["audio"])) core.retro_unload_game() core.retro_deinit() if tsv: tsv.close() if raw: raw.close() if ram_tsv: ram_tsv.close() size = f"{last[1]}x{last[2]}" if last else "none" print( f"{name}: {a.frames} frames, last frame {size} {last[4] if last else '-'}, " f"all-frames sha256 {digest.hexdigest()}, fps {av.timing.fps:.4f}, " f"audio {len(state['audio']) // 4} samples at {av.timing.sample_rate:.0f} Hz" ) return 0 def run_debugger(a) -> int: import os import subprocess out = (a.out or Path("stella-debugger")).resolve() (out / "home").mkdir(parents=True, exist_ok=True) script = out / "run.script" # The first riot dump shows the power-on timer (random, from -seed). script.write_text(f"riot\nframe {a.frames}\ntia\nriot\nram\nsaveSnap\nexitRom\n") libdirs = [str(d) for d in SDL_LIBS.glob("lib*") if d.is_dir()] env = dict( os.environ, SDL_VIDEODRIVER="dummy", SDL_AUDIODRIVER="dummy", LD_LIBRARY_PATH=":".join([*libdirs, os.environ.get("LD_LIBRARY_PATH", "")]), ) command = [ str(SDL_STELLA), "-basedir", str(out / "home"), "-userdir", str(out), "-snapsavedir", str(out), "-ss1x", "1", "-dbg.logexec", "1", "-plr.timemachine", "0", ] if a.tia_type: command += ["-dev.settings", "1", "-dev.tia.type", a.tia_type] if a.trace: command += ["-dbg.logtrace", "1", "-loglevel", "2", "-logtoconsole", "1"] for option in a.stella_option: key, _, value = option.partition("=") command += [f"-{key}", value] command += ["-debug", "-dbg.script", str(script), str(a.rom.resolve())] with (out / "stella-stdout.txt").open("w") as log: result = subprocess.run( command, env=env, stdout=log, stderr=subprocess.STDOUT, timeout=600, check=False ) report = script.with_name(script.name + ".output.txt") if report.exists(): print(report.read_text(errors="replace")) print(f"exit {result.returncode}; snapshot, dump and log in {out}") return result.returncode def write_png(path: Path, width: int, height: int, bgr: bytes) -> None: rgb = bytearray(len(bgr)) rgb[0::3], rgb[1::3], rgb[2::3] = bgr[2::3], bgr[1::3], bgr[0::3] path.write_bytes(png_bytes(width, height, bytes(rgb))) if __name__ == "__main__": sys.exit(main())