#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 5: sound-register writes (POKEY and TIA audio) against MAME 0.285, with times. MAME's side is ``writes.log`` from ``scripts/mame_trace.py --writes-only`` (memory taps, no debugger; docs/mame-oracle.md "Writes-only"). The board runs the same dump from the same BIOS and records its writes to the same address set: TIA AUDC/AUDF/AUDV ($15-$1A and the 7800-mode mirrors $115, $215, $315), $01 (INPTCTRL while unlocked, TIA VBLANK after), and POKEY at $4000-$400F, $440-$44F, $450-$45F, $800-$80F. Two judgements: 1. **Order and value**: the writes of the first ``--seconds`` of MAME's run, compared one by one (address, value) with the board's. 2. **Φ2 periods between writes, explained by timing.md's table** ("Φ2 periods at the cartridge port"). For every interval between successive writes the board's period count is decomposed from counts kept outside the period counter: CPU bus cycles (one period each, a slow one included), periods held by HALT (DMA, one per 4 clocks) and periods a read repeated for RDY (WSYNC); and its MARIA-clock length must equal 4 x periods + 2 x slow cycles. Then against MAME's CPU-cycle interval (MAME's time x 1,789,772.5 Hz): the difference is DMA accounting, which docs/mame-oracle.md traps 4-5 and C2-C4 describe; its distribution and total drift are printed. python scripts/sound_writes.py tests/mame_traces/a7800-ballblazu-writes/writes.log \\ ".../Ballblazer (USA).zip" --seconds 60 Seeded fault: ``--fault drop-write`` drops the board's 100th write (the order check must fail); ``--fault period`` adds one period to one interval's count (the decomposition must fail). """ from __future__ import annotations import argparse import collections import json import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a7800_python.machine import NTSC, PAL # noqa: E402 from a7800_python.system import System # noqa: E402 CPU_HZ = {"ntsc": 14318180 / 8, "pal": 14187576 / 8} def tapped(address: int) -> bool: """The address set mame_trace.py's WRITES_LUA taps, exactly.""" if address < 0x400: low = address & 0xFF return 0x15 <= low <= 0x1A or low == 0x01 return (0x4000 <= address <= 0x400F or 0x440 <= address <= 0x45F or 0x800 <= address <= 0x80F) # fmt: skip def mame_writes(log: Path, seconds: float, hz: float): """(writes, POKEY reads), each a list of (address, value, MAME CPU cycles).""" out, reads = [], [] with log.open() as handle: for line in handle: kind, address, value, when = line.split() t = float(when) if t >= seconds: break (out if kind == "S" else reads).append((int(address, 16), int(value, 16), t * hz)) return out, reads def realign(ours: list, theirs: list, window: int = 64) -> tuple[int, int]: """Greedy re-alignment after a difference: (matched writes, resyncs).""" i = j = matched = resyncs = 0 while i < len(ours) and j < len(theirs): if ours[i] == theirs[j]: i, j, matched = i + 1, j + 1, matched + 1 continue for k in range(1, window): if ours[i + k : i + k + 4] == theirs[j : j + 4]: i += k break if ours[i : i + 4] == theirs[j + k : j + k + 4]: j += k break else: i, j = i + 1, j + 1 resyncs += 1 return matched, resyncs def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("log", type=Path) parser.add_argument("cart", type=Path) parser.add_argument("--seconds", type=float, default=60.0) parser.add_argument("--pal", action="store_true") parser.add_argument("--fault", choices=["drop-write", "period"]) parser.add_argument("--mame-switches", action="store_true") parser.add_argument("--force-reads", metavar="REGS", help="hex POKEY registers whose reads take MAME's values, e.g. 8,9 " "(a diagnostic exclusion, counted)") # fmt: skip parser.add_argument("--save", type=Path, help="write the board's writes as JSON lines") parser.add_argument( "--load", type=Path, help="judge a saved run instead (POKEY reads not kept)" ) args = parser.parse_args() machine = PAL if args.pal else NTSC hz = CPU_HZ["pal" if args.pal else "ntsc"] theirs, their_reads = mame_writes(args.log, args.seconds, hz) system = System.from_rom(args.cart, machine) board = system.board if args.mame_switches: # harness.py: MAME's difficulty switches (a setting) from harness import mame_switches mame_switches(board) if args.force_reads: # a named exclusion: register k's n-th read returns MAME's n-th value forced = {int(r, 16) for r in args.force_reads.split(",")} queues = {r: [v for a, v, _ in their_reads if a & 0xF == r] for r in forced} for socket in board.cartridge.pokeys.values(): original = socket.read def read(register, original=original): value = original(register) queue = queues.get(register & 0xF) return queue.pop(0) if queue else value socket.read = read counts = {"cpu": 0, "slow": 0} ours: list[dict] = [] our_reads: list[tuple[int, int, int]] = [] def watch(kind, address, value, clock): if kind == "D": return counts["cpu"] += 1 if board.is_slow(address): counts["slow"] += 1 if kind == "R" and 0x4000 <= address <= 0x400F: our_reads.append((address, value, board.periods + 1)) if kind == "W" and tapped(address): ours.append({ "address": address, "value": value, "clock": clock, # the period this write ends is counted after the callback: "periods": board.periods + 1, "cpu": counts["cpu"], "slow": counts["slow"], "halted": board.halted_periods, "stalled": board.stalled_periods, "frame": board.maria.frame, }) # fmt: skip board.bus_observers.append(watch) began = time.monotonic() clock_hz = hz * 4 end_clock = int((args.seconds + 1.0) * clock_hz) step = system.cpu.step if args.load: # a saved run (--save): re-judge without running the board with args.load.open() as handle: ours[:] = [json.loads(line) for line in handle] while not args.load and len(ours) < len(theirs) and board.clocks < end_clock: step() wall = time.monotonic() - began if args.fault == "drop-write" and len(ours) > 100: del ours[100] if args.save: with args.save.open("w") as handle: for row in ours: handle.write(json.dumps(row) + "\n") n = min(len(ours), len(theirs)) first = next((i for i in range(n) if (ours[i]["address"], ours[i]["value"]) != theirs[i][:2]), None) # fmt: skip same = first is None and len(ours) == len(theirs) print(f"{args.cart.name}: {system.description.summary()}") print(f"board ran {board.clocks / clock_hz:.2f} s emulated ({board.maria.frame} frames) " f"in {wall:.0f} s") # fmt: skip kinds = collections.Counter("POKEY" if a >= 0x400 else "TIA $01" if a & 0xFF == 1 else "TIA audio" for a, _, _ in theirs) # fmt: skip print(f"MAME {len(theirs)} writes in its first {args.seconds:g} s ({dict(kinds)}); " f"board {len(ours)}: " + ("identical in address, value and order" if same else f"first difference at {first}: MAME " f"{theirs[first][:2] if first is not None and first < len(theirs) else '-'} board " f"{(ours[first]['address'], ours[first]['value']) if first is not None and first < len(ours) else '-'}")) # fmt: skip if not same: a = [(r["address"], r["value"]) for r in ours] b = [(x, v) for x, v, _ in theirs] matched, resyncs = realign(a, b) when = theirs[first][2] / hz if first is not None and first < len(theirs) else 0 print(f" the first difference is at MAME {when:.3f} s; re-aligned greedily: " f"{matched} of {len(theirs)} writes match in order, {resyncs} resyncs") # fmt: skip # POKEY reads, per register (RANDOM $A is the one a program's state can follow; # most others here are the dummy reads of STA abs,X at the POT registers). for register in sorted( {a & 0xF for a, _, _ in their_reads} | {a & 0xF for a, _, _ in our_reads} ): mine = [r for r in our_reads if r[0] & 0xF == register] yours = [r for r in their_reads if r[0] & 0xF == register] m = min(len(mine), len(yours)) differ = next((k for k in range(m) if mine[k][1] != yours[k][1]), None) line = f"POKEY reads of ${register:X}: MAME {len(yours)}, board {len(mine)}; " if differ is None: line += "same values in order over the shorter" else: line += (f"first different value #{differ} at MAME {yours[differ][2] / hz:.3f} s " f"(MAME {yours[differ][1]:02X}, board {mine[differ][1]:02X}); Φ2 periods " f"from power-on: board {mine[differ][2]:,}, MAME {yours[differ][2]:,.0f}; " f"{sum(mine[k][1] != yours[k][1] for k in range(m))} of {m} differ") # fmt: skip print(line) # 2. the decomposition of each interval, then against MAME. if args.fault == "period" and len(ours) > 50: ours[50]["periods"] += 1 broken = 0 diffs = collections.Counter() e = first if first is not None else n for k in range(1, n): a, b = ours[k - 1], ours[k] periods = b["periods"] - a["periods"] parts = (b["cpu"] - a["cpu"]) + (b["halted"] - a["halted"]) + (b["stalled"] - a["stalled"]) clocks = b["clock"] - a["clock"] if periods != parts or clocks != 4 * periods + 2 * (b["slow"] - a["slow"]): broken += 1 if k < e: diffs[round(periods - (theirs[k][2] - theirs[k - 1][2]))] += 1 print(f"intervals: {n - 1}; Φ2 count = CPU cycles + DMA periods + RDY periods and " f"clocks = 4 x periods + 2 x slow in {n - 1 - broken} of {n - 1}") # fmt: skip if e > 1: last = e - 1 # against MAME: only the writes before the first difference drift = (ours[last]["periods"] - ours[0]["periods"]) - (theirs[last][2] - theirs[0][2]) print(f"board periods - MAME cycles per interval (most common): {diffs.most_common(8)}") print(f"writes 0-{last} (to MAME {theirs[last][2] / hz:.2f} s): board " f"{ours[last]['periods'] - ours[0]['periods']:,} periods, MAME " f"{theirs[last][2] - theirs[0][2]:,.0f} cycles, drift {drift:+,.0f}") # fmt: skip slow = ours[last]["slow"] - ours[0]["slow"] real = (ours[last]["clock"] - ours[0]["clock"]) / 4 - (theirs[last][2] - theirs[0][2]) print(f" drift explained: a slow cycle is one 6-clock period (timing.md), so periods " f"fall behind time by slow/2 = {-slow / 2:+,.0f}; the rest, {drift + slow / 2:+,.0f}, " f"is when the program wrote (board time - MAME time in CPU cycles: {real:+,.0f})") # fmt: skip dma = ours[n - 1]["halted"] - ours[0]["halted"] print(f"board DMA periods in the window {dma:,}, RDY periods " f"{ours[n - 1]['stalled'] - ours[0]['stalled']:,}, slow cycles " f"{ours[n - 1]['slow'] - ours[0]['slow']:,}") # fmt: skip return 0 if same and not broken else 1 if __name__ == "__main__": sys.exit(main())