#!/usr/bin/env python3 """Replay a MAME I/O log into the VDP and PSG, and compare every VDP read. No CPU is involved: the Z80's port writes from MAME's log drive the devices at MAME's cycle stamps, and each port read MAME recorded (status, data, V counter, H counter) is checked against what the device returns at that moment. MAME is a detector (docs/validation.md): a disagreement is a question, not a verdict. python scripts/replay_mame_io.py tests/mame_traces/sms-SMSVDPTest-SMS-1.31/error.log MAME stamps each access with its instruction's *start* cycle, so ``--offset`` adds a fixed number of cycles to every stamp (the I/O cycle of ``IN A,(n)`` and ``OUT (n),A`` comes late in their 11 T-states; docs/timing.md). ``--phase`` is where MAME's cycle 0 falls in our frame, in mclocks; by default it is solved from the first V and H counter reads. """ from __future__ import annotations import argparse import sys from collections import Counter from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from sms_python.board import MACHINES, Board from sms_python.mame_log import PortAccess, read_log from sms_python.png import read_png, write_png from sms_python.vdp import ( LINE_ORIGIN, MCLOCKS_PER_CYCLE, MCLOCKS_PER_LINE, TMS9918A_RGB, v_counter_table, ) # MAME driver -> our machine (docs/mame-oracle.md, "Driver facts"). DRIVERS = { "sms": "sms2", "sms1": "sms1", "smsj": "smsj", "sg1000": "sg1000", "gamegear": "gamegear", } def port_accesses(path: Path) -> list[PortAccess]: return [event for event in read_log(path) if isinstance(event, PortAccess)] def solve_phase(accesses: list[PortAccess], offset: int) -> int: """The frame phase (mclocks) that best fits MAME's early V and H counter reads. V counter reads fix the line; the first H counter read after a TH rising edge on port $3F fixes the position within the line (HCount = (MClock - 93) / 4, with line-local m = MClock - LINE_ORIGIN; see sms_python.vdp). """ table = v_counter_table("NTSC", 192) frame = MCLOCKS_PER_LINE * len(table) v_reads = [a for a in accesses if not a.write and 0x40 <= a.port < 0x80 and not a.port & 1] v_reads = v_reads[:400] candidates = range(0, frame, MCLOCKS_PER_CYCLE) latch = _first_h_latch(accesses) if latch is not None: cycles, value = latch wanted = {(value * 4 + 93 - LINE_ORIGIN + d) % MCLOCKS_PER_LINE for d in range(4)} candidates = [ p for p in range(0, frame) if ((cycles + offset) * 3 + p) % MCLOCKS_PER_LINE in wanted ] def score(phase: int) -> int: hits = 0 for access in v_reads: mclock = (access.cycles + offset) * MCLOCKS_PER_CYCLE + phase hits += table[(mclock // MCLOCKS_PER_LINE) % len(table)] == access.value return hits if not v_reads: return _solve_phase_from_status(accesses, offset, frame) return max(candidates, key=score) def refine_phase(accesses: list[PortAccess], machine, offset: int, candidates) -> int: """Pick, among candidate phases, the one whose short no-render replay agrees most. Used when the counters cannot fix the phase (the SG-1000): status reads also carry the fifth-sprite and collision flags, whose timing a full replay does model. """ status_reads = [i for i, a in enumerate(accesses) if not a.write and a.port & 0xC1 == 0x81] prefix = accesses[: status_reads[min(60, len(status_reads) - 1)] + 1] def agreement(phase: int) -> int: board = Board(machine, cartridge=None) board.vdp.render = False results = replay(prefix, machine, offset, phase, 0, board) return sum(count for (name, ok), count in results.items() if ok is True) return max(candidates, key=agreement) def _solve_phase_from_status(accesses: list[PortAccess], offset: int, frame: int) -> int: """For machines without counters (the SG-1000): fit the frame flag's timing. Status bit 7 reads 1 exactly when the flag's set point (line 193, m = 2 after a 192-line display) fell between the previous status read and this one. """ reads = [a for a in accesses if not a.write and 0x80 <= a.port < 0xC0 and a.port & 1] reads = reads[:300] flag_at = 193 * MCLOCKS_PER_LINE + 2 def score(phase: int) -> int: hits, previous = 0, None for access in reads: now = (access.cycles + offset) * MCLOCKS_PER_CYCLE + phase if previous is not None: # Did a flag instant (flag_at + k * frame) fall in (previous, now]? crossed = (now - flag_at) // frame > (previous - flag_at) // frame hits += crossed == bool(access.value & 0x80) previous = now return hits # Every phase that fits bit 7 best, one per line: a game that polls status at a # fixed point after vblank leaves a whole window of them (Flicky: 22,619 phases). best = max(score(p) for p in range(0, frame, MCLOCKS_PER_CYCLE * 7)) fitting = [p for p in range(0, frame, MCLOCKS_PER_CYCLE) if score(p) >= best] return fitting # type: ignore[return-value] # refined by the caller def _first_h_latch(accesses: list[PortAccess]) -> tuple[int, int] | None: """(cycle of the TH write that latched it, value) for the first H counter read.""" last_th_write = None for access in accesses: if access.write and access.port < 0x40 and access.port & 1: last_th_write = access.cycles elif not access.write and 0x40 <= access.port < 0x80 and access.port & 1: return (last_th_write, access.value) if last_th_write is not None else None return None def replay( accesses: list[PortAccess], machine, offset: int, phase: int, show: int, board=None ) -> Counter: board = board or Board(machine, cartridge=None) vdp = board.vdp # Start the VDP at the solved phase: whole lines, then the remainder. lines, remainder = divmod(phase, MCLOCKS_PER_LINE) vdp.line = lines % vdp.lines_per_frame vdp.m = remainder now = 0 results: Counter = Counter() for access in accesses: when = access.cycles + offset if when > now: board.advance(when - now) now = when if access.write: board.write_port(access.port, access.value) continue name = port_name(machine, access.port) got = board.read_port(access.port) ok = got == access.value results[(name, ok)] += 1 if not ok and results[("shown", name)] < show: results[("shown", name)] += 1 print( f"{name}: MAME {access.value:02X}, board {got:02X} at cycle {access.cycles}" f" (line {vdp.line}, m {vdp.m})" ) return results def compare_frame( board: Board, snapshot: Path, save: Path | None, offset: tuple[int, int] | None = None ) -> tuple[int, int, tuple]: """Compare our last complete frame with a MAME snapshot, at the best alignment. MAME's snapshot includes some border around the active picture, so every offset that fits is tried; returns (differing pixels, total pixels, (dx, dy)). """ ours = board.vdp.visible_frame() theirs = read_png(snapshot) if save is not None: write_png(save, ours) # Compare colours, not RGB values. MAME 0.285 maps the SMS's 2-bit levels to # $00/$59/$AE/$FF where we use $00/$55/$AA/$FF, and its TMS9918A palette differs # from the one we take from the wiki: palette choices with no hardware ruling. # So SMS pixels become 2-bit levels and TMS pixels their nearest palette index. if board.machine.vdp.game_gear: normalise = _gg_levels else: normalise = _levels if board.machine.vdp.mode4 else _tms_index ours = [[normalise(p) for p in row] for row in ours] theirs = [[normalise(p) for p in row] for row in theirs] height, width = len(ours), len(ours[0]) fits = offset is not None and ( offset[1] + height <= len(theirs) and offset[0] + width <= len(theirs[0]) ) if fits: # the driver's known snapshot geometry (192-line pictures) dx, dy = offset wrong = sum( ours[y][x] != theirs[y + dy][x + dx] for y in range(height) for x in range(width) ) return wrong, height * width, (dx, dy) coarse = [] for dy in range(len(theirs) - height + 1): for dx in range(len(theirs[0]) - width + 1): wrong = 0 for y in range(0, height, 8): # a coarse pass to rank the alignments row, their_row = ours[y], theirs[y + dy] wrong += sum(row[x] != their_row[x + dx] for x in range(0, width, 4)) coarse.append((wrong, dx, dy)) if not coarse: # our picture is larger than MAME's snapshot return height * width, height * width, (0, 0) # A mostly uniform picture ties many alignments in the coarse pass, so the best # few are compared in full. best = None for _, dx, dy in sorted(coarse)[:6]: wrong = sum( ours[y][x] != theirs[y + dy][x + dx] for y in range(height) for x in range(width) ) if best is None or wrong < best[0]: best = (wrong, dx, dy) wrong, dx, dy = best return wrong, height * width, (dx, dy) def _levels(pixel: int) -> int: """RGB888 -> three 2-bit levels (the SMS's 64 colours).""" return sum(((pixel >> shift) & 0xFF) * 3 // 250 << shift for shift in (16, 8, 0)) def _gg_levels(pixel: int) -> int: """RGB888 -> three 4-bit levels (the Game Gear's 4,096 colours).""" return sum(((pixel >> shift) & 0xFF) * 15 // 250 << shift for shift in (16, 8, 0)) def _tms_index(pixel: int) -> int: """RGB888 -> the nearest TMS9918A colour (1-15; black and transparent are one).""" def distance(colour: int) -> int: return sum( (((pixel >> shift) & 0xFF) - ((colour >> shift) & 0xFF)) ** 2 for shift in (16, 8, 0) ) return min(range(1, 16), key=lambda index: distance(TMS9918A_RGB[index])) def port_name(machine, port: int) -> str: if machine.decode == "gamegear" and port <= 6: return f"GG port {port:02X}" if port < 0x40: return "open bus" if port < 0x80: return "H counter" if port & 1 else "V counter" if port < 0xC0: return "status" if port & 1 else "data" return "port DD" if port & 1 else "port DC" def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("log", type=Path) parser.add_argument("--driver", choices=sorted(DRIVERS), default="sms", help="MAME driver") parser.add_argument("--offset", type=int, default=0, help="cycles added to each stamp") parser.add_argument("--phase", type=int, help="frame phase in mclocks (default: solve)") parser.add_argument("--show", type=int, default=5, help="mismatches to print per port") parser.add_argument( "--seconds", type=float, help="MAME's -seconds_to_run: compare the exit snapshot" ) parser.add_argument("--save-frame", type=Path, help="write our last frame as a PNG") args = parser.parse_args() accesses = port_accesses(args.log) machine = MACHINES[DRIVERS[args.driver]] phase = solve_phase(accesses, args.offset) if args.phase is None else args.phase if isinstance(phase, list): # no counters: refine the fitting window by replay lines = sorted({p - p % MCLOCKS_PER_LINE for p in phase}) coarse = refine_phase(accesses, machine, args.offset, lines) phase = refine_phase( accesses, machine, args.offset, [p for p in phase if coarse <= p < coarse + 684] ) print(f"{len(accesses):,} port accesses; phase {phase} mclocks; offset {args.offset}") board = Board(machine, cartridge=None) results = replay(accesses, machine, args.offset, phase, args.show, board) failed = 0 names = sorted({name for name, ok in results if name != "shown"}) for name in names: good, bad = results[(name, True)], results[(name, False)] failed += bad print(f"{name:10} {good:>8,} agree {bad:>8,} differ") if args.seconds: clock = 3_579_545 if machine.region == "NTSC" else 3_546_893 board.advance(round(args.seconds * clock) + args.offset - board.cycles) snapshots = sorted(args.log.parent.glob("snap/*/*.png")) wrong, total, (dx, dy) = compare_frame(board, snapshots[-1], args.save_frame) print(f"frame {total - wrong:>8,} agree {wrong:>8,} differ (offset {dx},{dy})") failed += wrong return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())