"""Track the audio stream's position through a rendered WAV, over a whole song. tools/oracle_audio.py and tools/blastem_audio.py compare the DAC bytes the driver wrote, which is exact but needs a capture at register level: megadrive-python's FM hook (about 70 minutes for the full song) or a BlastEm VGM log (a keypress and real time). megadrive-rust-fast renders the whole song to a WAV in 19 seconds, but through the mixer - scaled, filtered, resampled - so the values cannot be compared byte for byte. What survives that is *position*. Asking for the WAV at the DAC's own rate (17,594 Hz) puts its samples roughly one-to-one with the stream, so a window of it can be located in the source by correlation, and the lag that locates it names the same faults the exact tools name: lag 0 the stream is playing from the right place here lag -524288 a stale 512 KB page: the window 7 fault this project had lag -32768 a stale 32 KB bank lag drifting samples lost or inserted What it CANNOT see is a fault smaller than the noise floor of a correlation window: the six-sample splice that the exact tools found at each page crossing is invisible here. So this is the cheap check that covers a whole song's worth of crossings for the gross failure mode, not a replacement for the byte-exact one. md-run ROM --machine megadrive2 --frames 10565 --wav out/full/rust.wav --rate 17594 python tools/wav_audio.py out/full/rust.wav out/full """ from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) from blastem_audio import BANK, PAGE, SAMPLE_RATE, describe, place # noqa: E402 SAMPLE_RATE_TRUE = 53_203_424 / 3024 # the DAC's real rate: MCLK / 3024 = 17,593.73 Hz def read_wav(path: Path) -> tuple[np.ndarray, int]: """One mono float channel and the sample rate, from a 16-bit PCM WAVE file.""" blob = path.read_bytes() if blob[:4] != b"RIFF" or blob[8:12] != b"WAVE": raise SystemExit(f"{path}: not a RIFF/WAVE file") pos, rate, channels, bits, data = 12, 0, 0, 0, None while pos + 8 <= len(blob): tag = blob[pos : pos + 4] size = int.from_bytes(blob[pos + 4 : pos + 8], "little") body = pos + 8 if tag == b"fmt ": channels = int.from_bytes(blob[body + 2 : body + 4], "little") rate = int.from_bytes(blob[body + 4 : body + 8], "little") bits = int.from_bytes(blob[body + 14 : body + 16], "little") elif tag == b"data": size = min(size, len(blob) - body) or (len(blob) - body) data = blob[body : body + (size - size % (2 * max(channels, 1)))] break pos = body + size + (size & 1) if data is None or bits != 16 or channels < 1: raise SystemExit(f"{path}: need 16-bit PCM, got {bits} bit / {channels} ch") samples = np.frombuffer(data, dtype=" 1: samples = samples.reshape(-1, channels).mean(axis=1) return samples, rate def correlate_at(window: np.ndarray, source: np.ndarray, at: int) -> float: """Normalised correlation of ``window`` against the source starting at ``at``.""" n = len(window) if at < 0 or at + n > len(source): return -1.0 seg = source[at : at + n] sd = seg.std() if sd < 1e-9: return -1.0 return float(np.dot(window, seg) / (n * window.std() * sd)) def find_start(played: np.ndarray, source: np.ndarray, window: int, limit: int) -> tuple[int, float]: """Where in the WAV the stream begins, to the sample. The ROM boots, clears VRAM and primes the Z80's ring before the first sample, so the WAV opens with a lead-in that is not in the stream at all. This has to be found *exactly*: a coarse search that lands even a few hundred samples out leaves every later window misaligned, every correlation low, and the whole report meaningless - which is exactly what a step-of-2048 search did here before it was replaced. """ from scipy.signal import fftconvolve loud = np.flatnonzero(np.abs(played) > 0.01 * np.abs(played).max()) first = int(loud[0]) if len(loud) else 0 probe = played[first : first + window] probe = probe - probe.mean() hay = source[: min(len(source), limit + window)] hay = hay - hay.mean() if len(probe) < window or len(hay) <= len(probe): return first, 0.0 corr = fftconvolve(hay, probe[::-1], mode="valid") at = int(np.argmax(corr)) seg = hay[at : at + len(probe)] den = float(np.sqrt(np.sum(probe * probe) * np.sum(seg * seg))) return first - at, (float(np.dot(probe, seg)) / den if den else 0.0) def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("wav", type=Path) ap.add_argument("out", type=Path, help="build directory holding audio.u8") ap.add_argument("--window", type=int, default=8192, help="samples per window (default 8192 = 0.47 s)") ap.add_argument("--audio-page", type=int, default=21) ap.add_argument("--min-correlation", type=float, default=0.85) ap.add_argument("--tolerance", type=int, default=2, help="residual lag in samples still counted as clean (default 2)") # fmt: skip args = ap.parse_args(argv) played, rate = read_wav(args.wav) source = np.frombuffer((args.out / "audio.u8").read_bytes(), dtype=np.uint8).astype(np.float64) - 128.0 print(f"{args.wav.name}: {len(played):,} samples at {rate} Hz ({len(played) / rate:.1f} s)") print(f"stream: {len(source):,} samples ({len(source) / SAMPLE_RATE:.1f} s)") if abs(rate - SAMPLE_RATE) > 0.02 * SAMPLE_RATE: print(f"warning: {rate} Hz is not the DAC rate ({SAMPLE_RATE:.0f}); windows will not be 1:1") w = args.window lead, c0 = find_start(played, source, w, 24 * int(SAMPLE_RATE)) print(f"stream starts {lead:,} samples into the WAV (correlation {c0:.3f})") if c0 < 0.8: print(" alignment is poor: every lag below is suspect, not a finding") played = played[lead:] candidates = [0, 1, -1, 2, -2, 4, -4, 8, -8, 16, -16, 32, -32, 64, -64, 128, -128] structural = [k * u for u in (BANK, PAGE) for k in (-2, -1, 1, 2)] segments: list[tuple[int, int, int, float]] = [] near = 0 for start in range(0, len(played) - w + 1, w): window = played[start : start + w] if window.std() < 1e-9: continue best_lag, best_c = near, correlate_at(window, source, start + near) for lag in {near + d for d in candidates} | {near + s for s in structural} | set(structural): c = correlate_at(window, source, start + lag) if c > best_c: best_lag, best_c = lag, c near = best_lag if segments and segments[-1][2] == best_lag: s0, _, l0, c_min = segments[-1] segments[-1] = (s0, start + w, l0, min(c_min, best_c)) else: segments.append((start, start + w, best_lag, best_c)) # The WAV is rendered at an integer rate, and the DAC's real rate is not an # integer: MCLK / 3024 = 17,593.73 Hz, so asking for 17,594 builds in 0.27 # samples per second of drift - about 57 samples over this song, which looks # exactly like a fault at every page crossing and is not one. Fit the straight # line through lag against time and judge the residual, reporting the slope so a # rate mismatch is visible as a rate mismatch rather than as seven faults. if len(segments) > 4: mid = np.array([(s0 + e0) / 2 for s0, e0, _, _ in segments], float) lag = np.array([l for _, _, l, _ in segments], float) slope, intercept = np.polyfit(mid, lag, 1) drift_per_s = slope * SAMPLE_RATE implied = SAMPLE_RATE_TRUE * (1 + slope) print() print(f"lag drifts {drift_per_s:+.3f} samples per second over the run") print(f" a WAV rendered at {rate} Hz against a DAC at {SAMPLE_RATE_TRUE:.2f} Hz " f"predicts {rate - SAMPLE_RATE_TRUE:+.2f} Hz = {rate - SAMPLE_RATE_TRUE:+.3f} samples/s") print(f" so the render's effective rate is about {implied:.2f} Hz") residual = lag - (slope * mid + intercept) segments = [(s0, e0, int(round(r)), c) for (s0, e0, _, c), r in zip(segments, residual)] print(" lags below are residuals after removing that line") bad = [s for s in segments if abs(s[2]) > args.tolerance or s[3] < args.min_correlation] total = sum(e - s for s, e, _, _ in bad) print(f"\n{len(segments)} segments; {len(bad)} not clean, {total:,} samples " f"({total / SAMPLE_RATE:.2f} s, {100 * total / max(1, len(played)):.2f}% of the run)") if not bad: print("the stream played from the right place for the whole song: PASS") else: print(f"\n{'start':>11} {'length':>9} {'came from':>22} corr where") for s0, e0, lag, c in sorted(bad, key=lambda r: -(r[1] - r[0]))[:20]: print(f" {s0 / SAMPLE_RATE:9.3f}s {(e0 - s0) / SAMPLE_RATE:8.2f}s {describe(lag):>22} " f"{c:5.3f} {place(s0, args.audio_page)}") # The crossings this project's fix is about, checked one by one. print(f"\nthe {len(source) // PAGE} page crossings, where the stale-window fault lived:") for k in range(1, len(source) // PAGE + 1): at = k * PAGE seg = next((s for s in segments if s[0] <= at < s[1]), None) if seg is None: print(f" {at / SAMPLE_RATE:8.3f}s (beyond the capture)") else: verdict = "clean" if seg[2] == 0 and seg[3] >= args.min_correlation else f"FAULT {describe(seg[2])}" print(f" {at / SAMPLE_RATE:8.3f}s lag {seg[2]:+9,} corr {seg[3]:5.3f} {verdict}") return 1 if bad else 0 if __name__ == "__main__": raise SystemExit(main())