#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 3 gate: the display's line and frame structure against the Lynx II captures. For each ``lynx2-mikey-refresh_rate-T0_PBKUP_T2.dsl`` capture (tier 1, a console recorded at 100 MHz; decoded by our own ``scripts/dsl.py``) measure, in 16 MHz ticks (CLK rising edges): - the line period (HSYNC fall to fall) and frame period (VSYNC fall to fall); - the LCD transfer window of a line: first to last ``CLK 1`` edge after HSYNC; - display DMA bursts per frame (RAS pulses with 4 CAS falls, paired; LT: ten 8-byte fetches per visible line). and compare with this board run at the same Timer 0 / PBKUP / Timer 2 setting (display DMA on, the CPU in a two-instruction loop). python -I scripts/m3_display.py [--jobs 3] [--limit N] """ from __future__ import annotations import argparse import bisect import collections import os import re import statistics import sys from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from dsl import lows, open_capture CAPTURES = ROOT / "reference" / "src" / "gearlynx" / "tests" / "logic-analyzer" def rising(capture, name): first, changes = capture.edges(name) level, out = first, [] for at in changes: level ^= 1 if level: out.append(at) return out def measure_capture(path: Path) -> dict: cap = open_capture(path) clk = rising(cap, "CLK") def tick(sample): return bisect.bisect_left(clk, sample) hs = [tick(s) for s, _e in lows(cap, "HSYNC")] vs = [tick(s) for s, _e in lows(cap, "VSYNC")] line = statistics.median(b - a for a, b in zip(hs, hs[1:], strict=False)) frame = statistics.median(b - a for a, b in zip(vs, vs[1:], strict=False)) if len(vs) > 2 else 0 c1 = [tick(s) for s in rising(cap, "CLK 1")] windows = [] for a, b in zip(hs, hs[1:], strict=False): i, j = bisect.bisect_left(c1, a), bisect.bisect_left(c1, b) if j - i > 10: windows.append(c1[j - 1] - c1[i]) ras = lows(cap, "RAS") cas = [s for s, _e in lows(cap, "CAS")] fours = [ tick(s) for s, e in ras if bisect.bisect_left(cas, e) - bisect.bisect_left(cas, s) == 4 ] bursts = 0 if len(vs) > 2: lo, hi = bisect.bisect_left(fours, vs[1]), bisect.bisect_left(fours, vs[2]) # Two 4-CAS pulses 14 ticks apart make one 8-byte fetch. k = lo while k < hi: if k + 1 < hi and fours[k + 1] - fours[k] <= 20: bursts += 1 k += 2 else: k += 1 return {"line": line, "frame": frame, "window": statistics.median(windows) if windows else 0, "bursts": bursts} # fmt: skip def _seed_fault() -> None: """LYNX_FAULT=reload-plus-one: a reloading timer reloads BKUP + 1 (a one-line fault).""" if os.environ.get("LYNX_FAULT") != "reload-plus-one": return from lynx_python.mikey import timers original = timers.TimerBank.clock def clock(self, timer, when, forced=False): was = timer.count original(self, timer, when, forced) if was == 0 and timer.ctla & 0x10 and timer.count == timer.backup: timer.count = (timer.backup + 1) & 0xFF timers.TimerBank.clock = clock def measure_board(t0: int, pbkup: int, t2: int) -> dict: from lynx_python.board import Lynx _seed_fault() board = Lynx() ram = board.ram ram[0x0200:0x0203] = bytes((0x4C, 0x00, 0x02)) # JMP $0200 ram[0xFFFC], ram[0xFFFD] = 0x00, 0x02 board.mapctl = 0x0F # vectors from RAM (no boot ROM here) mikey = board.mikey for address, value in ((0xFD00, t0), (0xFD02, t0), (0xFD08, t2), (0xFD0A, t2), (0xFD93, pbkup), (0xFD95, 0x20), (0xFD92, 0x0D), (0xFD09, 0x1F), (0xFD01, 0x18)): # fmt: skip mikey.write(address, value) lines, frames, dma = [], [], [] display = mikey.display line_borrow, frame_borrow = display.line_borrow, display.frame_borrow def on_line(when): lines.append(when) before = len(display.dma_times) line_borrow(when) dma.extend(display.dma_times[before:]) def on_frame(when): frames.append(when) frame_borrow(when) mikey.display = type("Hook", (), {})() hook = mikey.display hook.line_borrow, hook.frame_borrow = on_line, on_frame hook.dma_times = display.dma_times board.reset() board.run_ticks(16 * (t0 + 1) * (t2 + 1) * 4) line = statistics.median(b - a for a, b in zip(lines, lines[1:], strict=False)) frame = statistics.median(b - a for a, b in zip(frames, frames[1:], strict=False)) per_frame = sum(1 for t in dma if frames[1] <= t < frames[2]) return {"line": line, "frame": frame, "window": 1920 - 192 + 1, "bursts": per_frame} def job(path: Path) -> tuple[str, dict, dict]: t0, pbkup, t2 = (int(v) for v in re.search(r"(\d+)_(\d+)_(\d+)\.dsl$", path.name).groups()) empty = {"line": -1, "frame": -1, "window": -1, "bursts": -1} try: la = measure_capture(path) except statistics.StatisticsError: la = empty # too few HSYNC/VSYNC edges in the capture to measure try: ours = measure_board(t0, pbkup, t2) except statistics.StatisticsError: ours = empty return path.name, la, ours TITLES = { "lemmings-50hz": "Lemmings (", "batman-75hz": "Batman Returns (", "kracy_ace-52hz": "Krazy Ace - Miniature Golf (", "crystal_mines-60hz": "Crystal Mines II (", } def title_job(item: tuple[str, str]) -> str: """Frame period of a title: the capture's VSYNC against this board running the cart.""" from lynx_python import bootrom, romsets from lynx_python.board import Lynx from lynx_python.cart import load tag, title = item la = measure_capture(CAPTURES / f"lynx2-mikey-{tag}.dsl") cart = romsets.find_cart(title) if cart is None: return f"{tag}: capture frame {la['frame']:.0f} ticks; cart not found under $NO_INTRO_DIR" description = load(cart) board = Lynx(description.payload, description.bank0_block, boot_rom=bootrom.find()) board.reset() periods = [] display = board.mikey.display # The titles' loaders run 7-14 emulated seconds before setting their own timers. for _second in range(16): board.run_ticks(16_000_000) periods.append(display.frame_period) if abs(display.frame_period - la["frame"]) <= 1 and periods[0] != display.frame_period: break verdict = "agrees" if abs(periods[-1] - la["frame"]) <= 1 else "DIFFERS" return (f"{tag}: capture frame {la['frame']:.0f} ticks (line {la['line']:.0f}); ours after " f"1..{len(periods)} s: {periods}: {verdict}") # fmt: skip def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=3) parser.add_argument("--limit", type=int) parser.add_argument("--titles", action="store_true", help="the four titles' frame periods") args = parser.parse_args() if args.titles: with ProcessPoolExecutor(args.jobs) as pool: for line in pool.map(title_job, TITLES.items()): print(line) return 0 paths = sorted(CAPTURES.glob("lynx2-mikey-refresh_rate-*.dsl"))[: args.limit] agree = collections.Counter() with ProcessPoolExecutor(args.jobs) as pool: for name, la, ours in pool.map(job, paths): # The 4-CAS pulse pairs mix display fetches with the CPU's own page-mode runs # (about 30 per line in these captures), so "bursts" is reported, not judged. same = {k: abs(la[k] - ours[k]) <= 1 for k in ("line", "frame")} agree.update(k for k, v in same.items() if v) print(f"{name[25:-4]}: line LA {la['line']:.0f} / ours {ours['line']:.0f}; " f"frame LA {la['frame']:.0f} / ours {ours['frame']:.0f}; " f"LCD clock window LA {la['window']:.0f}; " f"4-CAS pairs per frame LA {la['bursts']} / our fetches {ours['bursts']}") # fmt: skip print(f"{len(paths)} captures; agree within 1 tick: " + ", ".join(f"{k} {agree[k]}" for k in ("line", "frame"))) # fmt: skip return 0 if __name__ == "__main__": sys.exit(main())