"""Time every YM2612 write the Z80 driver makes, from inside the emulator, and report the intervals between DAC sample writes by position in the 4-sample group - the tool that tunes the driver's padding constants. .venv python tools/pcm_timing.py out/pcmtest/pcmtest.bin [frames] """ from __future__ import annotations import sys from collections import Counter 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 # Z80 cycle in master clocks PERIOD = 3 * 1008 / Z80_MCLK # 201.6 Z80 cycles per sample def main(rom: Path, frames: int) -> None: system = System(MACHINES["megadrive"], Cartridge.from_image(load_image(rom))) fm = system.board.fm fm.enabled = True log: list[tuple[int, int, int, int]] = [] real_write = fm.write z80 = system.z80 def write(port: int, value: int) -> None: log.append((fm.mclk, port & 3, value, z80.pc)) 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() # DAC data writes: port 1 while the latched address is $2A; keyed by the PC of the # writing instruction, which identifies the loop iteration. addr = None dac: list[tuple[int, int]] = [] for t, port, value, pc in log: if port == 0: addr = value elif port == 1 and addr == 0x2A: dac.append((t, pc)) print(f"{len(log)} YM writes, {len(dac)} DAC samples") if len(dac) < 40: return dac = dac[400:] # steady state by_pc: dict[int, Counter] = {} for (t0, pc0), (t1, _) in zip(dac, dac[1:]): by_pc.setdefault(pc0, Counter())[round((t1 - t0) / Z80_MCLK)] += 1 total = 0.0 for pc in sorted(by_pc): c = by_pc[pc] n = sum(c.values()) mean = sum(v * k for v, k in c.items()) / n total += mean top = sorted(c.items(), key=lambda kv: -kv[1])[:7] print(f" write at PC {pc:04X}: n={n:5d} mean {mean:6.1f} " + ", ".join(f"{v}:{k}" for v, k in top)) print(f"group total of means {total:.1f} (nominal {4 * PERIOD:.1f})") return # drop the first second (priming) and look at steady state d = [(b - a) / Z80_MCLK for a, b in zip(dac_times, dac_times[1:])] d = d[200:] # phase: find the group alignment by the position of the longest-average interval best = None for k in range(4): groups = [d[i : i + 4] for i in range(k, len(d) - 4, 4)] means = [sum(g[j] for g in groups) / len(groups) for j in range(4)] if best is None or max(means) > best[1]: best = (k, max(means), means) k, _, means = best print(f"mean interval after sample 1,2,3,4 of a group (Z80 cycles; nominal {PERIOD:.1f}): " + ", ".join(f"{m:6.1f}" for m in means)) groups = [d[i : i + 4] for i in range(k, len(d) - 4, 4)] print(f"group total mean {sum(means):.1f} (nominal {4 * PERIOD:.1f})") for j in range(4): c = Counter(round(g[j]) for g in groups) top = sorted(c.items(), key=lambda kv: -kv[1])[:6] print(f" interval after iteration {j + 1}: " + ", ".join(f"{v}:{n}" for v, n in top)) if __name__ == "__main__": main(Path(sys.argv[1]), int(sys.argv[2]) if len(sys.argv) > 2 else 40)