#!/usr/bin/env python3 """Compare the board's sound with NanoBoyAdvance 1.8.3's over the same frames. A detector, not a judge (docs/validation.md, rung 5): NanoBoyAdvance is emulator-derived, so a difference is a question, never a verdict. Both mix one sample every 512 cycles from power-on (SOUNDBIAS resolution 0), so where the two machines agree cycle for cycle the samples are equal one for one; where an instruction's timing differs the streams slip against each other and the comparison says by how much. Each ROM runs N frames on the board (PyPy, retail BIOS read in place, ``--wav``) and on ``reference/build/nba/nba_driver --wav``. Printed per ROM: - ``equal``: stereo frames identical at the same index, of those compared; - ``near``: frames within one step of the 10-bit output (64 of the 16-bit sample) at the best lag within +-``LAGS`` samples, found per second: timing slips leave this high; - ``level``: the board's RMS over NanoBoyAdvance's, over the seconds where either sounds; - ``envelope``: the correlation of the two loudness curves (RMS per 512 samples, 1/64 s): the same music gives 1 whatever the samples' phase. It is taken at the best shift within four points either way, and the shift is printed: a game that starts its music a frame apart on the two machines (a frame is 549 samples) is the same music one point over; - per second (``--seconds``): both RMS levels, the best lag and the two fractions. Both WAVs are kept under ``tests/sound_runs/`` (not committed) to listen to. python scripts/sound_diff.py ROM[.zip] ... [--frames 1500] [--skip-bios] [--keys FRAME:MASK]... python scripts/sound_diff.py --games # the GAMES list """ from __future__ import annotations import argparse import array import subprocess import sys import tempfile import wave from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from frame_diff import NBA, ROOT_NOINTRO, _retail, rom_file # noqa: E402 from referee_run import bios_args # noqa: E402 RUNS = ROOT / "tests" / "sound_runs" RATE = 32768 LAGS = 16 WINDOW = 512 # samples per point of the loudness curve STEP = 64 # one step of the 10-bit output in the 16-bit samples #: (No-Intro name, frames, keys): music a few seconds in, from the cartridge's entry (skip_bios). #: All play MusicPlayer2000 through the FIFOs; the Game Boy channels heard in these frames (the #: board's own count of frames with a channel on at a volume above 0) are noted beside each. GAMES = [ ("Pokemon - Emerald Version (USA, Europe).zip", 1500, []), # pulses 1 and 2 ("Mario Kart - Super Circuit (Europe).zip", 1200, []), # pulse 2 and the wave channel ("F-Zero - Maximum Velocity (USA, Europe).zip", 1200, []), # pulses 1 and 2 ("Legend of Zelda, The - The Minish Cap (USA).zip", 1200, []), # pulses and noise ("Metroid - Zero Mission (USA).zip", 1200, []), # noise ("Golden Sun (USA, Europe).zip", 1200, []), # pulse 1 ("Kirby - Nightmare in Dream Land (USA).zip", 1200, []), # FIFOs only ("Advance Wars (USA).zip", 1200, []), # FIFOs only ] def read_wav(path: Path) -> array.array: with wave.open(str(path), "rb") as source: assert source.getnchannels() == 2 and source.getsampwidth() == 2 assert source.getframerate() == RATE samples = array.array("h") samples.frombytes(source.readframes(source.getnframes())) if sys.byteorder == "big": samples.byteswap() return samples def run_board(rom: Path, frames: int, keys: list[str], skip: bool, out: Path) -> None: command = [str(ROOT / ".venv-pypy" / "bin" / "python"), "-m", "gba_python", str(rom)] command += ["--frames", str(frames), "--no-stop", "--wav", str(out)] command += ["--skip-bios"] if skip else [] for key in keys: command += ["--keys", key] subprocess.run(command, capture_output=True, check=True, cwd=ROOT) def run_nba(rom: Path, frames: int, keys: list[str], skip: bool, out: Path) -> None: with tempfile.TemporaryDirectory() as scratch: command = [str(NBA), str(rom), *bios_args(str(_retail()), Path(scratch))] command += ["--frames", str(frames), "--wav", str(out)] command += ["--skip-bios"] if skip else [] for key in keys: command += ["--keys", key] subprocess.run(command, capture_output=True, check=True, timeout=1800) def rms(samples: array.array) -> float: return (sum(s * s for s in samples) / len(samples)) ** 0.5 if samples else 0.0 def near_at(board: array.array, nba: array.array, start: int, count: int, lag: int) -> int: """Stereo frames from ``start`` where the board's frame i is within a step of NBA's i + lag.""" hits = 0 limit = len(nba) - 1 for i in range(start * 2, (start + count) * 2, 2): j = i + lag * 2 if ( 0 <= j < limit and abs(board[i] - nba[j]) <= STEP and abs(board[i + 1] - nba[j + 1]) <= STEP ): hits += 1 return hits def envelope(samples: array.array, frames: int) -> list[float]: return [rms(samples[i * 2 : (i + WINDOW) * 2]) for i in range(0, frames - WINDOW + 1, WINDOW)] def correlation(a: list[float], b: list[float]) -> float: if not a: return 0.0 mean_a, mean_b = sum(a) / len(a), sum(b) / len(b) cross = sum((x - mean_a) * (y - mean_b) for x, y in zip(a, b, strict=True)) power = (sum((x - mean_a) ** 2 for x in a) * sum((y - mean_b) ** 2 for y in b)) ** 0.5 return cross / power if power else 1.0 if a == b else 0.0 def best_envelope(a: list[float], b: list[float]) -> tuple[float, int]: """The best correlation of two loudness curves over small shifts, and the shift.""" def at(shift: int) -> float: return correlation( a[max(0, shift) : len(a) + min(0, shift)], b[max(0, -shift) : len(b) + min(0, -shift)] ) shift = max(range(-4, 5), key=lambda g: (at(g), -abs(g))) return at(shift), shift def compare(board: array.array, nba: array.array) -> dict: frames = min(len(board), len(nba)) // 2 seconds = [] equal = near = 0 for start in range(0, frames - RATE + 1, RATE): b, n = board[start * 2 : (start + RATE) * 2], nba[start * 2 : (start + RATE) * 2] same = sum(1 for i in range(0, RATE * 2, 2) if b[i] == n[i] and b[i + 1] == n[i + 1]) probe = min(RATE, 4096) # choose the lag on the second's first eighth, score it on all lag = max( range(-LAGS, LAGS + 1), key=lambda g: (near_at(board, nba, start, probe, g), -abs(g)) ) close = near_at(board, nba, start, RATE, lag) equal += same near += close seconds.append( {"second": start // RATE, "board": rms(b), "nba": rms(n), "lag": lag, "equal": same / RATE, "near": close / RATE} ) # fmt: skip loud = [s for s in seconds if s["board"] > STEP or s["nba"] > STEP] compared = len(seconds) * RATE return { "frames": frames, "equal": equal / compared if compared else 0.0, "near": near / compared if compared else 0.0, "level": (sum(s["board"] for s in loud) / sum(s["nba"] for s in loud)) if loud and sum(s["nba"] for s in loud) else 0.0, "sounding": len(loud), "envelope": best_envelope(envelope(board, frames), envelope(nba, frames)), "seconds": seconds, } # fmt: skip def job(spec: tuple[str, int, list[str], bool]) -> dict: name, frames, keys, skip = spec path = Path(name) if Path(name).is_absolute() else ROOT / name RUNS.mkdir(parents=True, exist_ok=True) stem = f"{path.stem.split(' (')[0].replace(' ', '_')}-{frames}" board_wav, nba_wav = RUNS / f"{stem}-board.wav", RUNS / f"{stem}-nba.wav" with tempfile.TemporaryDirectory() as scratch: rom = rom_file(path, Path(scratch)) with ThreadPoolExecutor(2) as pool: runs = [ pool.submit(run_board, rom, frames, keys, skip, board_wav), pool.submit(run_nba, rom, frames, keys, skip, nba_wav), ] for run in runs: run.result() result = compare(read_wav(board_wav), read_wav(nba_wav)) result["rom"] = path.name return result def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("roms", nargs="*") parser.add_argument("--frames", type=int, default=1500) parser.add_argument("--keys", action="append", default=[]) parser.add_argument("--skip-bios", action="store_true", help="start both at 8000000") parser.add_argument("--games", action="store_true", help="the GAMES list (skip_bios)") parser.add_argument("--seconds", action="store_true", help="print every second") parser.add_argument("--jobs", type=int, default=3) args = parser.parse_args() specs = [(rom, args.frames, args.keys, args.skip_bios) for rom in args.roms] if args.games: games = ROOT_NOINTRO / "Nintendo - Game Boy Advance" specs += [(str(games / name), frames, keys, True) for name, frames, keys in GAMES] if not specs: parser.error("give a ROM or --games") with ThreadPoolExecutor(args.jobs) as pool: for result in pool.map(job, specs): print( f"{result['rom'][:52]:52s} {result['frames'] / RATE:5.1f} s" f" equal {result['equal']:6.1%} near {result['near']:6.1%}" f" level {result['level']:.3f} over {result['sounding']} s" f" envelope {result['envelope'][0]:.4f} at {result['envelope'][1]:+d}" ) if args.seconds: for s in result["seconds"]: print( f" {s['second']:3d} board {s['board']:7.0f} nba {s['nba']:7.0f}" f" lag {s['lag']:+3d} equal {s['equal']:6.1%} near {s['near']:6.1%}" ) return 0 if __name__ == "__main__": sys.exit(main())