"""Pull the DAC stream out of megadrive-rust-fast's YM2612 write log. ``md-run --ym-log FILE`` records every YM2612 write as 10 little-endian bytes: an i64 master clock, the port (0-3) and the value. The DAC samples are the writes to port 1 made while port 0 has register $2A latched, which is how player/pcm.z80 feeds it. This writes the same two files tools/dump_dac.py produces from megadrive-python, so tools/oracle_audio.py scores either without knowing which emulator produced it - the difference being 32 seconds against about 70 minutes for a full song. md-run ROM --machine megadrive2 --frames 10565 --ym-log out/ym.log python tools/ym_log.py out/ym.log out/dac_rust python tools/oracle_audio.py out/dac_rust.u8 out/full """ from __future__ import annotations import argparse from pathlib import Path import numpy as np RECORD = np.dtype([("mclk", " tuple[np.ndarray, np.ndarray, dict]: """The DAC bytes and their master clocks, plus what else the log contained.""" blob = log.read_bytes() if len(blob) % RECORD.itemsize: raise SystemExit(f"{log}: {len(blob)} bytes is not a whole number of 10-byte records") rec = np.frombuffer(blob, dtype=RECORD) port, value = rec["port"], rec["value"] # The latched register is the most recent port-0 value before each record: carry # the index of that write forward, then read its value. is_addr = port == 0 idx = np.where(is_addr, np.arange(len(rec)), -1) last_addr = np.maximum.accumulate(idx) latched = np.where(last_addr >= 0, value[np.maximum(last_addr, 0)], 0xFF) dac = (port == 1) & (latched == DAC_REG) others: dict[int, int] = {} for reg, count in zip(*np.unique(value[is_addr], return_counts=True)): if int(reg) != DAC_REG: others[int(reg)] = int(count) info = {"records": len(rec), "dac_writes": int(dac.sum()), "address_writes": int(is_addr.sum()), "other_registers": others} # fmt: skip return value[dac].copy(), rec["mclk"][dac].copy(), info def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("log", type=Path, help="the file md-run --ym-log wrote") ap.add_argument("out", type=Path, help="prefix: writes OUT.u8 and OUT.mclk") args = ap.parse_args(argv) values, times, info = dac_stream(args.log) print(f"{args.log.name}: {info['records']:,} YM writes, {info['address_writes']:,} address " f"latches, {info['dac_writes']:,} DAC samples") regs = sorted(info["other_registers"].items(), key=lambda kv: -kv[1])[:8] print(" other registers latched: " + " ".join(f"{r:#04x}x{c:,}" for r, c in regs)) if not len(values): raise SystemExit("no DAC writes: was the driver running?") args.out.parent.mkdir(parents=True, exist_ok=True) args.out.with_suffix(".u8").write_bytes(values.tobytes()) args.out.with_suffix(".mclk").write_bytes(times.astype("