#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Compare the board's sound with a referee's (scripts/referee.py --wav): find the time offset between them, then say how alike they are. CPython with numpy (a measuring tool, not part of the board). The two runs reach each sound at different times (drive timing, boot speed), and the two emulators filter and scale their output differently, so: 1. both are made mono and brought to ``--rate`` (linear interpolation); 2. the loudness envelope (RMS over 10 ms) of a stretch of the board's sound is slid along the referee's to find the offset where they agree best (normalised correlation of the envelopes): the **envelope correlation**; 3. at that offset, refined to the sample, the waveforms are compared one second at a time (Pearson's r over each second where the board is sounding, each second allowed to sit up to 10 ms off the first so a slow drift between the two clocks does not count): the **waveform correlation**, as the median over those seconds and the share above 0.9, and the **drift**, how far the seconds had to move. A level difference does not lower either number (both are normalised); a different filter lowers the waveform number a little; a wrong pitch, a missing channel or a sample out of place lowers it a lot. A detector's number, not a judge's (docs/validation.md): the referee is an emulator. python3 scripts/compare_audio.py BOARD.wav REFEREE.wav [--from 30 --to 60] [--search 20] """ from __future__ import annotations import argparse import sys import wave from pathlib import Path import numpy as np def read(path: Path, rate: int) -> np.ndarray: with wave.open(str(path)) as file: channels, width, source_rate = file.getnchannels(), file.getsampwidth(), file.getframerate() data = np.frombuffer(file.readframes(file.getnframes()), dtype=" np.ndarray: n = len(signal) // block return np.sqrt((signal[: n * block].reshape(n, block) ** 2).mean(axis=1)) def normalised(a: np.ndarray, b: np.ndarray) -> float: a = a - a.mean() b = b - b.mean() scale = np.sqrt((a * a).sum() * (b * b).sum()) return float((a * b).sum() / scale) if scale else 0.0 def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("board", type=Path) parser.add_argument("referee", type=Path) parser.add_argument("--rate", type=int, default=11_025) parser.add_argument("--from", dest="start", type=float, default=0.0, help="board seconds") parser.add_argument("--to", dest="stop", type=float, default=None, help="board seconds") parser.add_argument("--search", type=float, default=20.0, help="offsets tried, seconds") args = parser.parse_args() rate = args.rate board, referee = read(args.board, rate), read(args.referee, rate) first = int(args.start * rate) last = int(args.stop * rate) if args.stop is not None else len(board) piece = board[first:last] block = rate // 100 env_piece, env_ref = envelope(piece, block), envelope(referee, block) reach = int(args.search * 100) best = (-2.0, 0) base = first // block for shift in range(-reach, reach + 1): at = base + shift if at < 0 or at + len(env_piece) > len(env_ref): continue r = normalised(env_piece, env_ref[at : at + len(env_piece)]) if r > best[0]: best = (r, shift) env_r, shift = best if env_r < -1: sys.exit("no offset fits inside the referee's recording") # Refine to the sample, within one block either way. coarse = first + shift * block fine = (-2.0, coarse) probe = piece[: min(len(piece), rate * 5)] for at in range(coarse - block, coarse + block + 1): if at < 0 or at + len(probe) > len(referee): continue r = normalised(probe, referee[at : at + len(probe)]) if r > fine[0]: fine = (r, at) at = fine[1] seconds = [] lags = [] slack = rate // 100 # each second may sit up to 10 ms off the first (drift) for s in range(0, len(piece) - rate + 1, rate): a = piece[s : s + rate] if a.std() < 50: continue # silence says nothing scores = [] for lag in range(-slack, slack + 1): b = referee[at + s + lag : at + s + lag + rate] if len(b) < rate or at + s + lag < 0 or b.std() < 50: continue scores.append((normalised(a, b), lag)) if scores: r, lag = max(scores) seconds.append(r) lags.append(lag) offset = (at - first) / rate print(f"offset: the referee is {offset:+.3f} s from the board") print(f"envelope correlation: {env_r:.3f}") if seconds: median = float(np.median(seconds)) share = sum(1 for r in seconds if r > 0.9) / len(seconds) print(f"waveform correlation: median {median:.3f} over {len(seconds)} sounding seconds; " f"{share:.0%} above 0.9") # fmt: skip print(f"drift: each second re-aligned by {min(lags) / rate * 1000:+.1f} to " f"{max(lags) / rate * 1000:+.1f} ms (first {lags[0] / rate * 1000:+.1f}, last " f"{lags[-1] / rate * 1000:+.1f})") # fmt: skip else: print("waveform correlation: no second where both sound") return 0 if __name__ == "__main__": sys.exit(main())