#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """ym2203-lle's command line (README.md): one run of YM2203-LLE's SSG harness, with a manifest. python3 -I run.py --input WRITES.jsonl --cycles N --out DIR [--phase P] python3 -I run.py --version WRITES.jsonl: one register write a line, {"t": step, "reg": 0-255, "value": 0-255}, at most one to a step. --cycles counts steps (one turn of the SSG's shared counter, four master clocks); --phase (0-3) is the master clock of the step a write lands on. Writes ssg.bin (three 32-bit floats per step) and the contract's manifest.json. """ from __future__ import annotations import argparse import datetime import hashlib import json import platform import struct import subprocess import sys import tempfile from pathlib import Path TOOL, VERSION = "ym2203-lle", "0.1.0" HERE = Path(__file__).resolve().parent BUILD = HERE / "build" UPSTREAM = {"name": "YM2203-LLE", "url": "https://github.com/nukeykt/YM2203-LLE", "commit": "817387fd89affd0db5331034d6ae04d919e25a5e", "licence": "GPL-2.0-or-later", "patches": []} EXIT_OK, EXIT_CHECK, EXIT_USAGE, EXIT_MISSING = 0, 1, 2, 3 class Usage(Exception): pass def tool_commit() -> str: try: head = subprocess.run(["git", "-C", str(HERE), "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() dirty = subprocess.run(["git", "-C", str(HERE), "status", "--porcelain", "--", "."], capture_output=True, text=True, check=True).stdout.strip() except (OSError, subprocess.CalledProcessError): return "unknown" return head + ("-dirty" if dirty else "") def read_writes(path: Path) -> list[tuple[int, int, int]]: rows = [] for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): if not line.strip(): continue try: row = json.loads(line) t, reg, value = int(row["t"]), int(row["reg"]), int(row["value"]) except (ValueError, KeyError, TypeError) as error: raise Usage(f"{path}:{number}: {error}") from None if t < 0 or not 0 <= reg <= 255 or not 0 <= value <= 255: raise Usage(f"{path}:{number}: t >= 0, reg and value 0-255") rows.append((t, reg, value)) rows.sort(key=lambda r: r[0]) if any(x[0] == y[0] for x, y in zip(rows, rows[1:])): raise Usage(f"{path}: at most one write to a step") return rows def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv p = argparse.ArgumentParser(prog="run.py", description="Run YM2203-LLE's SSG on writes.") p.add_argument("--version", action="store_true") p.add_argument("--input", type=Path, help="register writes (JSON Lines: t, reg, value)") p.add_argument("--cycles", type=int, help="steps to run (four master clocks each)") p.add_argument("--phase", type=int, default=0, help="master clock of the step a write lands on (0-3)") p.add_argument("--out", type=Path) a = p.parse_args(argv) if a.version: print(f"{TOOL} {VERSION} (YM2203-LLE {UPSTREAM['commit'][:7]})") return EXIT_OK started = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") try: if not (a.input and a.cycles and a.out) or a.cycles < 1 or not 0 <= a.phase <= 3: raise Usage("--input, --cycles (>= 1) and --out are required; --phase is 0-3") if not a.input.is_file(): print(f"no such input: {a.input}", file=sys.stderr) return EXIT_MISSING writes = read_writes(a.input) if not (BUILD / "ssg_ref").exists(): print(f"no {BUILD / 'ssg_ref'}: run build.sh", file=sys.stderr) return EXIT_MISSING except Usage as error: p.print_usage(sys.stderr) print(f"run.py: {error}", file=sys.stderr) return EXIT_USAGE a.out.mkdir(parents=True, exist_ok=True) out = a.out / "ssg.bin" with tempfile.TemporaryDirectory(prefix="ym2203-lle-") as scratch: events = Path(scratch) / "events.bin" events.write_bytes(b"".join(struct.pack("