# SPDX-License-Identifier: GPL-3.0-or-later """The SNES adapter: Mesen2's SnesConfig and a run that ends on a script's marker. From snes-python's ``scripts/mesen_run.py`` (MIT, alewman, first published in snes-python; ``notices/MIT-emulator-family.txt``), parked 2026-11-22 and regrouped here 2026-11-23 without changing what it does. Mesen2 frames are 256x239 (512x478 in hi-res and interlace), overscan included: row 7 is MAME's row 0 (OBSERVED by snes-python, 2026-10-21). Mesen2 carries its own S-SMP IPL ROM, so no BIOS is needed. """ from __future__ import annotations import ctypes import time from pathlib import Path from . import api from .lua import DONE, hex_frame_lua # Mesen2 2.1.1's SnesConfig, measured with offsetof() against its settings header: its size # and the fields set here. Headless, both ports are empty unless configured. SNES_CONFIG_SIZE = 10024 SNES_CONFIG_PORT_TYPES = (988, 1980) # ControllerType (int32) of Port1, Port2 SNES_CONTROLLER = 1 # ControllerType::SnesController SNES_CONFIG_REGION = 9920 # ConsoleRegion: 0 auto, 1 NTSC, 2 PAL REGIONS = {"auto": 0, "ntsc": 1, "pal": 2} # bool DisableFrameSkipping (measured 2026-11-24, as the rest): at maximum speed the PPU # otherwise skips drawing frames on a wall-clock timer, so a frame read from Lua can be one # drawn two or three frames earlier and differs from run to run (OBSERVED on krom's WaveHDMA). SNES_CONFIG_DISABLE_FRAME_SKIPPING = 9931 SNES_CONFIG_CHANNEL_VOLUMES = 9956 # uint32[8], default 100 SNES_CONFIG_RAM_POWER_ON = 9992 # RamState: 0 random, 1 all zeros, 2 all ones SNES_CONFIG_GSU_SPEED = 10008 # uint32, default 100 SNES_CONFIG_BSX_DATE = 10016 # int64, default -1 class SnesConfig(ctypes.Structure): # by value: a bare ctypes array would pass a pointer _fields_ = [("raw", ctypes.c_ubyte * SNES_CONFIG_SIZE)] def snes_config(region: str = "ntsc", ram: int = 1, no_frame_skip: bool = False) -> SnesConfig: """Defaults, plus a standard pad in each port, the region (NTSC unless told), the RAMs powered on as ``ram`` (1 zeros, 2 ones, 0 random: WRAM, VRAM, CGRAM, OAM, ARAM, the DSP's registers and the cartridge's RAMs, except where Mesen2 overrides it for a game by name), and with ``no_frame_skip`` every frame drawn.""" config = SnesConfig() raw = config.raw def put(at: int, value: int, size: int = 4) -> None: raw[at : at + size] = list(value.to_bytes(size, "little", signed=True)) for port in SNES_CONFIG_PORT_TYPES: put(port, SNES_CONTROLLER) put(SNES_CONFIG_REGION, REGIONS[region]) raw[SNES_CONFIG_DISABLE_FRAME_SKIPPING] = int(no_frame_skip) for i in range(8): put(SNES_CONFIG_CHANNEL_VOLUMES + 4 * i, 100) put(SNES_CONFIG_RAM_POWER_ON, ram) put(SNES_CONFIG_GSU_SPEED, 100) put(SNES_CONFIG_BSX_DATE, -1, 8) return config def run( lib: Path, rom: Path, frames: int, home: Path, timeout: float, lua: str | None = None, pads: bool = False, region: str | None = None, reset_at: int | None = None, done: str = DONE, config: SnesConfig | None = None, script_io: bool | None = None, ) -> tuple[str, float]: """Run ``rom``; the script (``lua``, else one that logs frame ``frames`` as hex) ends the run by logging ``done``. Without ``pads``, ``region`` or ``config`` Mesen2's defaults stand: no pads, region auto, random RAM, frame skipping at maximum speed. ``config`` replaces the settings ``pads`` and ``region`` would give; ``script_io`` (None: as Mesen2 has it) allows Lua's io and os libraries. Returns the script's log and the wall time.""" m = api.load(lib) home.mkdir(parents=True, exist_ok=True) api.start(m, home) m.Pause() m.SetEmulationFlag(api.CONSOLE_MODE, True) if script_io is not None: m.SetDebugConfig(api.debug_config(script_io)) if config is not None or pads or region is not None: m.SetSnesConfig.argtypes = [SnesConfig] m.SetSnesConfig(config if config is not None else snes_config(region or "ntsc")) if not m.LoadRom(str(rom.resolve()).encode(), b""): raise SystemExit("LoadRom failed") m.InitializeDebugger() code = (lua or hex_frame_lua(frames, done, reset_at)).encode() script = m.LoadScript(b"frame.lua", str(home.resolve()).encode(), code, -1) m.SetEmulationFlag(api.MAXIMUM_SPEED, True) began = time.monotonic() m.Resume() buf = ctypes.create_string_buffer(1 << 24) log = "" while time.monotonic() - began < timeout: time.sleep(0.05) m.GetScriptLog(script, buf, len(buf)) log = buf.value.decode(errors="replace") if done in log: break api.finish(m) return log, time.monotonic() - began def frame_size(count: int) -> tuple[int, int]: """Width and height of a SNES screen buffer of ``count`` pixels.""" width = 512 if count >= 512 * 448 else 256 return width, count // width