# SPDX-License-Identifier: GPL-3.0-or-later """The NES adapter: Mesen2's NesConfig, settings that make its frames comparable with a board's, the trace logger's NES line, and a run until a script's marker or a stop. From famicom-python's ``scripts/mesen_run.py`` and ``mesen_audio.py`` (MIT, alewman, first published in famicom-python; ``notices/MIT-emulator-family.txt``), parked 2026-11-21 and regrouped here 2026-11-23 without changing what they do. """ from __future__ import annotations import ctypes import time from pathlib import Path from . import api # Mesen2 2.1.1's NesConfig, measured with offsetof() against its settings header: its size, # and where the fields set here lie. ``configure_for_comparison`` checks two known defaults # before trusting them. NES_CONFIG_SIZE = 14184 NES_CONFIG_PORT1_TYPE = 988 # ControllerType (int32) of Port1 NES_CONFIG_PORT2_TYPE = 1980 NES_CONFIG_AUTO_CONFIGURE_INPUT = 11908 # bool, default true NES_CONFIG_REGION = 11912 # ConsoleRegion (int32): 0 auto, 1 NTSC, 2 PAL, 3 Dendy REGIONS = {"NTSC": 1, "PAL": 2, "Dendy": 3} # by famicom-python's machine.Timing.name NES_CONFIG_SPRITES_ENABLED = 11932 # bool, default true NES_CONFIG_OAM_ROW_CORRUPTION = 11982 # bool: EnablePpuOamRowCorruption, default false NES_CONFIG_RESTRICT_FIRST_FRAME = 11989 # bool: RestrictPpuAccessOnFirstFrame NES_CONFIG_RAM_POWER_ON = 11996 # RamState: 0 random, 1 zeros, 2 ones NES_CONFIG_INPUT_SCANLINE = 12016 # int32, default 241 NES_CONFIG_FULL_COLOR_PALETTE = 12020 # bool NES_CONFIG_USER_PALETTE = 12024 # uint32[512] # NesConfig.ChannelVolumes (uint32[11]), measured the same way. Its default is all 0 (the UI # sets 100), so headless Mesen2 records silence unless they are set. NES_CONFIG_CHANNEL_VOLUMES = 14072 #: The trace logger's line: registers, CPU cycle, PPU scanline and dot, frame. TRACE_FORMAT = ( b"[PC,4h] A:[A,2h] X:[X,2h] Y:[Y,2h] S:[SP,2h] P:[P,h] " b"CYC:[CycleCount] SL:[Scanline] DOT:[Cycle] FR:[FrameCount]" ) class NesConfig(ctypes.Structure): _fields_ = [("raw", ctypes.c_ubyte * NES_CONFIG_SIZE)] def nes_controller(lib: Path | str) -> int: """ControllerType::NesController: 6 on Mesen2, 10 on MesenCE (found by which value gives a pad of eight buttons: MesenCE renumbered the list; with 6 no controller is plugged in).""" return 10 if "mesence" in str(lib).lower() else 6 def load(lib: Path | str) -> ctypes.CDLL: global _library m = _library = api.load(lib) m.GetNesConfig.restype = NesConfig m.SetNesConfig.argtypes = [NesConfig] return m _library: ctypes.CDLL | None = None _pristine: bytes | None = None def pristine() -> None: """Batch mode only: the NesConfig the library started with, saved by the first run and restored by each later one, so no setting of one run (channel volumes, say) reaches the next. Outside batch mode nothing is done.""" global _pristine if not api.KEEP or _library is None: return if _pristine is None: _pristine = bytes(_library.GetNesConfig().raw) else: _library.SetNesConfig(NesConfig.from_buffer_copy(_pristine)) def configure_for_comparison( m: ctypes.CDLL, region: int = 1, ppu_reset_at_power: bool = True, oam_row_corruption: bool = True, controller: int = 6, ram: int = 1, ) -> None: """Make Mesen2's frames comparable with a board's, pixel value for pixel value. - A 512-entry identity palette: headless, nothing loads a palette (the UI normally does), so frames come out black; with entry i = i, ``emu.getScreenBuffer()`` returns palette value | emphasis << 6. - The PPU ignores $2000/$2001/$2005/$2006 writes until the first pre-render line if ``ppu_reset_at_power``, as the NES-001 does; Mesen2 does not by default. - Work RAM (and the other memories Mesen2 initialises with it) powers on as ``ram``: 1 zeros (the default here), 2 ones, 0 random; Mesen2's default is random. - A standard controller in each port and no input configured from Mesen2's game database (which plugs a Zapper into port 2 for some games); headless, the ports are otherwise empty. - The ``region`` given whatever the dump's (NTSC by default). - OAM row corruption on unless ``oam_row_corruption`` is false (off by default in Mesen2). """ config = m.GetNesConfig() raw = config.raw if ( raw[NES_CONFIG_SPRITES_ENABLED] != 1 or int.from_bytes( bytes(raw[NES_CONFIG_INPUT_SCANLINE : NES_CONFIG_INPUT_SCANLINE + 4]), "little" ) != 241 ): raise SystemExit("NesConfig layout does not match Mesen2 2.1.1; re-measure the offsets") raw[NES_CONFIG_REGION : NES_CONFIG_REGION + 4] = [region, 0, 0, 0] raw[NES_CONFIG_AUTO_CONFIGURE_INPUT] = 0 for port in (NES_CONFIG_PORT1_TYPE, NES_CONFIG_PORT2_TYPE): raw[port : port + 4] = [controller, 0, 0, 0] raw[NES_CONFIG_RESTRICT_FIRST_FRAME] = int(ppu_reset_at_power) raw[NES_CONFIG_RAM_POWER_ON] = ram raw[NES_CONFIG_OAM_ROW_CORRUPTION] = int(oam_row_corruption) raw[NES_CONFIG_FULL_COLOR_PALETTE] = 1 for i in range(512): at = NES_CONFIG_USER_PALETTE + 4 * i raw[at : at + 4] = list(i.to_bytes(4, "little")) m.SetNesConfig(config) def set_channel_volumes(m: ctypes.CDLL, apu: bool = True) -> None: """All eleven channel volumes to 100; the APU's five (square 1, 2, triangle, noise, DMC, the first five) to 0 if not ``apu``.""" config = m.GetNesConfig() for i in range(11): at = NES_CONFIG_CHANNEL_VOLUMES + 4 * i volume = 100 if apu or i >= 5 else 0 config.raw[at : at + 4] = list(volume.to_bytes(4, "little")) m.SetNesConfig(config) def run( lib: Path | str, rom: Path, *, lua: bytes | None = None, lua_name: str = "script.lua", seconds: float = 2.0, home: Path = Path("mesen-home"), trace: Path | None = None, until: str | None = None, max_speed: bool = True, for_comparison: bool = False, region: int = 1, ppu_reset_at_power: bool = True, collect: dict[str, str] | None = None, oam_row_corruption: bool = True, trace_format: bytes = TRACE_FORMAT, ram: int = 1, script_io: bool | None = None, poll: float = 0.05, ) -> tuple[int, str, float]: """Run ``rom`` until the Lua script stops it, logs ``until``, or ``seconds`` pass. Mesen2 discards a script's log when ``emu.stop`` ends emulation, so a script that reports through its log prints ``until`` as its last line instead and keeps running; this polls for it and then stops (stop code 0). Returns the stop code (-1 on timeout), the script's log and the wall time. ``collect`` gathers lines ``KEY text`` (keys starting L or E) as they pass through the log, which keeps only its last 500. ``ram`` is the power-on RAM setting with ``for_comparison`` (``configure_for_comparison``); ``script_io`` (None: left as Mesen2 has it) sets whether Lua may use its io and os libraries. """ m = load(lib) home.mkdir(parents=True, exist_ok=True) api.start(m, home) m.Pause() m.SetEmulationFlag(api.CONSOLE_MODE, True) pristine() if script_io is not None: m.SetDebugConfig(api.debug_config(script_io)) if for_comparison: configure_for_comparison( m, region, ppu_reset_at_power, oam_row_corruption, nes_controller(lib), ram ) if not m.LoadRom(str(rom.resolve()).encode(), b""): raise SystemExit("LoadRom failed") m.InitializeDebugger() script_id = -1 if lua is not None: script_id = m.LoadScript(lua_name.encode(), str(home.resolve()).encode(), lua, -1) if trace: opts = api.TraceLoggerOptions(True, False, False, b"", trace_format) m.SetTraceOptions(api.CPU_TYPES["nes"], opts) m.StartLogTraceToFile(str(trace.resolve()).encode()) m.SetEmulationFlag(api.MAXIMUM_SPEED, max_speed) began = time.monotonic() m.Resume() result = -1 log = "" buf = ctypes.create_string_buffer(1 << 22) while time.monotonic() - began < seconds: time.sleep(poll) if until is not None: m.GetScriptLog(script_id, buf, len(buf)) log = buf.value.decode(errors="replace") if collect is not None: for line in log.splitlines(): key, _, text = line.partition(" ") if key[:1] in ("L", "E") and text: collect[key] = text if until in log: result = 0 break if not m.IsRunning(): result = m.GetStopCode() break if trace: m.StopLogTraceToFile() if script_id >= 0 and until is None: m.GetScriptLog(script_id, buf, len(buf)) log = buf.value.decode(errors="replace") api.finish(m) return result, log, time.monotonic() - began def record_wave( lib: Path | str, rom: Path, frames: int, out: Path, home: Path, seconds: float = 300, apu: bool = True, stop_lua: str | None = None, ram: int = 1, exact: bool = False, ) -> None: """Record Mesen2's mixed output (its WAV recorder, after its own mixer and resampler) for the first ``frames`` frames into ``out``, compared-for settings (power-on RAM ``ram``), channel volumes at 100 (the APU's five at 0 if not ``apu``). With ``exact`` (run.py, from 0.3.0) the script holds the emulator at the end of frame ``frames`` before it tells the runner, so the recording stops there every run; without it (the old shim) the emulator runs on while the runner polls, and the recording may run a few frames past.""" from .lua import STOP_HOLD_LUA, STOP_LUA m = load(lib) m.WaveRecord.argtypes = [ctypes.c_char_p] home.mkdir(parents=True, exist_ok=True) api.start(m, home) m.Pause() m.SetEmulationFlag(api.CONSOLE_MODE, True) pristine() configure_for_comparison(m, controller=nes_controller(lib), ram=ram) set_channel_volumes(m, apu) if not m.LoadRom(str(rom.resolve()).encode(), b""): raise SystemExit("LoadRom failed") m.InitializeDebugger() script = m.LoadScript( b"stop.lua", str(home.resolve()).encode(), ((stop_lua or (STOP_HOLD_LUA if exact else STOP_LUA)) % frames).encode(), -1 ) m.WaveRecord(str(out.resolve()).encode()) m.SetEmulationFlag(api.MAXIMUM_SPEED, True) m.Resume() began = time.monotonic() buf = ctypes.create_string_buffer(1 << 16) while time.monotonic() - began < seconds: time.sleep(0.02) m.GetScriptLog(script, buf, len(buf)) if b"DONE" in buf.value: break m.Pause() m.WaveStop() api.finish(m)