# SPDX-License-Identifier: MIT """Milestone 4 audio: the board's sound against Atari800's (a detector) and the POKEY registers. Not a sample comparison: two emulators' audio paths differ (filters, mixing curves, sample rates). What is compared, per video frame (1/59.92 s): - the level (RMS after removing the frame's mean), as an envelope over time; - the dominant pitch (autocorrelation peak between 40 Hz and 4 kHz); - what the game wrote to POKEY (``scripts/scripted_run.py --pokey-log``): for each channel with a non-zero volume and a pure-tone setting (AUDC bits 5-7 = %101 or %111), the frequency the registers ask for, from the POKEY data sheet's divider rule ([DS-P], tier 2): F_in / (2 (N + 1)) with F_in = 63.9 kHz or 15.7 kHz (AUDCTL bit 0), F_in / (2 (N + 4)) for a channel clocked at 1.79 MHz (AUDCTL bits 6/5 for channels 1/3), and the joined 16-bit forms with + 7 at 1.79 MHz (bits 4/3). The two runs are aligned by the lag (within +/- 120 frames) that best correlates their level envelopes, since boot and game start can differ by some frames between the emulators. python scripts/audio_compare.py BOARD.wav ATARI800.wav --pokey-log LOG [--from F --to F] """ from __future__ import annotations import argparse import math from pathlib import Path CYCLE_HZ = 3_579_575 / 2 # the board's machine clock ([FSM] crystal, C2) FRAME_HZ = CYCLE_HZ / 29_868 def read_wav(path: Path) -> tuple[list[float], int]: data = path.read_bytes() if data[:4] != b"RIFF" or data[8:12] != b"WAVE": raise ValueError(f"{path}: not a WAV file") pos = 12 fmt = None samples = b"" while pos + 8 <= len(data): tag = data[pos : pos + 4] size = int.from_bytes(data[pos + 4 : pos + 8], "little") body = data[pos + 8 : pos + 8 + size] if tag == b"fmt ": fmt = body elif tag == b"data": samples = body pos += 8 + size + (size & 1) if fmt is None: raise ValueError(f"{path}: no fmt chunk") channels = int.from_bytes(fmt[2:4], "little") rate = int.from_bytes(fmt[4:8], "little") bits = int.from_bytes(fmt[14:16], "little") step = bits // 8 * channels out = [] for i in range(0, len(samples) - step + 1, step): if bits == 8: out.append((samples[i] - 128) / 128) else: out.append(int.from_bytes(samples[i : i + 2], "little", signed=True) / 32768) return out, rate def frames_of(samples: list[float], rate: int) -> list[tuple[float, float]]: """(level, pitch in Hz or 0) per video frame.""" per = rate / FRAME_HZ out = [] n = 0 while int((n + 1) * per) <= len(samples): window = samples[int(n * per) : int((n + 1) * per)] mean = sum(window) / len(window) centred = [s - mean for s in window] level = math.sqrt(sum(s * s for s in centred) / len(centred)) out.append((level, pitch(centred, rate) if level > 0.002 else 0.0)) n += 1 return out def pitch(window: list[float], rate: int) -> float: lo = max(2, int(rate / 4000)) hi = min(len(window) // 2, int(rate / 40)) energy = sum(s * s for s in window) if energy == 0: return 0.0 best, best_lag = 0.0, 0 for lag in range(lo, hi): r = sum(window[i] * window[i + lag] for i in range(len(window) - lag)) r /= energy * (len(window) - lag) / len(window) if r > best: best, best_lag = r, lag return rate / best_lag if best > 0.5 else 0.0 def register_tones(log: Path, frames: int) -> list[list[float]]: """Per frame, the pure-tone frequencies the registers ask for (after that frame's writes).""" audf = [0] * 4 audc = [0] * 4 audctl = 0 writes: dict[int, list[tuple[int, int]]] = {} for line in log.read_text(encoding="utf-8").split("\n"): if line.strip(): frame, _cycle, reg, value = (int(x) for x in line.split()) writes.setdefault(frame, []).append((reg, value)) out = [] for frame in range(frames): for reg, value in writes.get(frame, []): if reg == 8: audctl = value elif reg % 2 == 0: audf[reg // 2] = value else: audc[reg // 2] = value base = 15_700.0 if audctl & 1 else 63_921.0 tones = [] for ch in range(4): if audc[ch] & 0x0F == 0 or audc[ch] & 0x10 or (audc[ch] >> 5) not in (5, 7): continue if (ch == 0 and audctl & 0x10) or (ch == 2 and audctl & 0x08): continue # the low half of a joined pair makes no tone of its own fast = (ch == 0 and audctl & 0x40) or (ch == 2 and audctl & 0x20) joined = (ch == 1 and audctl & 0x10) or (ch == 3 and audctl & 0x08) if joined: n = audf[ch] * 256 + audf[ch - 1] fast = (ch == 1 and audctl & 0x40) or (ch == 3 and audctl & 0x20) divisor = n + (7 if fast else 1) else: divisor = audf[ch] + (4 if fast else 1) tones.append((CYCLE_HZ if fast else base) / (2 * divisor)) out.append(tones) return out def best_lag(a: list[float], b: list[float], span: int = 120) -> tuple[int, float]: """The lag of b against a that best correlates the two envelopes, and that correlation.""" def corr(lag: int) -> float: pairs = [(a[i], b[i + lag]) for i in range(len(a)) if 0 <= i + lag < len(b)] if len(pairs) < 60: return -1.0 ma = sum(p[0] for p in pairs) / len(pairs) mb = sum(p[1] for p in pairs) / len(pairs) num = sum((x - ma) * (y - mb) for x, y in pairs) den = math.sqrt(sum((x - ma) ** 2 for x, _ in pairs) * sum((y - mb) ** 2 for _, y in pairs)) return num / den if den else -1.0 lag = max(range(-span, span + 1), key=corr) return lag, corr(lag) def close(f: float, g: float, tolerance: float = 0.04) -> bool: """Equal within the tolerance, or an octave apart (autocorrelation can lock on either).""" if not f or not g: return False return any(abs(f * k - g) <= tolerance * g for k in (0.5, 1, 2)) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("board", type=Path) parser.add_argument("atari800", type=Path) parser.add_argument("--pokey-log", type=Path) parser.add_argument("--from", dest="start", type=int, default=0, help="first board frame") parser.add_argument("--to", dest="stop", type=int, help="last board frame") parser.add_argument("--table", type=int, default=0, help="print every Nth frame") args = parser.parse_args() ours = frames_of(*read_wav(args.board)) theirs = frames_of(*read_wav(args.atari800)) stop = min(args.stop or len(ours), len(ours)) a = [lv for lv, _ in ours] b = [lv for lv, _ in theirs] lag, r = best_lag(a[args.start : stop], b[args.start :]) if stop > args.start else (0, 0.0) tones = register_tones(args.pokey_log, len(ours)) if args.pokey_log else None sounding = both = pitch_ok = reg_ok = reg_n = a800_reg_ok = 0 peak_a = max(a[args.start : stop] or [0]) or 1 peak_b = max(b or [0]) or 1 for f in range(args.start, stop): g = f + lag la, pa = ours[f] lb, pb = theirs[g] if 0 <= g < len(theirs) else (0.0, 0.0) on_a = la > 0.05 * peak_a on_b = lb > 0.05 * peak_b sounding += on_a or on_b both += on_a and on_b if on_a and on_b and pa and pb: pitch_ok += close(pa, pb) expected = tones[f] if tones else [] if expected and pa: reg_n += 1 reg_ok += any(close(pa, t) for t in expected) a800_reg_ok += any(close(pb, t) for t in expected) if pb else 0 if args.table and f % args.table == 0: exp = ",".join(f"{t:.0f}" for t in expected) print( f"{f:5d} board {la / peak_a:5.2f} {pa:7.1f} Hz | a800 {lb / peak_b:5.2f} {pb:7.1f} Hz | regs {exp}" ) pitched = sum( 1 for f in range(args.start, stop) if ours[f][1] and 0 <= f + lag < len(theirs) and theirs[f + lag][1] ) print(f"frames {args.start}-{stop}: Atari800 lag {lag:+d} frames, level envelopes r = {r:.3f}") print(f"sounding (either side above 5 % of its peak): {sounding}; on both sides: {both}") print(f"pitch agrees (4 %, octave-tolerant) on {pitch_ok} of {pitched} frames pitched on both") if tones is not None: print( f"board pitch matches a register tone on {reg_ok} of {reg_n} frames with a pure tone set" ) print(f"Atari800 pitch matches the board's register tone on {a800_reg_ok} of those frames") return 0 if __name__ == "__main__": raise SystemExit(main())