"""PCM driver test: build a test tone, assemble the test ROM, run it with the FM generator capturing, and check that every sample came out, in order, each held for exactly three FM sample periods. py -3.12 tools/pcm_check.py [--frames N] The tone is a pseudo-random byte sequence (so order and drops are unambiguous), long enough to cross a 32 KB bank boundary. """ from __future__ import annotations import argparse import struct import subprocess import sys from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from rrmd.toolchain import assemble_68k, assemble_z80 # noqa: E402 EMULATOR = ROOT.parent / "megadrive-python" EMU_PYTHON = EMULATOR / ".venv" / "Scripts" / "python.exe" OUT = ROOT / "out" / "pcmtest" HOLD = 3 # FM sample periods per PCM sample TONE_SAMPLES = 40_000 # 2.3 s: crosses the 32 KB bank boundary def build_tone() -> np.ndarray: rng = np.random.default_rng(7) # slow random walk, 8-bit: adjacent samples differ by at most 9, never equal # (equal neighbours would be indistinguishable from a dropped/duplicated one) steps = rng.integers(1, 10, TONE_SAMPLES) * rng.choice([-1, 1], TONE_SAMPLES) tone = np.empty(TONE_SAMPLES, dtype=np.int64) v = 128 for i, s in enumerate(steps): v += s if v > 250 or v < 5: v -= 2 * s tone[i] = v return tone.astype(np.uint8) def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--frames", type=int, default=60) parser.add_argument("--machine", default="megadrive") args = parser.parse_args() OUT.mkdir(parents=True, exist_ok=True) tone = build_tone() (OUT / "tone.u8").write_bytes(tone.tobytes()) assemble_z80(ROOT / "player" / "pcm.z80", OUT / "pcm.bin") assemble_68k(ROOT / "player" / "pcmtest.s", OUT / "pcmtest.bin", listing=OUT / "pcmtest.lst", include_dirs=(OUT,)) audio_dir = OUT / "audio" for old in audio_dir.glob("*") if audio_dir.exists() else []: old.unlink() cmd = [str(EMU_PYTHON), str(EMULATOR / "scripts" / "board_frames.py"), str(OUT / "pcmtest.bin"), str(OUT / "frames"), "--machine", args.machine, "--frames", str(args.frames), "--fm", "--audio", str(audio_dir)] # fmt: skip subprocess.run(cmd, check=True) raw = np.frombuffer((audio_dir / "fm.bin").read_bytes(), dtype=" 1000) if len(long_runs) == 0: print("no PCM activity found") return 1 first = int(long_runs[-1]) + 1 lengths, values = lengths[first:], values[first:] # Trailing run is the tail after the tone (or cut off by the capture end): drop it. lengths, values = lengths[:-1], values[:-1] # A value held for one FM period between two others is the DAC changing part way # through a multiplexed sample (some of channel 6's slots old, some new): real, # harmless, and not a sample. Fold it into its successor. keep = lengths != 1 transitions = int((~keep).sum()) merged_lengths = lengths.copy() for i in np.flatnonzero(~keep): if i + 1 < len(merged_lengths): merged_lengths[i + 1] += 1 lengths, values = merged_lengths[keep], values[keep] n = len(values) hist = np.bincount(np.clip(lengths, 0, 8), minlength=9) print(f"{n} output samples ({transitions} mid-sample transitions folded); hold-length histogram (FM periods 0..8+): {hist.tolist()}") exact = int((lengths == HOLD).sum()) print(f"held exactly {HOLD}: {exact} ({100 * exact / n:.2f}%); 2: {int((lengths == 2).sum())}, 4: {int((lengths == 4).sum())}, other: {int(((lengths < 2) | (lengths > 4)).sum())}") expected = tone[:n].astype(np.int64) if n < 100: print("too few samples to check order") return 1 if args.machine in ("megadrive2", "genesis2", "genesis3", "megadrive2-japan"): # YM3438 (no ladder effect): the capture is 3 slots x 2 x (sample - 128). predicted = 6 * (expected - 128) mism = int((values != predicted).sum()) print(f"exact value match (6 x (sample - 128)): {n - mism} of {n} ({100 * (n - mism) / n:.3f}%)") if mism: bad = np.flatnonzero(values != predicted) print(f"first mismatches at: {bad[:10].tolist()}; got {values[bad[:5]].tolist()} expected {predicted[bad[:5]].tolist()}") ok = mism == 0 and exact >= 0.9 * n else: # MD1 ladder effect: nonlinear but monotonic, so compare the direction of change. d_out = np.sign(np.diff(values)) d_exp = np.sign(np.diff(expected)) agree = int((d_out == d_exp).sum()) print(f"direction of change agrees with the source on {agree} of {n - 1} steps ({100 * agree / (n - 1):.3f}%)") bad = np.flatnonzero(d_out != d_exp) if len(bad): print(f"first disagreements at output samples: {bad[:10].tolist()}") ok = agree == n - 1 and exact >= 0.9 * n print("PASS" if ok else "FAIL") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())