# SPDX-License-Identifier: GPL-3.0-or-later """Lua scripts the runner loads into Mesen2, and the readers of what they log. Mesen2's script log is the channel out of the emulator: it keeps its last 500 lines, and a script's log is discarded when ``emu.stop`` ends emulation, so a script reports a marker as its last line and keeps running while the runner polls for it. Two frame formats travel through it: - **hex**: one ``PIXELS `` line holding the whole screen buffer, six hex digits a pixel, at the frame a script names (SNES, PC Engine, Cx4 runs); - **base64 lines**: two characters a pixel from a 64-letter alphabet, in numbered lines of 280 characters (``L.``, then ``E ``), for consoles whose buffer values fit 12 bits (the NES with an identity palette), so many frames fit the 500-line log. The scripts came from famicom-, snes- and pcengine-python's drivers (MIT, alewman; ``notices/MIT-emulator-family.txt``). """ from __future__ import annotations DONE = "MESEN-DONE" # -- hex frames --------------------------------------------------------------------------- #: Count frames; at frame ``{frames}`` log the screen buffer as hex and ``{done}``; ``{reset}`` #: is a line run every frame before the test (empty, or a reset at a frame). HEX_FRAME_LUA = """\ local frames = 0 emu.addEventCallback(function() frames = frames + 1 {reset} if frames == {frames} then local buf = emu.getScreenBuffer() local parts = {{}} for i = 1, #buf do parts[i] = string.format("%06x", buf[i]) end emu.log("PIXELS " .. #buf .. " " .. table.concat(parts)) emu.log("{done}") end end, emu.eventType.endFrame) """ def hex_frame_lua(frames: int, done: str = DONE, reset_at: int | None = None) -> str: reset = f" if frames == {reset_at} then emu.reset() end\n" if reset_at else "" return HEX_FRAME_LUA.format(frames=frames, done=done, reset=reset) def hex_pixels(log: str) -> tuple[int, bytes]: """The pixel count and the RGB bytes of the first ``PIXELS`` line in ``log``.""" line = next(x for x in log.splitlines() if x.startswith("PIXELS ")) _, count, hexes = line.split(" ", 2) return int(count), bytes.fromhex(hexes) # -- base64-line frames ------------------------------------------------------------------- ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/" #: ``%s`` the wanted frames as a Lua set (``[60]=true, [300]=true``), ``%d`` the last frame #: (after which ``DONE`` is logged). FRAMES_LUA = """ local wanted, frame, last = {%s}, 0, %d local alphabet = "ALPHABET" local digit = {} for i = 1, 64 do digit[i - 1] = alphabet:sub(i, i) end emu.addEventCallback(function() frame = frame + 1 if wanted[frame] then local buffer = emu.getScreenBuffer() local parts = {} for i = 1, #buffer do local v = buffer[i] parts[i] = digit[(v // 64) %% 64] .. digit[v %% 64] end local all = table.concat(parts) local count = 0 for at = 1, #all, 280 do emu.log("L" .. frame .. "." .. count .. " " .. all:sub(at, at + 279)) count = count + 1 end emu.log("E" .. frame .. " " .. count) end if frame == last then emu.log("DONE") end end, emu.eventType.endFrame) """.replace("ALPHABET", ALPHABET) def frames_lua(frames: list[int]) -> str: return FRAMES_LUA % (", ".join(f"[{f}]=true" for f in frames), max(frames)) def decode_frames(lines: dict[str, str]) -> dict[int, list[int]]: """The complete frames among collected ``L``/``E`` log lines (``KEY -> text``).""" frames = {} for key, text in lines.items(): if key.startswith("E"): frame, count = int(key[1:]), int(text) parts = [lines.get(f"L{frame}.{n}") for n in range(count)] if None in parts: continue data = "".join(parts) frames[frame] = [ ALPHABET.index(data[i]) << 6 | ALPHABET.index(data[i + 1]) for i in range(0, len(data), 2) ] return frames # -- the full log (run.py, from 0.2.0) ---------------------------------------------------- #: What run.py puts before every line its own scripts log, so script-log.txt keeps exactly the #: lines the player's script logged, even in the runner's own formats (famicom-python's scripts #: log frames as ``L``/``E`` lines and ``DONE`` too). TAG = "@mesen2-runner " def tagged(script: str) -> str: """``script`` (one of the runner's own) with every ``emu.log`` line prefixed by ``TAG``.""" return script.replace("emu.log(", f'emu.log("{TAG}" .. ') def untag(lines: list[str]) -> tuple[list[str], list[str]]: """The runner's own lines (tag removed) and everything else, each in order.""" own, others = [], [] for line in lines: if line.startswith(TAG): own.append(line[len(TAG) :]) else: others.append(line) return own, others #: Placed first in a run.py script: every ``emu.log`` line is also written, as it is logged, to #: the file named (line-buffered), so the runner reads the whole log afterwards, not the last #: 500 lines Mesen2 keeps. The file is closed after the runner's (tagged) ``RUN-DONE`` (the end of the last #: frame, logged after every other script's callbacks), so what the emulator runs while it is #: being stopped never reaches it. Needs Lua's io library, which the runner allows for that run #: (Mesen2's DebugConfig, ``api.debug_config``). ``%s`` the file's path. FULL_LOG_LUA = """\ local mesen2_runner_log_file = assert(io.open([==[%s]==], "w")) mesen2_runner_log_file:setvbuf("line") local mesen2_runner_emu_log = emu.log emu.log = function(text, ...) if mesen2_runner_log_file then mesen2_runner_log_file:write(tostring(text), "\\n") if text == "@mesen2-runner RUN-DONE" then mesen2_runner_log_file:close() mesen2_runner_log_file = nil end end return mesen2_runner_emu_log(text, ...) end function mesen2_runner_write(text) if mesen2_runner_log_file then mesen2_runner_log_file:write(text, "\\n") end end """ def full_log_lua(path) -> str: text = str(path) if "]==]" in text or "\n" in text: raise ValueError(f"the script log's path cannot be quoted for Lua: {text!r}") return FULL_LOG_LUA % text #: Placed last in a run.py script: log ``%s`` at the end of frame ``%d``, after every other #: script's callbacks for that frame have run (callbacks run in the order they were added), so #: the runner never stops the emulator before a script's last-frame lines are logged. DONE_LAST_LUA = """ local mesen2_runner_done_frames = 0 emu.addEventCallback(function() mesen2_runner_done_frames = mesen2_runner_done_frames + 1 if mesen2_runner_done_frames == %d then emu.log("%s") end end, emu.eventType.endFrame) """ def done_last_lua(frames: int, marker: str) -> str: return DONE_LAST_LUA % (frames, marker) #: Press the console's reset button at the end of frame ``%d`` (frames count on through it). #: Mesen2 takes the request at a frame boundary of its own (the SNES's right after that frame's #: end-of-frame event, the NES's one frame later), so the reset lands at the same emulated moment #: on every run (OBSERVED 2026-11-24). Not used for the PC Engine, where it stalled the emulator. RESET_LUA = """ local mesen2_runner_reset_frames = 0 emu.addEventCallback(function() mesen2_runner_reset_frames = mesen2_runner_reset_frames + 1 if mesen2_runner_reset_frames == %d then emu.reset() end end, emu.eventType.endFrame) """ def reset_lua(frame: int) -> str: return RESET_LUA % frame # -- ending a run early (run.py, from 0.3.0) ---------------------------------------------- #: Placed after the full-log script, before every other: the player's ``emu.stop(code)`` no #: longer stops Mesen2 (whose own stop runs on another thread, at a moment the host's timing #: picks, and discards the script log); it records the code (the first non-zero one, as Mesen2 #: keeps it) and the run ends at the end of that frame (``END_FRAME_LUA``). With ``--until #: log:TEXT`` a line the player logs that starts with TEXT does the same. STOP_UNTIL_LUA = """\ mesen2_runner_stop_code = nil mesen2_runner_until_hit = false emu.stop = function(code) code = math.tointeger(code) or 0 if mesen2_runner_stop_code == nil or mesen2_runner_stop_code == 0 then mesen2_runner_stop_code = code end end """ UNTIL_LOG_LUA = """\ local mesen2_runner_until = [==[%s]==] local mesen2_runner_until_log = emu.log emu.log = function(text, ...) if not mesen2_runner_until_hit and string.sub(tostring(text), 1, #mesen2_runner_until) == mesen2_runner_until then mesen2_runner_until_hit = true end return mesen2_runner_until_log(text, ...) end """ def stop_until_lua(until_log: str | None = None) -> str: """The ``emu.stop`` wrapper, and with ``until_log`` the line prefix that ends a run.""" if until_log is None: return STOP_UNTIL_LUA if "]==]" in until_log or "\n" in until_log or not until_log: raise ValueError(f"--until log:TEXT cannot be quoted for Lua: {until_log!r}") return STOP_UNTIL_LUA + UNTIL_LOG_LUA % until_log #: Placed last in a run.py script: the end of the run. At the end of frame ``{frames}``, or of #: the frame in which the player's script called ``emu.stop`` or logged the ``--until`` line, #: log ``END `` (early or asked-for ends only), the picture of that frame if #: ``{picture}`` asks and the frame scripts did not log it (``{picture}`` is Lua run with ``n`` #: the frame), hold the emulator if ``{hold}``, then the marker. Callbacks run in the order #: they were added, so every other script's lines for that frame come first. END_FRAME_LUA = """ local mesen2_runner_end_frames, mesen2_runner_ended = 0, false emu.addEventCallback(function() if mesen2_runner_ended then return end mesen2_runner_end_frames = mesen2_runner_end_frames + 1 local n = mesen2_runner_end_frames local early = mesen2_runner_stop_code ~= nil or mesen2_runner_until_hit if n == {frames} or early then mesen2_runner_ended = true if early then local by = mesen2_runner_stop_code ~= nil and "script-stop" or "until" emu.log("END " .. by .. " " .. tostring(mesen2_runner_stop_code or "-") .. " " .. n) if n ~= {frames} then {picture} end end {hold}emu.log("{marker}") end end, emu.eventType.endFrame) """ #: The NES picture of frame ``n`` in base64 lines (``FRAMES_LUA``'s format), unless ``n`` is one #: of ``mesen2_runner_wanted`` (logged already). NES_PICTURE_LUA = """\ if not mesen2_runner_wanted[n] then local alphabet = "ALPHABET" local buffer, parts = emu.getScreenBuffer(), {} for i = 1, #buffer do local v = buffer[i] local hi, lo = (v // 64) % 64 + 1, v % 64 + 1 parts[i] = alphabet:sub(hi, hi) .. alphabet:sub(lo, lo) end local all, count = table.concat(parts), 0 for at = 1, #all, 280 do emu.log("L" .. n .. "." .. count .. " " .. all:sub(at, at + 279)) count = count + 1 end emu.log("E" .. n .. " " .. count) end""".replace("ALPHABET", ALPHABET) #: The SNES, Cx4 or PC Engine picture of frame ``n`` as a hex ``PIXELS`` line. HEX_PICTURE_LUA = """\ local buf, parts = emu.getScreenBuffer(), {} for i = 1, #buf do parts[i] = string.format("%06x", buf[i]) end emu.log("PIXELS " .. #buf .. " " .. table.concat(parts))""" def end_frame_lua(frames: int, marker: str, picture: str = "", hold: bool = False) -> str: return (END_FRAME_LUA.replace("{frames}", str(frames)).replace("{marker}", marker) .replace("{picture}", picture or " -- no picture asked for") .replace("{hold}", "emu.breakExecution(); " if hold else "")) # fmt: skip def wanted_lua(frames: list[int]) -> str: """``mesen2_runner_wanted``: the frames the NES frame script logs.""" return "mesen2_runner_wanted = {%s}\n" % ", ".join(f"[{f}]=true" for f in frames) #: SNES ``--frames-at``: at each wanted frame, the screen buffer as one hex line, written to the #: full log only (``mesen2_runner_write``: a hi-res frame is 1.4 MB of text, too much for #: Mesen2's own 500-line log), tagged as the runner's: ``FRAME-PIXELS ``. SNES_FRAMES_AT_LUA = """ local mesen2_runner_at, mesen2_runner_at_frames = {%s}, 0 emu.addEventCallback(function() mesen2_runner_at_frames = mesen2_runner_at_frames + 1 local n = mesen2_runner_at_frames if mesen2_runner_at[n] then local buf, parts = emu.getScreenBuffer(), {} for i = 1, #buf do parts[i] = string.format("%%06x", buf[i]) end mesen2_runner_write("%sFRAME-PIXELS " .. n .. " " .. #buf .. " " .. table.concat(parts)) end end, emu.eventType.endFrame) """ def snes_frames_at_lua(frames: list[int]) -> str: return SNES_FRAMES_AT_LUA % (", ".join(f"[{f}]=true" for f in frames), TAG) def frame_pixels(lines: list[str]) -> dict[int, tuple[int, bytes]]: """``FRAME-PIXELS`` lines (the runner's own, tag removed): frame -> (count, RGB bytes).""" found = {} for line in lines: if line.startswith("FRAME-PIXELS "): _, frame, count, hexes = line.split(" ", 3) found[int(frame)] = (int(count), bytes.fromhex(hexes)) return found def end_of_run(lines: list[str]) -> dict | None: """The ``END by code frame`` line (the runner's own, tag removed), or None.""" for line in lines: if line.startswith("END "): _, by, code, frame = line.split(" ") return {"by": by, "frame": int(frame), **({"stop_code": int(code)} if code != "-" else {})} return None # -- stopping ----------------------------------------------------------------------------- #: Count frames and log ``DONE`` at frame ``%d``. STOP_LUA = """ local target, frame = %d, 0 emu.addEventCallback(function() frame = frame + 1 if frame == target then emu.log("DONE") end end, emu.eventType.endFrame) """ #: ``STOP_LUA``, holding the emulator first (``record_wave(exact=True)``): the WAV recorder is #: stopped while nothing more is mixed. STOP_HOLD_LUA = """ local target, frame = %d, 0 emu.addEventCallback(function() frame = frame + 1 if frame == target then emu.breakExecution(); emu.log("DONE") end end, emu.eventType.endFrame) """