#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later # The decoder below was first written, by alewman, as megadrive-python's MIT # scripts/blastem_events.py (2026-09 to 2026-11-25) and moved here on 2026-11-26; # it keeps that MIT permission (../../notices/MIT-emulator-family.txt). """blastem-events: decode BlastEm's hardware event log (``blastem -e FILE``) into the family tool contract's ``trace/events`` format, so an MIT repository can read the log knowing only this tool's README and emu-tools ``docs/contract.md``. run.py --log FILE --out DIR [--gzip] run.py --version Writes ``DIR/manifest.json`` and ``DIR/events.jsonl`` (``events.jsonl.gz`` with ``--gzip``). Exit status: 0 decoded to the log's last byte; 1 the decode failed or desynchronised (the manifest says where); 2 usage; 3 the log is missing. Layout (OBSERVED on logs of BlastEm 542164d, first learned in 2026-09 from its GPL-3.0 source at that revision; a whole log decodes to its last byte with no desync only when every payload width and rule below is right): ``BLSTEL``, a two-byte big-endian version, then an **uncompressed** start block (system type, video standard, a length-prefixed game name) and a zlib stream of events. An event is a header byte, optionally preceded by a MULTI byte (type 13) whose low nibble says how many more times the next event's type and delta repeat; each repetition carries its own payload. =========================== ================== ========================== ``header & 0xF0`` type delta =========================== ================== ========================== ``< 0xE0`` ``header >> 4`` ``(header & 0xF) + 16`` ``== 0xE0`` ``header & 0xF`` a 16-bit big-endian word ``== 0xF0`` ``header & 0xF`` a sign-extended 24-bit value =========================== ================== ========================== VRAM addresses are carried as deltas from the last one of their kind, so the decoder keeps the last word address and the last byte address. The auto-increment byte event steps by the VDP's auto-increment, which the log carries only as register 15's own writes, tracked from zero. The logged counter is 32 bits and wraps, and the adjust event (type 1) deducts a large amount from it; ``t`` here is absolute time, which only advances by each event's delta and is untouched by an adjust, so it stays continuous (a 12,000-frame Overdrive 2 log read without this appears to stop after 4,008 frames). The wrapped counter BlastEm holds is reported at the end as ``counter_end``. """ from __future__ import annotations import argparse import collections import datetime import gzip import hashlib import json import platform import subprocess import sys import zlib from pathlib import Path TOOL = "blastem-events" VERSION = "0.1.0" CONTRACT = 1 UPSTREAM = {"name": "BlastEm", "commit": "542164d", "licence": "GPL-3.0", "patches": []} FLUSH, ADJUST, PSG_REG, YM_REG, VDP_REG = 0, 1, 2, 3, 4 VRAM_BYTE, VRAM_BYTE_DELTA, VRAM_BYTE_ONE, VRAM_BYTE_AUTO = 5, 6, 7, 8 VRAM_WORD, VRAM_WORD_DELTA, VDP_INTRAM, STATE, MULTI = 9, 10, 11, 12, 13 NAMES = { FLUSH: "flush", ADJUST: "adjust", PSG_REG: "psg", YM_REG: "ym", VDP_REG: "vdp-reg", VRAM_BYTE: "vram-b", VRAM_BYTE_DELTA: "vram-bd", VRAM_BYTE_ONE: "vram-b1", VRAM_BYTE_AUTO: "vram-ba", VRAM_WORD: "vram-w", VRAM_WORD_DELTA: "vram-wd", VDP_INTRAM: "intram", STATE: "state", MULTI: "multi", } # fmt: skip #: A line in BlastEm's cycles, which are master clocks (OBSERVED; 3,420 a line is the #: Mega Drive's own figure, DOC). 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} class Decoder: """Every event of one log, in order, as ``(t, name, fields)``. Iterating to the end without raising *and* finishing on the last byte of the decompressed body is what says the decode is right: one wrong payload width desynchronises the stream and either raises or stops short. """ def __init__(self, data: bytes) -> None: if data[:6] != b"BLSTEL": raise ValueError("not a BlastEm event log (no BLSTEL magic)") self.version = int.from_bytes(data[6:8], "big") self.system_type = data[8] self.video_std = data[9] length = data[10] self.name = data[11 : 11 + length].decode("latin1") self.body = zlib.decompress(data[11 + length :]) self.pos = 0 self.raw = 0 # the counter as BlastEm holds it: 32 bits, wrapping, adjusted self.cycle = 0 # absolute time: only ever advances by an event's delta self.last_word = 0 self.last_byte = 0 self.autoinc = 0 @property def frame_cycles(self) -> int: return FRAME_CYCLES[self.video_std & 1] def _u8(self) -> int: value = self.body[self.pos] self.pos += 1 return value def _u16(self) -> int: value = int.from_bytes(self.body[self.pos : self.pos + 2], "big") self.pos += 2 return value def _payload(self, kind: int) -> dict: if kind == ADJUST: deduction = int.from_bytes(self.body[self.pos : self.pos + 4], "big") self.pos += 4 self.raw = (self.raw - deduction) & 0xFFFFFFFF return {"deduction": deduction} if kind == PSG_REG: return {"value": self._u8()} if kind == YM_REG: part, register, value = self._u8(), self._u8(), self._u8() return {"part": part, "register": register, "value": value} if kind == VDP_REG: register, value = self._u8(), self._u8() if register == 15: self.autoinc = value return {"register": register, "value": value} if kind == VRAM_BYTE: self.last_byte = self._u16() return {"address": self.last_byte, "value": self._u8()} if kind == VRAM_BYTE_DELTA: self.last_byte = (self.last_byte + self._u8()) & 0xFFFF return {"address": self.last_byte, "value": self._u8()} if kind == VRAM_BYTE_ONE: self.last_byte = (self.last_byte + 1) & 0xFFFF return {"address": self.last_byte, "value": self._u8()} if kind == VRAM_BYTE_AUTO: self.last_byte = (self.last_byte + self.autoinc) & 0xFFFF return {"address": self.last_byte, "value": self._u8()} if kind == VRAM_WORD: self.last_word = (self._u8() << 16) | self._u16() return {"address": self.last_word, "value": self._u16()} if kind == VRAM_WORD_DELTA: self.last_word += self._u8() return {"address": self.last_word, "value": self._u16()} if kind == VDP_INTRAM: # The address byte: below 128 a CRAM byte address, from 128 a VSRAM word # index plus 128. Learned in the 2026-09 source reading; decoding to the # last byte checks the width only, so the split is HYPOTHESIS until a log # is replayed against a known CRAM and VSRAM. address, value = self._u8(), self._u16() if address < 128: return {"memory": "cram", "index": (address >> 1) & 63, "value": value} return {"memory": "vsram", "index": address & 63, "value": value} if kind == FLUSH: return {} raise ValueError(f"event type {kind} has no payload this decoder knows") def __iter__(self): while self.pos < len(self.body): repeats = 0 header = self._u8() if header & 0xF0 == MULTI << 4: repeats = header & 0xF header = self._u8() if header & 0xF0 < 0xE0: kind, delta = header >> 4, (header & 0xF) + 16 elif header & 0xF0 == 0xE0: kind, delta = header & 0xF, self._u16() else: kind = header & 0xF delta = self._u8() << 16 if delta & 0x800000: # sign-extended 24-bit (OBSERVED: the log decodes so) delta -= 0x1000000 delta |= self._u16() for _ in range(repeats + 1): self.raw = (self.raw + delta) & 0xFFFFFFFF self.cycle += delta fields = self._payload(kind) yield self.cycle, NAMES.get(kind, f"?{kind}"), fields def _tool_commit() -> str | None: try: here = Path(__file__).resolve().parent out = subprocess.run(["git", "-C", str(here), "rev-parse", "--short", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip dirty = subprocess.run(["git", "-C", str(here), "status", "--porcelain", "--", "."], capture_output=True, text=True, check=True).stdout.strip() # fmt: skip return out + ("-dirty" if dirty else "") except (OSError, subprocess.CalledProcessError): return None def decode(log: Path, out: Path, *, compress: bool = False, argv: list[str] | None = None) -> int: """Decode ``log`` into ``out``; return the exit status.""" data = log.read_bytes() out.mkdir(parents=True, exist_ok=True) events_name = "events.jsonl.gz" if compress else "events.jsonl" manifest = { "contract": CONTRACT, "tool": TOOL, "tool_version": VERSION, "tool_commit": _tool_commit(), "tool_licence": "GPL-3.0-or-later", "upstream": UPSTREAM, "machine": None, "inputs": [{"role": "log", "sha1": hashlib.sha1(data).hexdigest(), "size": len(data)}], "args": list(argv or []), "seed": None, "host": {"os": sys.platform, "arch": platform.machine()}, "started": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), "time_origin": "the log's start: t counts master clocks from 0, absolute " "(continuous across the log's adjust events)", } counts: collections.Counter[str] = collections.Counter() records = 0 error = None decoder = None opener = gzip.open if compress else open with opener(out / events_name, "wt", encoding="utf-8", newline="\n") as f: try: decoder = Decoder(data) for t, name, fields in decoder: f.write(json.dumps({"t": t, "clock": "mclk", "event": name, **fields}, separators=(",", ":")) + "\n") # fmt: skip counts[name] += 1 records += 1 except (ValueError, IndexError, zlib.error) as exc: error = f"{type(exc).__name__}: {exc}" if decoder is not None: manifest["log"] = { "version": decoder.version, "system_type": decoder.system_type, "video_std": decoder.video_std, "name": decoder.name, "line_mclk": LINE_CYCLES, "frame_mclk": decoder.frame_cycles, "body_bytes": len(decoder.body), "decoded_bytes": decoder.pos, "t_end": decoder.cycle, "counter_end": decoder.raw, "counts": dict(counts.most_common()), } if error is None and decoder.pos != len(decoder.body): error = (f"desync: decoded to byte {decoder.pos} of {len(decoder.body)}, " "not on the body's last byte") # fmt: skip manifest["outputs"] = [{"path": events_name, "format": "trace/events", "records": records}] manifest["status"] = "ok" if error is None else "failed" if error is not None: manifest["error"] = error manifest["evidence"] = "OBSERVED" (out / "manifest.json").write_text(json.dumps(manifest, indent=1) + "\n") return 0 if error is None else 1 def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv parser = argparse.ArgumentParser(prog="run.py", description=__doc__.splitlines()[0]) parser.add_argument("--log", type=Path, help="a file written by blastem -e") parser.add_argument("--out", type=Path, help="output directory") parser.add_argument("--gzip", action="store_true", help="write events.jsonl.gz") parser.add_argument("--version", action="store_true", help="print the version") args = parser.parse_args(argv) if args.version: print(f"{TOOL} {VERSION} (format of BlastEm {UPSTREAM['commit']}, contract {CONTRACT})") return 0 if args.log is None or args.out is None: parser.print_usage(sys.stderr) print("run.py: --log and --out are required", file=sys.stderr) return 2 if not args.log.is_file(): print(f"run.py: {args.log}: no such log", file=sys.stderr) return 3 status = decode(args.log, args.out, compress=args.gzip, argv=argv) if status: error = json.loads((args.out / "manifest.json").read_text())["error"] print(f"run.py: {args.log}: {error}", file=sys.stderr) return status if __name__ == "__main__": sys.exit(main())