#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only """ym2608-lle's command line (README.md): one run of a YM2608-LLE harness, with a manifest. python3 -I run.py --machine ym2610 --out DIR [--measure NAME [ARG ...]] python3 -I run.py --machine ym2612 --input WRITES.jsonl --cycles N --out DIR [--stride N] python3 -I run.py --version ym2610 runs build/lle2610_probe (every measurement, or one by name with its arguments) and keeps its text output; ym2612 runs build/lle2612_ref on a write script and keeps its DAC pin records. Both write the contract's manifest.json. Exit status as the contract says. """ 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 = "ym2608-lle", "0.1.0" HERE = Path(__file__).resolve().parent BUILD = HERE / "build" UPSTREAM = {"name": "YM2608-LLE", "url": "https://github.com/nukeykt/YM2608-LLE", "commit": "7a2aca7b6830b96e48e3a4e1a40d15525993fa60", "licence": "GPL-2.0-only"} MEASURES = ("clock", "fm", "ssg", "busy", "timers", "flagctl", "pages", "adpcma", "adpcmb", "lfo") 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]]: """(chip clock, port 0-3, data) sorted by clock, from JSON Lines {t, port, data}.""" 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, port, data = int(row["t"]), int(row.get("port", 0)), int(row["data"]) except (ValueError, KeyError, TypeError) as error: raise Usage(f"{path}:{number}: {error}") from None if t < 0 or not 0 <= port <= 3 or not 0 <= data <= 255: raise Usage(f"{path}:{number}: t >= 0, port 0-3, data 0-255") rows.append((t, port, data)) return sorted(rows, key=lambda r: r[0]) 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 a YM2608-LLE harness.") p.add_argument("--version", action="store_true") p.add_argument("--machine", choices=("ym2610", "ym2612")) p.add_argument("--measure", nargs="+", metavar="NAME", help="ym2610: one measurement and its arguments") p.add_argument("--input", type=Path, help="ym2612: write script (JSON Lines: t, port, data)") p.add_argument("--cycles", type=int, help="ym2612: chip clocks to run (master clock / 7)") p.add_argument("--stride", type=int, default=1, help="ym2612: keep one record in N") p.add_argument("--out", type=Path) a = p.parse_args(argv) if a.version: print(f"{TOOL} {VERSION} (YM2608-LLE {UPSTREAM['commit'][:7]})") return EXIT_OK started = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") inputs: list[dict] = [] try: if not (a.machine and a.out): raise Usage("--machine and --out are required") if a.machine == "ym2610": if a.input or a.cycles: raise Usage("ym2610 takes --measure, not --input or --cycles") if a.measure and a.measure[0] not in MEASURES: raise Usage(f"--measure is one of {', '.join(MEASURES)}") exe = BUILD / "lle2610_probe" else: if a.measure or not (a.input and a.cycles) or a.cycles < 1 or a.stride < 1: raise Usage("ym2612 needs --input and --cycles (>= 1), --stride >= 1") exe = BUILD / "lle2612_ref" if not a.input.is_file(): print(f"no such input: {a.input}", file=sys.stderr) return EXIT_MISSING writes = read_writes(a.input) data = a.input.read_bytes() inputs = [{"role": "writes", "sha1": hashlib.sha1(data).hexdigest(), "size": len(data)}] if not exe.exists(): print(f"no {exe}: 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) if a.machine == "ym2610": done = subprocess.run([str(exe), *(a.measure or [])], capture_output=True, check=True) name, fmt, layout = "probe.txt", "ym2608-lle/probe-text", None (a.out / name).write_bytes(done.stdout) records = done.stdout.count(b"\n") patches = ["ym2610-build-fix.patch"] else: with tempfile.TemporaryDirectory(prefix="ym2608-lle-") as scratch: events, out = Path(scratch) / "events.bin", Path(scratch) / "out.bin" events.write_bytes(b"".join(struct.pack("