#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Compare spc700-python + snes_python.smp + snes_python.dsp with the snes_spc referee on .spc files. python -I scripts/dsp_compare.py [--samples N] [--every-other 0|1] [--phase P] [SPC ...] For each file: run the referee (closed box, ``$EMU_TOOLS_GPL/tools/snes-spc/build/spc_dump --regs``) and the board's S-SMP side for the same number of 32 kHz samples, then count the samples whose (left, right) differ, the first one, and, from the per-sample DSP register dumps, which registers differ first. Every referee number is OBSERVED (snes_spc 0.9.0). Default: the synthetic cases. """ from __future__ import annotations import argparse import hashlib import struct import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) # run with -I: the script directory is not on the path import emu_tools from snes_python.smp import SMP from snes_python.spc_file import read_spc #: The referee, ``$EMU_TOOLS_GPL/tools/snes-spc/build/spc_dump`` (None when not built). REFEREE = emu_tools.find(emu_tools.SPC_DUMP) SYNTHETIC = ROOT / "reference" / "dsp" / "spc" / "synthetic" RUNS = ROOT / "reference" / "dsp" / "runs" def referee(spc: Path, samples: int) -> tuple[list[tuple[int, int]], bytes]: RUNS.mkdir(parents=True, exist_ok=True) tag = hashlib.sha256(str(spc.resolve()).encode()).hexdigest()[:8] raw, regs = RUNS / f"{spc.stem}-{tag}.ref.raw", RUNS / f"{spc.stem}-{tag}.ref.regs" subprocess.run( [str(REFEREE), str(spc), str(samples), str(raw), "--regs", str(regs)], check=True ) values = struct.unpack(f"<{samples * 2}h", raw.read_bytes()) return list(zip(values[0::2], values[1::2])), regs.read_bytes() def board( spc: Path, samples: int, ref_regs: bytes, every_other: int | None = None, phase: int | None = None, ) -> tuple[list, list[int], int, tuple | None]: """Run the board's S-SMP side; return its samples, the samples whose register file matched the referee's snapshot nowhere, how many matched only off step 31, and the first mismatch. The referee's snapshot of sample i is taken after DSP step 31 of sample i, except that it sometimes lands a few steps earlier (OBSERVED: 10 of 1,500 samples of a Mega Man X track equal the board's register file after step 21-24, and no other step). So a snapshot counts as matching if it equals the board's file after any step from 20 to 31 of that sample; matches off step 31 are counted as jitter. """ smp = SMP() smp.load_spc(read_spc(spc)) if every_other is not None: smp.dsp.every_other = every_other if phase is not None: smp.dsp.phase = phase dsp = smp.dsp plain_step = dsp.step sample = 0 # the sample whose steps are running pending: dict[int, str] = {} # sample -> "exact" or "near" once matched mismatched: list[int] = [] jitter = 0 first: list = [] def check(i: int, exact: bool) -> None: if ( i < samples and pending.get(i) != "exact" and dsp.regs == ref_regs[i * 128 : i * 128 + 128] ): pending[i] = "exact" if exact else pending.get(i, "near") def settle(i: int) -> None: nonlocal jitter if i < 0 or i >= samples: return verdict = pending.pop(i, None) if verdict is None: mismatched.append(i) if not first: a = ref_regs[i * 128 : i * 128 + 128] diff = [ f"${r:02X}:{a[r]:02X}/{dsp.regs[r]:02X}" for r in range(128) if a[r] != dsp.regs[r] ] first.append((i, diff[:6])) elif verdict == "near": jitter += 1 def step() -> None: nonlocal sample current = dsp.phase plain_step() if current >= 20: check(sample, current == 31) if current <= 8: check(sample - 1, False) if current == 8: settle(sample - 1) if current == 31: sample += 1 dsp.step = step while sample <= samples: # through step 8 of the sample after the last smp.cpu.step() out = dsp.take_samples()[:samples] return out, mismatched, jitter, first[0] if first else None def compare( spc: Path, samples: int, every_other: int | None = None, phase: int | None = None, lag: int = 4 ) -> int: """Print one line for ``spc``; return the number of samples whose audio differs.""" ref_out, ref_regs = referee(spc, samples + lag) ref_out = ref_out[lag:] start = time.perf_counter() our_out, mismatched, jitter, reg_first = board(spc, samples, ref_regs, every_other, phase) elapsed = time.perf_counter() - start diffs = [i for i in range(samples) if ref_out[i] != our_out[i]] line = f"{spc.name[:30]:30s} samples {samples} audio-different {len(diffs)}" if diffs: first = diffs[0] line += f" (first {first}: ref {ref_out[first]} ours {our_out[first]})" line += f" regs-different {len(mismatched)}" if reg_first: line += f" (first {reg_first})" line += f" jitter {jitter}" print(line + f" ({elapsed:.1f} s)", flush=True) compare.last = (len(diffs), len(mismatched), jitter, diffs[0] if diffs else None) return len(diffs) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--samples", type=int, default=16000) parser.add_argument("--every-other", type=int, default=None) parser.add_argument("--phase", type=int, default=None) parser.add_argument( "--lag", type=int, default=4, help="samples the referee's audio trails its register snapshots (OBSERVED: 4)", ) parser.add_argument("spc", nargs="*", type=Path) args = parser.parse_args() emu_tools.require(emu_tools.SPC_DUMP) # exit 3, naming EMU_TOOLS_GPL and build.sh files = args.spc or sorted(SYNTHETIC.glob("*.spc")) total = sum(compare(f, args.samples, args.every_other, args.phase, args.lag) for f in files) print(f"total different samples: {total}") return 0 if total == 0 else 1 if __name__ == "__main__": sys.exit(main())