#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 5: the board's sound against MAME 0.285's recorded output, as a detector. Compares two WAV files over time, not sample by sample (the two machines' clocks, mixes and output filters differ; MAME resamples to 48 kHz): - **level**: the RMS of each 1/60 s window (each window's mean removed), each series scaled by its own median over sounding windows; the lag (within +-1 s) that best correlates the two is found and the Pearson correlation at that lag printed, with the share of windows where both agree on sounding or silent; - **pitch**: the strongest spectral peak (50 Hz-8 kHz, Hann window of 4,096 samples at 48 kHz, hop 1/30 s) where both sound, compared in semitones at the same lag; the share within half a semitone is printed. Verdict "agree" needs level correlation >= 0.90 and pitch within half a semitone in >= 90 % of sounding windows. Seeded faults: ``--fault pitch`` plays the board's file 6 % fast (one semitone), ``--fault level`` replaces its envelope with a constant tone; each must fail. Needs numpy (run with the system Python: ``/usr/bin/python3 -I``). /usr/bin/python3 -I scripts/audio_compare.py board.wav tests/mame_traces/a7800-ballblazu-writes/mame.wav """ from __future__ import annotations import argparse import sys import wave import numpy as np RATE = 48000 def load(path: str) -> np.ndarray: with wave.open(path) as w: rate, channels, width = w.getframerate(), w.getnchannels(), w.getsampwidth() data = np.frombuffer(w.readframes(w.getnframes()), dtype=" np.ndarray: n = len(x) // window blocks = x[: n * window].reshape(n, window) return np.sqrt(((blocks - blocks.mean(axis=1, keepdims=True)) ** 2).mean(axis=1)) def pitches(x: np.ndarray, hop: int, size: int = 8192, keep: int = 3): """Per window: the ``keep`` strongest spectral peaks (Hz, parabolic interpolation) as an array (windows x keep) and the strongest peak's magnitude.""" hann = np.hanning(size) freqs = np.fft.rfftfreq(size, 1 / RATE) band = (freqs >= 50) & (freqs <= 8000) step = freqs[1] out, power = [], [] for start in range(0, len(x) - size, hop): seg = x[start : start + size] s = np.abs(np.fft.rfft((seg - seg.mean()) * hann)) s[~band] = 0 peaks = np.flatnonzero((s[1:-1] > s[:-2]) & (s[1:-1] >= s[2:])) + 1 peaks = peaks[np.argsort(s[peaks])[::-1][:keep]] row = [] for k in peaks: a, b, c = s[k - 1], s[k], s[k + 1] d = 0.5 * (a - c) / (a - 2 * b + c) if a - 2 * b + c else 0.0 row.append((k + d) * step) row += [1.0] * (keep - len(row)) out.append(row) power.append(s[peaks[0]] if len(peaks) else 0.0) return np.array(out), np.array(power) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("board") parser.add_argument("mame") parser.add_argument("--seconds", type=float, default=60.0) parser.add_argument("--skip", type=float, default=3.0, help="seconds of BIOS to leave out") parser.add_argument("--fault", choices=["pitch", "level"]) args = parser.parse_args() ours, theirs = load(args.board), load(args.mame) if args.fault == "pitch": ours = np.interp(np.arange(0, len(ours) / 1.06), np.arange(len(ours)) / 1.06, ours) if args.fault == "level": ours = 1000 * np.sin(np.arange(len(ours)) * 2 * np.pi * 440 / RATE) a, b = int(args.skip * RATE), int((args.skip + args.seconds) * RATE) ours, theirs = ours[a:b], theirs[a:b] window = RATE // 60 lo, lt = levels(ours, window), levels(theirs, window) n = min(len(lo), len(lt)) lo, lt = lo[:n], lt[:n] sound_o, sound_t = lo > 0.02 * lo.max(), lt > 0.02 * lt.max() lo = lo / (np.median(lo[sound_o]) if sound_o.any() else 1) lt = lt / (np.median(lt[sound_t]) if sound_t.any() else 1) best = (-2.0, 0) for lag in range(-60, 61): x = lo[max(0, lag) : n + min(0, lag)] y = lt[max(0, -lag) : n - max(0, lag)] if x.std() > 0 and y.std() > 0: r = float(np.corrcoef(x, y)[0, 1]) best = max(best, (r, lag)) r, lag = best so = sound_o[max(0, lag) : n + min(0, lag)] st = sound_t[max(0, -lag) : n - max(0, lag)] agree_sound = float((so == st).mean()) hop = RATE // 30 po, wo = pitches(ours, hop) pt, wt = pitches(theirs, hop) shift = round(lag * window / hop) m = min(len(po), len(pt)) - abs(shift) po_, pt_ = po[max(0, shift) :][:m], pt[max(0, -shift) :][:m] wo_, wt_ = wo[max(0, shift) :][:m], wt[max(0, -shift) :][:m] both = (wo_ > 0.05 * wo.max()) & (wt_ > 0.05 * wt.max()) if both.any(): po_, pt_ = po_[both], pt_[both] # each side's strongest peak, against the other side's three strongest to_board = np.abs(12 * np.log2(pt_[:, :1] / po_)).min(axis=1) to_mame = np.abs(12 * np.log2(po_[:, :1] / pt_)).min(axis=1) semis = np.maximum(to_board, to_mame) else: semis = np.array([99.0]) within = float((semis <= 0.5).mean()) verdict = "agree" if r >= 0.90 and within >= 0.90 else "DIFFER" print( f"window {args.skip:g}-{args.skip + args.seconds:g} s; best lag {lag * 1000 / 60:+.0f} ms" ) print( f"level: correlation {r:.3f}; sounding/silent agree in {agree_sound:.1%} of " f"{len(so)} windows (board sounds in {so.mean():.1%}, MAME {st.mean():.1%})" ) print( f"pitch: {int(both.sum())} windows where both sound; within half a semitone " f"{within:.1%}; median |difference| {float(np.median(semis)):.2f} semitones" ) print(f"verdict: {verdict}" + (f" (seeded fault {args.fault})" if args.fault else "")) return 0 if verdict == "agree" else 1 if __name__ == "__main__": sys.exit(main())