"""Find every place the PCM driver's 4-sample group ran longer than one Timer A period (806.4 Z80 cycles) and print what the Z80 / 68000 were doing around it. .venv python tools/pcm_overruns.py ROM [frames] [machine] """ from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT.parent / "megadrive-python" / "src")) sys.path.insert(0, str(ROOT.parent / "m68000-python" / "src")) sys.path.insert(0, str(ROOT.parent / "z80-python" / "src")) from megadrive_python.__main__ import load_image # noqa: E402 from megadrive_python.cartridge import Cartridge # noqa: E402 from megadrive_python.machine import MACHINES # noqa: E402 from megadrive_python.system import System # noqa: E402 Z80_MCLK = 15 GROUP = 4 * 3 * 1008 # master clocks per 4-sample group def main(rom: Path, frames: int, machine: str) -> None: system = System(MACHINES[machine], Cartridge.from_image(load_image(rom))) fm = system.board.fm fm.enabled = True log: list[tuple[int, int, int, int, int]] = [] real_write = fm.write z80 = system.z80 vdp = system.board.vdp def write(port: int, value: int) -> None: log.append((fm.mclk, port & 3, value, z80.pc, vdp.frame)) real_write(port, value) fm.write = write # type: ignore[method-assign] for _ in range(frames): system.run_frame() fm.take_samples() system.board.psg.take_samples() addr = None dac: list[tuple[int, int, int]] = [] for t, port, value, pc, frame in log: if port == 0: addr = value elif port == 1 and addr == 0x2A: dac.append((t, pc, frame)) print(f"{len(dac)} DAC samples") # the group ends with the write at the highest PC (the iteration that waits on the timer) end_pc = max(pc for _, pc, _ in dac[400:]) starts = [(t, f) for t, pc, f in dac if pc == end_pc] over = 0 for (t0, f0), (t1, f1) in zip(starts, starts[1:]): d = (t1 - t0) / GROUP if d > 1.05: over += 1 if over <= 40: print(f" group of {d:5.2f} periods at frame {f0} (mclk {t0}), DAC@{t0 % 1008}") print(f"{over} overruns in {len(starts)} groups") # phase of the group-ending write against a fixed 12-sample grid: constant if the # driver is locked to a free-running timer, drifting if lost time is never recovered phase = [(t % GROUP) // Z80_MCLK for t, _ in starts] print("phase (Z80 cycles) every 25 groups:") print(" ".join(str(p) for p in phase[400::25][:120])) if len(sys.argv) > 4: g0, g1 = int(sys.argv[4]), int(sys.argv[5]) print(f"group durations (periods) {g0}..{g1}, with the Z80 PC of the group-ending write:") print(" ".join(f"{(starts[i + 1][0] - starts[i][0]) / GROUP:.2f}" for i in range(g0, g1))) if __name__ == "__main__": main( Path(sys.argv[1]), int(sys.argv[2]) if len(sys.argv) > 2 else 70, sys.argv[3] if len(sys.argv) > 3 else "megadrive2", )