"""Score BlastEm's own DAC writes against the ROM's sample stream. BlastEm's VGM log (``ui.vgm_log``, bound to ``m``) records every YM2612 register write with a timestamp, so the DAC writes - register $2A, one per sample from ``player/pcm.z80`` - come back exactly as the Z80 made them: the byte values and the time each was issued, with no mixing, filtering or resampling in between. That makes it the right instrument for the chop heard in BlastEm, which megadrive-python's ``verify-clip --audio`` does not reproduce. (The per-channel WAVE log, ``-y``, would have been simpler, but in BlastEm 1.0.1-pre it opens ``ym_channel_*.wav`` and never writes a sample to them; ``-b`` headless segfaults in the same build. Hence the keypress.) What it measures: the driver plays the stream strictly in order, so played byte i should be ``source[i]``. The tool tracks, over the whole run, the lag that best explains what was actually played, and the lag names the fault: lag 0, high match the stream is correct here lag -524288 (-1 page) window 7 still held the previous page: the 68000 opened V_GO before z80_serve_page mapped the page the Z80 asked for, so it read 512 KB back - "the wrong music" lag -32768 (-1 bank) a set_bank that did not take lag small, persistent samples lost or repeated (a ring underrun and the i4 rewind guard): sound and picture drift apart from here lag small, temporary a stall: the right data arrived late Timing is checked separately: one DAC write every 44100/17594 = 2.5065 VGM samples, so a gap is a stall the ring did not cover and a burst is the loop catching up. Usage: 1. run the ROM in BlastEm, press ``m`` at once to start the log 2. let it play to the end, press ``m`` again (or quit) to close it 3. python tools/blastem_audio.py ~/blastem_YYYYmmdd_HHMMSS.vgm out/full """ from __future__ import annotations import argparse from pathlib import Path import numpy as np SAMPLE_RATE = 17594.0 # PAL: MCLK / 3024 VGM_RATE = 44100.0 # the VGM timebase PAGE = 0x80000 # the mapper's 512 KB window 7, one stream byte per sample BANK = 0x8000 # the Z80's 32 KB window into that page DAC_REG = 0x2A def read_vgm(path: Path) -> tuple[np.ndarray, np.ndarray, dict]: """The DAC writes in a VGM log: the byte values and the VGM time of each. Every command is either decoded or skipped by its documented length, so an unexpected one cannot silently desynchronise the parse - it raises instead. """ blob = path.read_bytes() if blob[:4] != b"Vgm ": raise SystemExit(f"{path}: not a VGM file (magic {blob[:4]!r})") version = int.from_bytes(blob[8:12], "little") data_off = int.from_bytes(blob[0x34:0x38], "little") pos = (0x34 + data_off) if version >= 0x150 and data_off else 0x40 fixed = {0x4F: 1, 0x50: 1, 0x51: 2, 0x53: 2, 0x54: 2, 0x55: 2, 0x56: 2, 0x57: 2, 0x58: 2, 0x59: 2, 0x5A: 2, 0x5B: 2, 0x5C: 2, 0x5D: 2, 0x5E: 2, 0x5F: 2, 0xA0: 2, 0xB0: 2, 0xB1: 2, 0xB2: 2, 0xB3: 2, 0xB4: 2, 0xB5: 2, 0xB6: 2, 0xB7: 2, 0xB8: 2, 0xB9: 2, 0xBA: 2, 0xBB: 2, 0xBC: 2, 0xBD: 2, 0xBE: 2, 0xBF: 2, 0xC0: 3, 0xC1: 3, 0xC2: 3, 0xC3: 3, 0xC4: 3, 0xC5: 3, 0xC6: 3, 0xC7: 3, 0xC8: 3, 0xD0: 3, 0xD1: 3, 0xD2: 3, 0xD3: 3, 0xD4: 3, 0xD5: 3, 0xD6: 3, 0xE0: 4, 0xE1: 4} values: list[int] = [] times: list[int] = [] other: dict[int, int] = {} t = 0 while pos < len(blob): cmd = blob[pos] if cmd == 0x52: # YM2612 port 0: the DAC lives here if blob[pos + 1] == DAC_REG: values.append(blob[pos + 2]) times.append(t) else: other[blob[pos + 1]] = other.get(blob[pos + 1], 0) + 1 pos += 3 elif cmd == 0x61: t += int.from_bytes(blob[pos + 1 : pos + 3], "little") pos += 3 elif cmd == 0x62: t += 735 pos += 1 elif cmd == 0x63: t += 882 pos += 1 elif 0x70 <= cmd <= 0x7F: t += (cmd & 0x0F) + 1 pos += 1 elif 0x80 <= cmd <= 0x8F: # DAC write from a data block, then wait t += cmd & 0x0F pos += 1 elif cmd == 0x67: # data block: 0x67 0x66 tt ssssssss pos += 7 + int.from_bytes(blob[pos + 3 : pos + 7], "little") elif cmd == 0x66: break elif cmd == 0x68: # PCM RAM write pos += 12 elif cmd in (0x90, 0x91, 0x92, 0x93, 0x94, 0x95): pos += {0x90: 5, 0x91: 5, 0x92: 6, 0x93: 11, 0x94: 2, 0x95: 5}[cmd] elif cmd in fixed: pos += 1 + fixed[cmd] else: raise SystemExit(f"{path}: unknown VGM command {cmd:#04x} at {pos:#x}") info = {"version": f"{version >> 8:x}.{version & 0xFF:02x}", "other_ym_regs": other, "vgm_seconds": t / VGM_RATE} return np.array(values, dtype=np.uint8), np.array(times, dtype=np.int64), info def best_lag(played: np.ndarray, source: np.ndarray, at: int, near: int) -> tuple[int, float]: """The lag that best explains ``played``, which was due at stream index ``at``. ``near`` is the lag that explained the previous window, tried first with its neighbourhood, then the mapper's own geometry - which is where the faults live. """ n = len(played) candidates = {0, near} candidates.update(near + k for k in range(-16, 17)) for unit in (BANK, PAGE): for k in (-3, -2, -1, 1, 2, 3): candidates.add(k * unit) candidates.add(near + k * unit) best, best_frac = 0, -1.0 for lag in candidates: start = at + lag if start < 0 or start + n > len(source): continue frac = float(np.count_nonzero(source[start : start + n] == played)) / n if frac > best_frac: best, best_frac = lag, frac return best, best_frac def search_lag(played: np.ndarray, source: np.ndarray, at: int) -> tuple[int, float]: """Matched filter over the whole stream, for a window no local lag explains.""" from scipy.signal import fftconvolve q = played.astype(np.float64) - played.mean() if not np.any(q): return 0, 0.0 corr = fftconvolve(source.astype(np.float64) - 128.0, q[::-1], mode="valid") found = int(np.argmax(corr)) n = len(played) frac = float(np.count_nonzero(source[found : found + n] == played)) / n if found + n <= len(source) else 0.0 return found - at, frac def find_base(dac: np.ndarray, source: np.ndarray, window: int) -> tuple[int, int, int]: """The stream sample the log begins at, by consensus over probe windows. The log is toggled by hand, often on hearing a fault, so its first window may be the faulty one - locating the log from that window alone would anchor the whole run to wherever the fault read from. Several windows spread through the log are each placed in the stream independently; a fault moves a minority of them, so the most-voted start is the right one. Returns (start, votes agreeing, votes cast). """ span = max(0, len(dac) - window) tally: dict[int, list[float]] = {} cast = 0 for frac_of in (0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95): off = int(frac_of * span) played = dac[off : off + window] if len(played) < window or played.min() == played.max(): continue cast += 1 found, frac = search_lag(played, source, 0) if frac > 0.5: vote = tally.setdefault(found - off, [0.0, 0.0]) vote[0] += 1 vote[1] += frac if not tally: return 0, 0, cast best = max(tally, key=lambda k: (tally[k][0], tally[k][1])) return max(0, best), int(tally[best][0]), cast def lag_timeline(dac: np.ndarray, source: np.ndarray, base: int, window: int, clean: float, search: bool) -> list[tuple[int, int, int, float]]: """Coarse (start, end, lag, worst match) segments over the played sequence. Windows merge only when they agree on the lag *and* on whether they are clean, and a segment keeps its worst window's match rather than an average: a fault lasting a fraction of a window still shows, instead of being diluted by its clean neighbours. ``base`` is the stream sample the log begins at, and the whole stream is searched from it rather than a slice of it: a log started by hand in the middle of the song must still be able to match a page *behind* its own first sample, which is exactly where a stale window 7 reads from. """ segments: list[tuple[int, int, int, float]] = [] near = 0 for start in range(0, len(dac) - window + 1, window): played = dac[start : start + window] lag, frac = best_lag(played, source, base + start, near) if frac < 0.75 and search: lag2, frac2 = search_lag(played, source, base + start) if frac2 > frac: lag, frac = lag2, frac2 near = lag ok = lag == 0 and frac >= clean if segments: s0, _, l0, f0 = segments[-1] if l0 == lag and (l0 == 0 and f0 >= clean) == ok: segments[-1] = (s0, start + window, l0, min(f0, frac)) continue segments.append((start, start + window, lag, frac)) return segments def faults(dac: np.ndarray, source: np.ndarray, base: int, segments: list[tuple[int, int, int, float]], clean: float, min_run: int, merge_gap: int, window: int) -> list[tuple[int, int, int, float]]: """Exact faults, each with the lag that explains the audio actually played. Two kinds, because the lag timeline works on whole windows: A segment the timeline gave a non-zero lag *is* a fault for its whole length - the lag explains the data, which is precisely the problem - so it is reported entire, with ``refine`` pinning the sample where the source changed rather than the window grid. A fault shorter than one window instead leaves a lag-0 segment with a poor match; that one is rescanned byte by byte, the mismatching runs pulled out (runs separated by fewer than ``merge_gap`` matching bytes count as one, since a wrong-source read still hits the odd right value by chance) and each attributed on its own. That turns "this 233 ms window is 85 % right" into "600 samples here came from one bank back". """ out: list[tuple[int, int, int, float]] = [] for s0, e0, lag, frac in segments: if lag == 0 and frac >= clean: continue if lag != 0: start = refine(dac, source, base, s0, 0, lag, window) out.append((start, e0 - start, lag, frac)) continue lo, hi = base + s0 + lag, base + e0 + lag if lo < 0 or hi > len(source): out.append((s0, e0 - s0, lag, frac)) continue bad = dac[s0:e0] != source[lo:hi] if not bad.any(): continue edges = np.flatnonzero(np.diff(np.concatenate([[False], bad, [False]]).astype(np.int8))) runs = [(int(a), int(b)) for a, b in zip(edges[::2], edges[1::2])] merged: list[list[int]] = [] for a, b in runs: if merged and a - merged[-1][1] < merge_gap: merged[-1][1] = b else: merged.append([a, b]) for a, b in merged: if b - a < min_run: continue run = dac[s0 + a : s0 + b] run_lag, run_frac = best_lag(run, source, base + s0 + a, lag) out.append((s0 + a, b - a, run_lag, run_frac)) # One fault that straddles a window boundary arrives as two touching segments with # the same lag; report it as the single event it was. out.sort() joined: list[list] = [] for s0, n, lag, frac in out: if joined and joined[-1][2] == lag and s0 - (joined[-1][0] + joined[-1][1]) <= min_run: joined[-1][1] = s0 + n - joined[-1][0] joined[-1][3] = min(joined[-1][3], frac) else: joined.append([s0, n, lag, frac]) return [(s0, n, lag, frac) for s0, n, lag, frac in joined] def refine(dac: np.ndarray, source: np.ndarray, base: int, at: int, lag_before: int, lag_after: int, window: int) -> int: """The played index where the lag changes, inside a one-window bracket. Both lags are scored on a short run either side of each candidate, so the boundary lands where the data stops matching the old source and starts matching the new one rather than on the window grid. """ run = 64 lo, hi = max(run, at - window), min(len(dac) - run, at + window) best, best_score = at, -1 def hits(i: int, lag: int) -> int: s = base + i + lag if s < 0 or s + run > len(source): return -1 return int(np.count_nonzero(source[s : s + run] == dac[i : i + run])) for i in range(lo, hi, 8): score = hits(i - run, lag_before) + hits(i, lag_after) if score > best_score: best, best_score = i, score return best def place(sample: int, audio_page: int) -> str: """Where a stream position sits in the ROM's mapper geometry.""" page, within = divmod(sample, PAGE) bank, offset = divmod(within, BANK) return f"ROM {(audio_page + page) * PAGE + within:#09x} page {audio_page + page} bank {bank:2d} +{offset:5d}" def describe(lag: int) -> str: if lag == 0: return "correct data, low match" for unit, name in ((PAGE, "page"), (BANK, "bank")): if lag % unit == 0: return f"{lag // unit:+d} {name} ({lag:+,})" return f"{lag:+,} samples" def report(vgm: Path, out: Path, audio_page: int, window: int, top: int, clean: float, min_run: int, merge_gap: int, search: bool) -> int: source = np.frombuffer((out / "audio.u8").read_bytes(), dtype=np.uint8) dac, times, info = read_vgm(vgm) print(f"{vgm.name}: VGM {info['version']}, {info['vgm_seconds']:.1f} s logged, " f"{len(dac):,} DAC writes ({len(dac) / SAMPLE_RATE:.1f} s of stream)") if info["other_ym_regs"]: print(" other YM port-0 writes: " + " ".join(f"{r:#04x}x{c}" for r, c in sorted(info["other_ym_regs"].items()))) print(f"stream: {len(source):,} samples ({len(source) / SAMPLE_RATE:.1f} s)") if not len(dac): raise SystemExit("no DAC writes in the log - was it started before the ROM played?") base, agree, votes = find_base(dac, source, window) if base: print(f"log starts at stream sample {base:,} ({base / SAMPLE_RATE:.2f} s), " f"agreed by {agree} of {votes} probe windows") segments = lag_timeline(dac, source, base, window, clean, search) wrong = [s for s in segments if s[2] != 0 or s[3] < clean] total = sum(e - s for s, e, _, _ in wrong) print(f"\nlag timeline: {len(segments)} segments, {len(wrong)} not clean, " f"{total:,} samples ({1000 * total / SAMPLE_RATE:.0f} ms, " f"{100 * total / max(1, len(dac)):.2f}% of the run) played from the wrong place") if not wrong: print("every window played the right data in the right order: PASS") else: wrong = faults(dac, source, base, segments, clean, min_run, merge_gap, window) bad = sum(n for _, n, _, _ in wrong) print(f"{len(wrong)} exact faults, {bad:,} samples ({1000 * bad / SAMPLE_RATE:.0f} ms) of wrong data") print(f"\n{'start':>11} {'length':>9} {'came from':>22} match where it started") for s0, n, lag, f in sorted(wrong, key=lambda r: -r[1])[:top]: print(f" {(base + s0) / SAMPLE_RATE:9.3f}s {1000 * n / SAMPLE_RATE:7.1f}ms " f"{describe(lag):>22} {100 * f:3.0f}% {place(base + s0, audio_page)}") # Do the faults sit on the mapper's boundaries? That is the page-serve race's # signature. A page boundary is also a bank boundary, so each fault is counted # once, against the coarser window it falls in. on_page = [r for r in wrong if (base + r[0]) % PAGE < PAGE // 16] on_bank = [r for r in wrong if r not in on_page and (base + r[0]) % BANK < BANK // 16] for name, on, unit in (("page", on_page, PAGE), ("bank", on_bank, BANK)): if on: print(f"\n{len(on)} of the {len(wrong)} faults start within the first {unit // 16:,} " f"samples ({1000 * (unit // 16) / SAMPLE_RATE:.0f} ms) of a {name}; " f"the stream crosses {len(source) // unit} {name} boundaries") # Timing: one write per 2.5065 VGM samples; a gap is a stall the ring did not cover. if len(times) > 1: gaps = np.diff(times) nominal = VGM_RATE / SAMPLE_RATE stalls = np.flatnonzero(gaps > 4 * nominal) print(f"\ntiming: median {np.median(gaps):.2f} VGM samples between writes " f"(nominal {nominal:.4f}); {len(stalls):,} gaps over 4 samples") if len(stalls): for i in sorted(stalls[np.argsort(-gaps[stalls])][:top]): print(f" {(base + i) / SAMPLE_RATE:9.3f}s {1000 * gaps[i] / VGM_RATE:7.2f}ms " f"{place(base + int(i), audio_page)}") return 1 if wrong else 0 def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("vgm", type=Path, help="BlastEm's VGM log (press m in the emulator)") ap.add_argument("out", type=Path, help="the build directory holding audio.u8") ap.add_argument("--audio-page", type=int, default=21, help="512 KB page the stream starts on (build-stream prints it as AUDIO_PAGE)") ap.add_argument("--window", type=int, default=4096, help="samples per lag window (default 4096 = 233 ms)") ap.add_argument("--top", type=int, default=25, help="how many faults to list") ap.add_argument("--clean", type=float, default=0.9, help="match fraction at or above which a lag-0 window counts as clean") ap.add_argument("--min-run", type=int, default=8, help="shortest run of wrong samples to report as a fault (default 8)") ap.add_argument("--merge-gap", type=int, default=16, help="matching samples that may sit inside one fault (default 16)") ap.add_argument("--no-search", action="store_true", help="skip the whole-stream matched filter") args = ap.parse_args(argv) return report(args.vgm, args.out, args.audio_page, args.window, args.top, args.clean, args.min_run, args.merge_gap, not args.no_search) if __name__ == "__main__": raise SystemExit(main())