# SPDX-License-Identifier: MIT """Read BlastEm's hardware event log (``blastem -b FRAMES -e FILE rom``) through the family's GPL tool ``blastem-events``. BlastEm is emulator-derived, so under the tier rule it is a **detector**: its log says *where to look*, never what is correct. It earns its place because its author is Mask of Destiny, whose ``gen_test_z80_bus`` this repository already treats as hardware tier, and because it runs cartridges MAME 0.285 cannot -- the Krikzz Extended SSF ones, where MAME has no header rule, puts Earthion on ``rom_sram`` and draws noise (docs/worklog.md, 2026-09-24). **Where the decoding is.** The log's binary layout was first learned in 2026-09 from BlastEm's GPL-3.0 source, so on 2026-11-26 the decoder moved to emu-tools-gpl as ``$EMU_TOOLS_GPL/tools/blastem-events/run.py`` (docs/provenance.md). This file runs it as a separate program and reads only what it writes: ``manifest.json`` and ``events.jsonl``, the family tool contract's ``trace/events`` format, one JSON record per event with ``t`` (master clocks, absolute) and ``event`` (a name) and the fields the tool's README lists for that name. Nothing here knows the log's bytes. With ``EMU_TOOLS_GPL`` unset or the tool absent, a script stops with exit status 3 naming the variable and the path (the contract's "Unset is a missing input"). What a reader of the log needs to know (OBSERVED on logs of BlastEm 542164d): - The ``flush`` event is **not** a frame marker. It is an output-buffer flush, and the count happens to land near the frame count (599 for a 600-frame run), which is what made it look like one. Use :meth:`Log.frame_of` instead. - A cycle is **one master clock**, not a 68000 clock and not half a master clock. The VDP's clock, which stamps every VDP event, advances 3,420 a line and 16 an H40 slot (the Mega Drive's own figures, DOC). This reader once took it for half a master clock, which doubled every frame number it gave; the data says so: Overdrive 2's once-a-line VSRAM writes land 3,420 apart. - **``-b N`` runs N/2 frames, not N**, at least headless at 542164d: the log of ``-b 12000`` on Overdrive 2 ends 6,423,581,234 master clocks in, 6,001 PAL frames, and its last write is the board's in frame 6,001. Ask for twice the frames wanted, and trust :meth:`Log.frame_of`, not the argument. - ``t`` is absolute time and continuous across the whole log (the tool's README says how it keeps it so); the counter BlastEm itself holds is the manifest's ``counter_end``. """ from __future__ import annotations import argparse import collections import gzip import json import os import subprocess import sys import tempfile from collections.abc import Iterator from pathlib import Path #: The tool's documented path under ``EMU_TOOLS_GPL`` (its README, tools/README.md). TOOL_PATH = "tools/blastem-events/run.py" #: The tool version this repository was checked against (docs/provenance.md). TOOL_VERSION = "0.1.0" #: A line in BlastEm's cycles, which are master clocks (OBSERVED, above; DOC figure). LINE_CYCLES = 3420 #: A frame in BlastEm's cycles, by video standard: 262 lines NTSC and 313 PAL (DOC). FRAME_CYCLES = {0: 262 * LINE_CYCLES, 1: 313 * LINE_CYCLES} #: The event names of the VRAM byte writes and word writes (the tool's README). VRAM_BYTE_EVENTS = frozenset({"vram-b", "vram-bd", "vram-b1", "vram-ba"}) VRAM_WORD_EVENTS = frozenset({"vram-w", "vram-wd"}) class ToolError(RuntimeError): """The tool ran and said the log did not decode (its manifest's ``error``).""" def tool_path() -> Path | None: """``$EMU_TOOLS_GPL/tools/blastem-events/run.py`` if it is there, else ``None``.""" root = os.environ.get("EMU_TOOLS_GPL") if not root: return None path = Path(root, TOOL_PATH) return path if path.is_file() else None def require_tool() -> Path: """The tool's path, or stop with exit status 3 naming the variable and the path.""" path = tool_path() if path is None: root = os.environ.get("EMU_TOOLS_GPL") state = f"EMU_TOOLS_GPL={root}" if root else "EMU_TOOLS_GPL is unset" print( f"blastem_events: $EMU_TOOLS_GPL/{TOOL_PATH} not found ({state}): set " "EMU_TOOLS_GPL to a checkout of emu-tools-gpl (the family tool contract, " "'Finding a tool')", file=sys.stderr, ) raise SystemExit(3) return path class Log: """One decoded log: the tool's manifest and its events. ``Log.decode(path)`` runs the tool; ``Log(directory)`` reads a directory it wrote. """ def __init__(self, directory: Path, *, keep: object = None) -> None: self.directory = Path(directory) self._keep = keep # a TemporaryDirectory that lives as long as this object self.manifest = json.loads((self.directory / "manifest.json").read_text()) info = self.manifest.get("log", {}) self.version = info.get("version") self.system_type = info.get("system_type") self.video_std = info.get("video_std", 0) self.name = info.get("name", "") self.body_bytes = info.get("body_bytes", 0) self.decoded_bytes = info.get("decoded_bytes", 0) self.t_end = info.get("t_end", 0) self.counter_end = info.get("counter_end", 0) self.frame_cycles = info.get("frame_mclk", FRAME_CYCLES[self.video_std & 1]) self.status = self.manifest["status"] self.error = self.manifest.get("error") (output,) = (o for o in self.manifest["outputs"] if o["format"] == "trace/events") self.events_path = self.directory / output["path"] self.records = output["records"] @classmethod def decode(cls, log: Path, out: Path | None = None) -> Log: """Run the tool on ``log`` into ``out`` (a temporary directory if not given).""" tool = require_tool() keep = None if out is None: keep = tempfile.TemporaryDirectory(prefix="blastem-events-") out = Path(keep.name) proc = subprocess.run( [sys.executable, "-I", str(tool), "--log", str(log), "--out", str(out)], capture_output=True, text=True, ) if proc.returncode not in (0, 1) or not (Path(out) / "manifest.json").is_file(): raise ToolError(f"blastem-events exited {proc.returncode}: {proc.stderr[-400:]}") return cls(Path(out), keep=keep) @property def tag(self) -> str: """The evidence tag a value from this log carries (the contract, section 3).""" m = self.manifest return (f"OBSERVED (BlastEm @ {m['upstream']['commit']} log format, via " f"{m['tool']} {m['tool_version']})") # fmt: skip def frame_of(self, cycle: int) -> int: """Which frame a cycle falls in. The honest frame marker, unlike ``flush``.""" return cycle // self.frame_cycles def __iter__(self) -> Iterator[dict]: """Every event record, in order, as the tool wrote it.""" opener = gzip.open if self.events_path.suffix == ".gz" else open with opener(self.events_path, "rt", encoding="utf-8") as f: for line in f: yield json.loads(line) def check(self) -> None: """Raise :class:`ToolError` unless the tool decoded the log to its last byte.""" if self.status != "ok": raise ToolError(self.error or f"blastem-events status {self.status}") def register_writes(log: Log) -> dict[int, list[tuple[int, int]]]: """The VDP register writes of each frame, keyed by frame number.""" frames: dict[int, list[tuple[int, int]]] = collections.defaultdict(list) for event in log: if event["event"] == "vdp-reg": frames[log.frame_of(event["t"])].append((event["register"], event["value"])) return dict(frames) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("log", type=Path, help="a file written by blastem -e") parser.add_argument("--frames", type=int, metavar="N", help="print the VDP register writes of the first N frames") # fmt: skip parser.add_argument("--tool-out", type=Path, metavar="DIR", help="keep the tool's manifest and events here") # fmt: skip args = parser.parse_args() log = Log.decode(args.log, args.tool_out) if log.status != "ok" and log.decoded_bytes == 0: print(f"{args.log.name}: {log.error}", file=sys.stderr) return 1 counts: collections.Counter[str] = collections.Counter() registers: collections.Counter[int] = collections.Counter() last = 0 for event in log: counts[event["event"]] += 1 last = event["t"] if event["event"] == "vdp-reg": registers[event["register"]] += 1 total = sum(counts.values()) standard = "PAL" if log.video_std & 1 else "NTSC" print(f"{args.log.name}: {log.name!r}, {standard}, version {log.version}") print(f" {total:,} events over {log.frame_of(last) + 1} frames " f"({last:,} master clocks); decoded to byte {log.decoded_bytes:,} of " f"{log.body_bytes:,}") # fmt: skip if log.status != "ok": print(f" WARNING: the decode failed: {log.error}") return 1 for name, count in counts.most_common(): print(f" {name:<9} {count:>9,}") if registers: print(" VDP registers written: " + ", ".join(f"{r}x{n}" for r, n in sorted(registers.items()))) # fmt: skip if args.frames: for frame, writes in sorted(register_writes(log).items()): if frame >= args.frames: break print(f" frame {frame:>4}: " + " ".join(f"{r}:{v:02X}" for r, v in writes)) return 0 if __name__ == "__main__": sys.exit(main())