#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Compare the board's sound with the detectors' (milestone 5): 16-bit stereo WAVs. Every program here gives each emulator its own level and its own DC (docs/claims.md: the PWM level rests on nothing), so nothing is compared sample for sample. Two reports: ``segments`` (the Mars Check Program's sound tests: one tone per test): the stretches where either side sounds, in order; per stretch its length, which outputs sound (each side's AC level against the louder side's), the tone's frequency from its rising zero crossings (interpolated, over the whole stretch, so a 0.2 % difference -- cycle against cycle - 1 -- shows), and one period's shape folded over the stretch, normalised, as a correlation with the first file's. ``window`` (a sample program or a game): one stretch of the first file against each other file, aligned by their envelopes, then compared in 50 ms windows each re-aligned within 7 ms, since no two emulators keep the same time base to a fraction of a per cent: per side the windows' median and tenth-percentile correlation, the lag's drift (ppm), the level ratio (RMS), and the spectra's correlation in third-octave bands. python3 scripts/compare_audio.py segments board.wav picodrive.wav blastem.wav python3 scripts/compare_audio.py window board.wav picodrive.wav --start 3 --seconds 4 numpy is needed (the system's Python has it); the board itself stays dependency-free. """ from __future__ import annotations import argparse import struct import sys from itertools import pairwise from pathlib import Path import numpy as np def read_wav(path: Path) -> tuple[int, np.ndarray]: """(rate, samples as float, shape (n, 2)).""" data = path.read_bytes() at, rate, pcm = 12, 0, b"" while at + 8 <= len(data): kind, size = data[at : at + 4], struct.unpack(" np.ndarray: """Two poles at ``corner`` Hz, each side: takes away each emulator's own DC and sub-audio filtering.""" pole = 1.0 - 2.0 * np.pi * corner / rate for _ in range(2): out = np.empty_like(x) previous_in = np.zeros(x.shape[1]) previous_out = np.zeros(x.shape[1]) for i in range(len(x)): previous_out = x[i] - previous_in + pole * previous_out previous_in = x[i] out[i] = previous_out x = out return x def active_segments(x: np.ndarray, rate: int, threshold: float) -> list[tuple[int, int]]: """Stretches (start, end) of 1/60 s windows where either side's AC RMS passes ``threshold`` of the file's loudest window; gaps under 3 windows are bridged, and a change in which sides sound starts a new stretch.""" window = rate // 60 n = len(x) // window rms = np.sqrt((x[: n * window].reshape(n, window, 2) ** 2).mean(axis=1)) top = rms.max() or 1.0 on = rms > threshold * top marks = [(bool(a), bool(b)) for a, b in on] segments: list[tuple[int, int, tuple[bool, bool]]] = [] for i, mark in enumerate(marks): if not any(mark): continue if segments and segments[-1][2] == mark and i - segments[-1][1] <= 3: segments[-1] = (segments[-1][0], i + 1, mark) else: segments.append((i, i + 1, mark)) return [(a * window, b * window) for a, b, _ in segments if b - a >= 10] def frequency(signal: np.ndarray, rate: int) -> float: """From the rising zero crossings, interpolated, first to last.""" s = signal - signal.mean() rising = np.nonzero((s[:-1] < 0) & (s[1:] >= 0))[0] if len(rising) < 3: return 0.0 times = rising + (-s[rising]) / (s[rising + 1] - s[rising]) return (len(times) - 1) * rate / (times[-1] - times[0]) def folded(signal: np.ndarray, rate: int, hz: float, bins: int = 64) -> np.ndarray: """One period, averaged over the stretch, zero mean and unit RMS.""" phase = (np.arange(len(signal)) * hz / rate) % 1.0 index = (phase * bins).astype(int) sums = np.bincount(index, weights=signal, minlength=bins) counts = np.bincount(index, minlength=bins) shape = sums / np.maximum(counts, 1) shape -= shape.mean() return shape / (np.sqrt((shape**2).mean()) or 1.0) def best_shift(a: np.ndarray, b: np.ndarray) -> float: """The circular shift of ``b`` that correlates best with ``a`` (normalised).""" return max(float(np.dot(a, np.roll(b, k))) / len(a) for k in range(len(b))) def describe( rate: int, x: np.ndarray, a: int, b: int ) -> tuple[np.ndarray, float, np.ndarray | None]: """A stretch's side levels (each against the louder), its frequency and its shape, from its middle 80 % (a test's start and end carry each emulator's own pop).""" trim = (b - a) // 10 part = x[a + trim : b - trim] rms = np.sqrt((part**2).mean(axis=0)) louder = int(rms[1] > rms[0]) hz = frequency(part[:, louder], rate) shape = folded(part[:, louder], rate, hz) if hz else None return rms / (rms.max() or 1.0), hz, shape def segments_report(paths: list[Path], threshold: float, scale: dict[str, float]) -> None: """Stretches of the first file, each paired with the stretch of every other file that starts nearest the same time after that file's first stretch (within 0.6 s).""" files = [] for path in paths: rate, x = read_wav(path) x = highpass(x, rate) files.append((path, rate, x, active_segments(x, rate, threshold))) print("files: " + "; ".join(f"{p.name} {len(s)} stretches" for p, _, _, s in files)) path0, rate0, x0, segments0 = files[0] for k, (a0, b0) in enumerate(segments0): sides0, hz0, shape0 = describe(rate0, x0, a0, b0) hz0 *= scale.get(path0.name, 1.0) cells = [f"{path0.stem}: {a0 / rate0:6.2f}-{b0 / rate0:6.2f} s, L {sides0[0]:.2f} " f"R {sides0[1]:.2f}, {hz0:8.2f} Hz"] # fmt: skip when0 = (a0 - segments0[0][0]) / rate0 for path, rate, x, segments in files[1:]: if not segments: cells.append(f"{path.stem}: -") continue first = segments[0][0] a, b = min(segments, key=lambda s: abs((s[0] - first) / rate - when0)) if abs((a - first) / rate - when0) > 0.6: cells.append(f"{path.stem}: -") continue sides, hz, shape = describe(rate, x, a, b) hz *= scale.get(path.name, 1.0) match = best_shift(shape0, shape) if shape0 is not None and shape is not None else 0 cells.append(f"{path.stem}: L {sides[0]:.2f} R {sides[1]:.2f}, {hz:8.2f} Hz, " f"shape {match:.3f}") # fmt: skip print(f"#{k + 1:2d} " + " | ".join(cells)) def resampled(path: Path, rate0: int) -> np.ndarray: """A file onto ``rate0`` (linear), DC taken away.""" rate, x = read_wav(path) if rate != rate0: t = np.arange(int(len(x) * rate0 / rate)) * rate / rate0 x = np.stack([np.interp(t, np.arange(len(x)), x[:, i]) for i in (0, 1)], axis=1) return highpass(x, rate0) def envelope_lag(a: np.ndarray, b: np.ndarray, rate: int, start: int, n: int, search: float) -> int: # fmt: skip """The lag of ``b`` against ``a`` (samples) at which their 10 ms RMS envelopes over ``a[start:start + n]`` correlate best, within +/- ``search`` seconds.""" block = rate // 100 def env(x: np.ndarray) -> np.ndarray: m = len(x) // block return np.sqrt((x[: m * block] ** 2).reshape(m, block).mean(axis=1)) ea, eb = env(a), env(b) s0, m = start // block, n // block ref = ea[s0 : s0 + m] best, lag = -2.0, 0 for d in range(-int(search * 100), int(search * 100) + 1): seg = eb[s0 + d : s0 + d + m] if s0 + d >= 0 else np.array([]) if len(seg) < m or ref.std() == 0 or seg.std() == 0: continue c = float(np.corrcoef(ref, seg)[0, 1]) if c > best: best, lag = c, d * block return lag def window_report(paths: list[Path], start: float, seconds: float, search: float) -> None: """Each later file against the first over one stretch: aligned by envelope, then in 50 ms windows each re-aligned within +/- 7 ms (following the lag, so two time bases a fraction of a per cent apart -- PicoDrive's libretro core is 0.13 % fast -- still line up); the windows' correlations (median, tenth percentile, per side), the lag's drift in parts per million, the level ratio and the spectra in third-octave bands.""" rate0 = read_wav(paths[0])[0] first = resampled(paths[0], rate0) a, n = int(start * rate0), int(seconds * rate0) reference = first[a : a + n] print(f"{paths[0].name}: {start:.2f}-{start + seconds:.2f} s, RMS L " f"{np.sqrt((reference[:, 0] ** 2).mean()):.1f} R " f"{np.sqrt((reference[:, 1] ** 2).mean()):.1f}") # fmt: skip window, reach = rate0 // 20, rate0 * 7 // 1000 for path in paths[1:]: x = resampled(path, rate0) lag = envelope_lag(first.sum(axis=1), x.sum(axis=1), rate0, a, n, search) cells = [] for side, name in ((0, "L"), (1, "R")): u_all, v_all = first[:, side], x[:, side] follow, corrs, lags = lag, [], [] for w in range(a, a + n - window, window): u = u_all[w : w + window] - u_all[w : w + window].mean() if u.std() < 1.0: continue best, at = -2.0, follow for d in range(follow - reach, follow + reach + 1): if w + d < 0 or w + d + window > len(v_all): continue v = v_all[w + d : w + d + window] v = v - v.mean() c = float(np.dot(u, v)) / (np.sqrt(np.dot(u, u) * np.dot(v, v)) or 1.0) if c > best: best, at = c, d corrs.append(best) lags.append((w, at)) follow = at if not corrs: cells.append(f"{name} silent") continue drift = 0.0 if len(lags) > 2: ws, ds = np.array(lags, dtype=float).T drift = float(np.polyfit(ws, ds, 1)[0]) * 1e6 other = x[a + lag : a + lag + n, side] ratio = np.sqrt((other**2).mean()) / (np.sqrt((reference[:, side] ** 2).mean()) or 1) cells.append(f"{name} corr median {np.median(corrs):.3f} p10 " f"{np.percentile(corrs, 10):.3f}, drift {drift:+.0f} ppm, " f"level x{ratio:.3f}") # fmt: skip spectrum = [] for signal in (reference.sum(axis=1), x[a + lag : a + lag + n].sum(axis=1)): power = np.abs(np.fft.rfft(signal)) ** 2 hz = np.fft.rfftfreq(len(signal), 1 / rate0) edges = 50 * 2 ** (np.arange(0, 28) / 3) spectrum.append(np.log10([power[(hz >= lo_) & (hz < hi_)].sum() + 1e-9 for lo_, hi_ in pairwise(edges)])) # fmt: skip bands = float(np.corrcoef(spectrum[0], spectrum[1])[0, 1]) print(f"{path.name}: lag {lag / rate0 * 1000:+.1f} ms; " + "; ".join(cells) + f"; third-octave spectra corr {bands:.3f}") # fmt: skip def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("mode", choices=("segments", "window")) parser.add_argument("wavs", nargs="+", type=Path) parser.add_argument("--threshold", type=float, default=0.05) parser.add_argument("--start", type=float, default=0.0) parser.add_argument("--seconds", type=float, default=3.0) parser.add_argument("--search", type=float, default=1.0, help="lag search, seconds") parser.add_argument( "--rate-scale", action="append", default=[], help="NAME=FACTOR: scale NAME's frequencies (a core whose stated rate is not its " "own: PicoDrive's libretro core gives 735 samples a frame at 59.92 frames/s, " "44,042.6 Hz, and calls it 44,100, so 0.99870)", ) args = parser.parse_args() if args.mode == "segments": scale = {k: float(v) for k, v in (item.split("=") for item in args.rate_scale)} segments_report(args.wavs, args.threshold, scale) else: window_report(args.wavs, args.start, args.seconds, args.search) return 0 if __name__ == "__main__": sys.exit(main())