#!/usr/bin/env python3 """Replay a MAME VDP port log (docs/mame-oracle.md) into the core and compare. MAME is a detector here (tier 5), never a judge. What is compared: - the final VRAM against MAME's ``vram.bin``; - every status and data read against the value MAME's log recorded; - the picture against MAME's last snapshot (``snap//0000.png``), by colour through MAME's own palette (which draws colours 0 and 1 the same black). Time: each log line carries MAME's beam position (``beamy``, ``beamx``) at the access and the Z80's ``totalcycles``. The beam gives the position inside a frame; ``totalcycles`` (1.5 pixel clocks each: the Z80 runs at XTAL/3) unwraps frames. MAME's line 0 is the first after vertical sync, its active picture lines 40-231 and pixels 37-292; the core's line 0 is the first active line and pixel x is shown at dot x + 10. So MAME (y, x) is core (y - 40, x - 27). python -I validation/mame_replay.py tests/mame_traces/sg1000-Flicky [--windows] """ from __future__ import annotations import argparse import sys from dataclasses import dataclass, field from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "validation")) try: # the package under test (validation/faults.py puts a broken copy first) import tms9918_python # noqa: F401 except ImportError: sys.path.insert(0, str(ROOT / "src")) from png import read_png # noqa: E402 from tms9918_python import TMS9918, TMS9918A, TMS9928A, TMS9929A, Frame # noqa: E402 DOTS = 342 MAME_ACTIVE_LEFT = 2 + 14 + 8 + 13 # HORZ_DISPLAY_START CORE_DISPLAY_START = 10 # tables.DISPLAY_START_DOT Z80_HZ = 3_579_545 MAME_BORDER = 12 # the snapshot's border around the 256 x 192 picture #: MAME 0.285 tms9928a.cpp's palette (R. Nabet): colour index -> RGB. #: Taken from MAME src/devices/video/tms9928a.cpp, BSD-3-Clause, copyright-holders: #: Sean Young, Nathan Woods, Aaron Giles, Wilbert Pol, hap (the file's header). Used #: here only to map MAME's snapshots back to colour indices. MAME_PALETTE = ( (0, 0, 0), (0, 0, 0), (33, 200, 66), (94, 220, 120), (84, 85, 237), (125, 118, 252), (212, 82, 77), (66, 235, 245), (252, 85, 84), (255, 121, 120), (212, 193, 84), (230, 206, 128), (33, 176, 59), (201, 91, 186), (204, 204, 204), (255, 255, 255), ) # fmt: skip DRIVERS = {"coleco": TMS9928A, "colecop": TMS9929A, "sg1000": TMS9918A} @dataclass class Event: time: int # master clocks from the core's power-on (line 0, dot 0) write: bool mode: int value: int line: int # MAME's log line number, for messages @dataclass class Result: run: str events: int = 0 status_reads: int = 0 status_differ: list = field(default_factory=list) data_reads: int = 0 data_differ: list = field(default_factory=list) vram_differ: int = -1 frame_pixels_differ: int = -1 frame_number: int = -1 frame_candidates: dict = field(default_factory=dict) lost_accesses: int = 0 lost_lines: list = field(default_factory=list) # log lines whose access replaced one end_time: int = 0 end_line: int = -1 frame_differ_at: list = field(default_factory=list) def parse_log(run: Path, variant=TMS9928A) -> tuple[list[Event], int]: """Events in core time, and the core time at which MAME stopped. MAME's line 0 is the first after vertical sync; the core's first active line comes ``top_blanking + top_border`` lines later (13 + 27 NTSC; 13 + 51 PAL, as MAME's ``VERT_DISPLAY_START_PAL``).""" frame = DOTS * variant.lines active_top = variant.layout.top_blanking + variant.layout.top_border raw = (run / "error.log").read_bytes().decode("latin-1").splitlines() rows = [] for number, text in enumerate(raw, 1): parts = text.split() if len(parts) != 6 or parts[0] not in ("W", "R"): continue kind, port, data, tc, by, bx = parts rows.append((kind == "W", int(port, 16), int(data, 16), int(tc), int(by), int(bx), number)) if not rows: raise ValueError(f"{run}: no accesses in error.log") # MAME pixel position, unwrapped with totalcycles (1.5 pixel clocks a Z80 clock). first = rows[0] k = first[4] * DOTS + first[5] - first[3] * 1.5 absolute = [] for write, port, data, tc, by, bx, number in rows: pos = by * DOTS + bx approx = tc * 1.5 + k n = round((approx - pos) / frame) absolute.append((pos + n * frame, write, port, data, number)) shift = active_top * DOTS + (MAME_ACTIVE_LEFT - CORE_DISPLAY_START) # The core powers on at the start of the frame in which MAME's soft reset happened # (totalcycles 0), so it lives through the same frame flags MAME's chip did before # the first logged access (Flicky's first access comes 0.96 s after the reset). origin = int((k - shift) // frame) * frame events = [ Event((pos - shift - origin) * 2, write, port & 1, data, number) for pos, write, port, data, number in absolute ] seconds = int((run / "summary.txt").read_text().split(" s emulated")[0].split()[-1]) end = round((seconds * Z80_HZ * 1.5 + k - shift - origin) * 2) return events, end def reset_time(run: Path, variant=TMS9928A) -> int: """Core time of MAME's soft reset (totalcycles 0), from the first logged access.""" events, end = parse_log(run, variant) first_tc = None for text in (run / "error.log").read_bytes().decode("latin-1").splitlines(): parts = text.split() if len(parts) == 6 and parts[0] in ("W", "R"): first_tc = int(parts[3]) break return max(0, events[0].time - round(first_tc * 3)) def driver_of(run: Path) -> str: """The MAME driver, from summary.txt's first line ("MAME 0.285 (...), coleco (...)").""" return (run / "summary.txt").read_text().split(",")[1].split()[0] def replay(run: Path, **chip_options) -> Result: run = Path(run) variant = DRIVERS[driver_of(run)] events, end = parse_log(run, variant) options = {"windows": False} | chip_options vdp = TMS9918(variant, **options) result = Result(run=run.name, events=len(events), end_time=end) frames = {} # MAME's soft reset (before the first logged access) cleared its status flags. The # log cannot place the reset's effect on the counters, so the replay applies only # the flags' part (TI 2.3.1-2.3.3: F, C, 5S cleared by reset) at that moment. now = reset_time(run, variant) vdp.run(now) vdp.status &= 0x1F for event in events: if event.time < now: raise ValueError(f"log line {event.line} goes back in time") vdp.run(event.time - now) now = event.time frame = vdp.take_frame() if frame is not None: frames[frame.number] = frame for old in [n for n in frames if n < frame.number - 2]: del frames[old] if event.write: lost = vdp.lost_accesses vdp.write(event.mode, event.value) if vdp.lost_accesses != lost: result.lost_lines.append(event.line) else: ours = vdp.read(event.mode) if event.mode: result.status_reads += 1 if ours != event.value: result.status_differ.append((event.line, vdp.line, vdp.dot, event.value, ours)) else: result.data_reads += 1 if ours != event.value: result.data_differ.append((event.line, event.value, ours)) # MAME stops at the first vertical blank (its line 244, the core's 204) after the # emulated seconds are up, which can be after the estimate from totalcycles; the # snapshot is taken there. vdp.run(max(0, end - now)) frame_len = variant.lines * DOTS * 2 here = vdp.line * DOTS * 2 + vdp.slot * 4 + vdp._phase vdp.run((204 * DOTS * 2 - here) % frame_len) result.end_time = vdp.clock + vdp._phase frame = vdp.take_frame() if frame is not None: frames[frame.number] = frame result.lost_accesses = vdp.lost_accesses mame_vram = (run / "vram.bin").read_bytes() result.vram_differ = sum(1 for a, b in zip(vdp.vram, mame_vram) if a != b) # The snapshot MAME saves as it stops is its line buffer at that moment: the lines of # the frame in progress drawn so far, the previous frame's below them. The core's # equivalent is its rows as they stand at the end time. The finished frames are # compared too, for information. snap = next((run / "snap").rglob("0000.png"), None) if snap is not None: _, _, rgb = read_png(snap) for number, f in frames.items(): result.frame_candidates[number] = len(compare_picture(f, rgb)) current = Frame(tuple(vdp._rows), (), vdp.frame_count) result.frame_differ_at = compare_picture(current, rgb) result.frame_pixels_differ = len(result.frame_differ_at) result.frame_number = vdp.frame_count result.end_line = vdp.line return result #: Switches that turn one named decision into MAME's behaviour, for attribution. MAME_SIDE = { "C7": {"offscreen_collisions": False}, "C10": {"flag_dot": (193, 10)}, "U4": {"power_on_status": 0x1F}, } def attribute(run: Path, **base) -> dict[str, int]: """Status reads differing from MAME's: with the core's defaults, with each named decision switched to MAME's side, and with all of them switched.""" counts = {"default": len(replay(run, **base).status_differ)} for name, switch in MAME_SIDE.items(): counts[name] = len(replay(run, **base, **switch).status_differ) every = {k: v for switch in MAME_SIDE.values() for k, v in switch.items()} counts["all"] = len(replay(run, **base, **every).status_differ) return counts def compare_picture(frame, rgb) -> list[tuple[int, int, int, tuple]]: """(y, x, core index, MAME RGB) where the colour (through MAME's palette) differs.""" differ = [] for y in range(192): row = frame.pixels[y] mame = rgb[y + MAME_BORDER] for x in range(256): if MAME_PALETTE[row[x]] != mame[x + MAME_BORDER]: differ.append((y, x, row[x], mame[x + MAME_BORDER])) return differ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("runs", nargs="+", type=Path) parser.add_argument("--windows", action="store_true", help="access windows on") parser.add_argument("--mame-like", action="store_true", help="C7, C10, C11, U4 switched to MAME's behaviour") # fmt: skip args = parser.parse_args() options = {"windows": args.windows} if args.mame_like: options |= {"roll_over_4k": False, "mux_4k": False, "offscreen_collisions": False, "flag_dot": (193, 10), "power_on_status": 0x1F} # fmt: skip for run in args.runs: r = replay(run, **options) print(f"{r.run}: {r.events} accesses, end at {r.end_time} master clocks") print(f" VRAM bytes differing from vram.bin: {r.vram_differ}") print(f" status reads: {r.status_reads}, differing: {len(r.status_differ)}") for d in r.status_differ[:10]: print( f" log line {d[0]}: core line {d[1]} dot {d[2]}: MAME {d[3]:02X} core {d[4]:02X}" ) print(f" data reads: {r.data_reads}, differing: {len(r.data_differ)}") print(f" lost accesses: {r.lost_accesses} (at log lines {r.lost_lines[:20]})") print(f" snapshot vs the rows at the end (frame {r.frame_number}, line {r.end_line}): " f"{r.frame_pixels_differ} pixels differ {r.frame_differ_at[:6]}") # fmt: skip print(f" finished frames for comparison: {r.frame_candidates}") return 0 if __name__ == "__main__": sys.exit(main())