"""python -m rrmd frame SRC.png OUT_DIR encode one picture (Phase 1) build FRAME_DIR ROM.bin assemble the Phase-1 player around an encoded frame verify ROM.bin FRAME_DIR run the ROM in megadrive-python, diff against expected.png """ from __future__ import annotations import argparse import subprocess import sys from pathlib import Path import numpy as np from PIL import Image from .encode import encode_frame, load_picture, measure_bands, measure_pixel_shade from .toolchain import ROOT, assemble_68k EMULATOR = ROOT.parent / "megadrive-python" EMU_PYTHON = EMULATOR / ".venv" / "Scripts" / "python.exe" TMSS_ROM = ROOT.parent / "megadrive-test-roms" / "bios" def _emulator_cmd(rom: Path, out_dir: Path, machine: str) -> list[str]: cmd = [str(EMU_PYTHON), str(EMULATOR / "scripts" / "board_frames.py"), str(rom), str(out_dir), "--machine", machine] tmss = sorted(TMSS_ROM.glob("*.zip")) + sorted(TMSS_ROM.glob("*.bin")) if TMSS_ROM.exists() else [] if machine in ("nuked-md", "genesis-tmss", "megadrive-tmss") and tmss: cmd += ["--tmss-rom", str(tmss[0])] print(f"TMSS boot ROM: {tmss[0].name}") return cmd def verify_clip(rom: Path, out: Path, machine: str, hw_frames: int | None, audio: bool = False, recheck: bool = False) -> int: # fmt: skip """Run the streaming ROM, then check every hardware frame shows some expected video frame, that the video frames appear in order, each for at least one hardware frame, and that none is skipped. With ``audio``, also capture the FM output and check the DAC stream against the ROM's sample data.""" import hashlib expected_paths = sorted((out / "expected").glob("e*.png")) n_video = len(expected_paths) if hw_frames is None: hw_frames = 2 * n_video + 8 actual_dir = out / "actual" cmd = _emulator_cmd(rom, actual_dir, machine) + ["--range", f"1:{hw_frames}:1"] if audio: cmd += ["--fm", "--audio", str(out / "audio_capture")] if not recheck: subprocess.run(cmd, check=True) def digest(path: Path) -> str: return hashlib.sha256(np.asarray(Image.open(path).convert("RGB")).tobytes()).hexdigest() # Identical consecutive expected frames (static shots) share a digest: resolve # each hardware frame to the lowest candidate not before the frame last shown, # so the run is attributed in order instead of all to one index. candidates: dict[str, list[int]] = {} for i, p in enumerate(expected_paths): candidates.setdefault(digest(p), []).append(i) blank = hashlib.sha256(np.zeros((224, 320, 3), np.uint8).tobytes()).hexdigest() seen: list[int] = [] hw_of: list[int] = [] unknown = 0 first_hw: dict[int, int] = {} last = -1 for hw in range(1, hw_frames + 1): p = actual_dir / f"f{hw:05d}.png" if not p.exists(): continue hw_of.append(hw) d = digest(p) if d == blank: seen.append(-1) continue if d not in candidates: unknown += 1 seen.append(-2) continue cs = candidates[d] if last in cs and hw - first_hw[last] < 2: v = last elif last in cs: v = next((c for c in cs if c > last), cs[-1]) else: v = next((c for c in cs if c >= last), cs[-1]) seen.append(v) first_hw.setdefault(v, hw) last = v shown = [v for v in seen if v >= 0] in_order = all(b >= a for a, b in zip(shown, shown[1:])) # the run's last two hardware frames may legitimately cut the final video frame off skipped = [v for v in range(n_video) if v not in first_hw and not (v == n_video - 1 and hw_frames <= 2 * n_video + 8)] runs: dict[int, int] = {} for v in shown: runs[v] = runs.get(v, 0) + 1 durations = sorted(set(runs.values())) print(f"{len(seen)} hardware frames: {unknown} unknown, {seen.count(-1)} blank, " f"{len(first_hw)} of {n_video} video frames shown, in order: {in_order}, skipped: {skipped[:10]}") print(f"hardware frames per video frame: {durations}; video frame 0 first at hw {first_hw.get(0)}") print("sequence: " + " ".join(f"{hw}:{'B' if v == -1 else '?' if v == -2 else v}" for hw, v in zip(hw_of, seen))) ok = unknown == 0 and in_order and not skipped if audio: ok = check_audio(out, machine) and ok print("PASS" if ok else "FAIL") return 0 if ok else 1 def check_audio(out: Path, machine: str) -> bool: """The DAC stream in the FM capture against the ROM's samples, compared in FM time: sample i is expected to hold for FM periods 3i..3i+2 from the stream start. Each captured period must equal the prediction within +-1 period (the driver's timing jitter), so equal neighbouring samples - normal in real music - need no run decoding. The start is found by alignment search. Exact values on YM3438 machines; on the MD1 the ladder DAC is nonlinear, so compare sign of change only.""" raw = np.frombuffer((out / "audio_capture" / "fm.bin").read_bytes(), dtype=" np.ndarray: # A period is fine if it shows the predicted sample, or one the driver would # show when a write is late by up to LATE periods (each 68000 bus hold - three # per video frame - delays one sample by up to ~40 us = 2 periods; nothing # accumulates), or early by one (spin-exit granularity). A DAC write landing # inside a sample's three channel-6 slots gives a one-period value between the # old and new levels (the chip really does this); accept any value between the # predictions it could be blending. LATE = 2 ok = seg == p for k in range(1, LATE + 1): ok |= np.concatenate([np.zeros(k, bool), seg[k:] == p[:-k]]) ok |= np.concatenate([seg[:-1] == p[1:], [False]]) lo = p.copy() hi = p.copy() for k in range(-LATE, 2): lo = np.minimum(lo, np.roll(p, k)) hi = np.maximum(hi, np.roll(p, k)) return ok | ((seg >= lo) & (seg <= hi)) # The stream starts after the silence before V_RUN (within the first second, or # some four seconds in behind a TMSS boot ROM's splash); search every alignment there. probe = min(6000, len(pred)) best = (-1, 0) for o in range(0, min(len(raw) - probe, 300000)): score = int((raw[o : o + probe] == pred[:probe]).sum()) # exact: keeps "on time" meaningful if score > best[0]: best = (score, o) o = best[1] n = min(len(pred), len(raw) - o - 1) seg = raw[o : o + n] p = pred[:n] match = tolerant(seg, p) ok_exact = seg == p bad = np.flatnonzero(~match) n_samples = n // 3 print(f"audio: stream aligned at FM period {o}; {n_samples} samples ({n_samples / 17594:.2f} s) compared in FM time") print(f"audio: periods matching within the driver's jitter (-1..+2 periods): {n - len(bad)} of {n} ({100 * (n - len(bad)) / n:.3f}%); " f"exactly on time: {100 * ok_exact.mean():.1f}%") # Drift: the exact-match lag of a window near the end against one near the start. # Lost timer overflows (4 samples each) show up here; isolated late samples do not. def lag_at(t: int, w: int = 3000) -> int: scores = [int((raw[o + t + k : o + t + k + w] == pred[t : t + w]).sum()) for k in range(-30, 31)] best = max(scores) return min((k for k in range(-30, 31) if scores[k + 30] == best), key=abs) # ties: nearest zero end = n - 6000 while end > 12000 and pred[end : end + 3000].std() == 0: # the silent tail cannot be aligned end -= 3000 drift = lag_at(end) - lag_at(3000) if n > 12000 else 0 print(f"audio: drift over the clip {drift:+d} FM periods ({drift / 3:+.1f} samples)") if len(bad): # Group the bad periods into events and report the longest events = np.split(bad, np.flatnonzero(np.diff(bad) > 3) + 1) longest = max(len(e) for e in events) print(f"audio: {len(events)} glitch events, longest {longest} periods; first at FM {bad[0]} " f"(sample {bad[0] // 3}), raw {seg[bad[0]]} expected {p[bad[0]]}") # Known residuals: ~3 bus holds per video frame delay one sample by up to 2 # periods (inside the tolerance) and each 32 KB bank switch delays two samples # by ~6 periods, recovered within ~50 samples (outside it): ~0.1 % of periods. return abs(drift) <= 2 and len(bad) <= 0.002 * n def verify(rom: Path, frame_dir: Path, frame: int, machine: str) -> int: actual_dir = frame_dir / "actual" cmd = _emulator_cmd(rom, actual_dir, machine) + ["--frames", str(frame)] subprocess.run(cmd, check=True) actual = np.asarray(Image.open(actual_dir / f"f{frame:05d}.png").convert("RGB")) expected = np.asarray(Image.open(frame_dir / "expected.png").convert("RGB")) if actual.shape != expected.shape: print(f"SHAPE MISMATCH: emulator {actual.shape} vs expected {expected.shape}") return 1 diff = np.any(actual != expected, axis=-1) n = int(diff.sum()) print(f"frame {frame} on {machine}: {n} of {diff.size} pixels differ") if n: ys, xs = np.nonzero(diff) print(f" bounding box x {xs.min()}-{xs.max()}, y {ys.min()}-{ys.max()}") y, x = ys[0], xs[0] print(f" first: ({x},{y}) emulator {actual[y, x].tolist()} expected {expected[y, x].tolist()}") Image.fromarray((diff * 255).astype(np.uint8)).save(frame_dir / "diff.png") return 1 if n else 0 def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="rrmd", description=__doc__) sub = parser.add_subparsers(dest="cmd", required=True) p_frame = sub.add_parser("frame") p_frame.add_argument("src", type=Path) p_frame.add_argument("out", type=Path) p_build = sub.add_parser("build") p_build.add_argument("frame_dir", type=Path) p_build.add_argument("rom", type=Path) p_verify = sub.add_parser("verify") p_verify.add_argument("rom", type=Path) p_verify.add_argument("frame_dir", type=Path) p_verify.add_argument("--frame", type=int, default=12) p_verify.add_argument("--machine", default="megadrive", help="the ROM is timed for a PAL Mega Drive 2 and check_audio only " "compares DAC values exactly on megadrive2-class machines, but the " "default stays on megadrive while the early-Model-1 freeze is open " "(PLAN phase 5): that is the machine that shows it") # fmt: skip p_bands = sub.add_parser("measure-bands") p_bands.add_argument("src", type=Path, nargs="+") p_shade = sub.add_parser("measure-pixel-shade") p_shade.add_argument("src", type=Path, nargs="+") p_clip = sub.add_parser("encode-clip") p_clip.add_argument("fields", type=Path) p_clip.add_argument("out", type=Path) p_clip.add_argument("--limit", type=int) p_clip.add_argument("--first", type=int, default=0, help="start at this source frame (codebook encoder only)") p_clip.add_argument("--codebook", action="store_true", help="ROM-side tile store (rrmd.codebook)") p_clip.add_argument("--tols", type=float, nargs=3, metavar=("KEEP", "REUSE", "ROM"), help="per-pixel luma-weighted error slack for keep / VRAM reuse / ROM reuse") # fmt: skip p_clip.add_argument("--target-frame-bytes", type=float, help="rate control: steer tolerances to this many ROM bytes per video frame") # fmt: skip p_clip.add_argument("--rate-floor", type=float, default=0.25, help="lowest tolerance multiplier the rate controller may ask for (default 0.25)") # fmt: skip p_clip.add_argument("--roi", type=Path, help="tools/face_track.py output: tighten tolerances inside face regions") # fmt: skip p_clip.add_argument("--roi-weights", type=float, nargs=3, metavar=("FACE", "EDGE", "BG"), help="tolerance multipliers inside a face box, at its edge, and elsewhere") # fmt: skip p_clip.add_argument("--saturation", type=float, default=1.0, help="push the source's chroma about luma before encoding (1.0 = as is)") # fmt: skip p_clip.add_argument("--denoise", type=float, nargs=2, metavar=("THRESHOLD", "BLEND"), help="temporal denoise: per-channel still threshold (0-255) and blend toward previous (0-1)") # fmt: skip p_bs = sub.add_parser("build-stream") p_bs.add_argument("out", type=Path) p_bs.add_argument("rom", type=Path) p_bs.add_argument("--codebook", action="store_true") p_bs.add_argument("--audio", type=Path, help="mono u8 samples at --audio-rate (resampled to the console's frame-locked rate)") p_bs.add_argument("--audio-rate", type=float, default=17594.0) p_bs.add_argument("--audio-tone", action="store_true", help="synthetic test tone instead of a file") p_bs.add_argument("--audio-skip", type=float, default=0.0, help="seconds of the audio file before the clip's first frame (clip start in stream time minus the audio stream's start)") # fmt: skip p_bs.add_argument("--audio-length", type=float, help="seconds of audio to include (default: all)") p_lay = sub.add_parser("layout") p_lay.add_argument("out", type=Path) p_vc = sub.add_parser("verify-clip") p_vc.add_argument("rom", type=Path) p_vc.add_argument("out", type=Path) p_vc.add_argument("--machine", default="megadrive", help="see verify --machine") p_vc.add_argument("--hw-frames", type=int, help="hardware frames to run (default: 2 per video frame + 8)") p_vc.add_argument("--audio", action="store_true", help="also capture and check the DAC stream") p_vc.add_argument("--recheck", action="store_true", help="re-score the existing actual/ and audio_capture/ without running the emulator") args = parser.parse_args(argv) if args.cmd == "encode-clip": paths = sorted(args.fields.glob("f*.png")) if args.codebook: import pickle from .codebook import encode_clip as encode_clip2 from .rom import write_layout2 encode_clip2(paths, args.out, args.limit, tuple(args.tols) if args.tols else None, args.target_frame_bytes, tuple(args.denoise) if args.denoise else None, args.rate_floor, args.roi, args.saturation, tuple(args.roi_weights) if args.roi_weights else None, args.first) # fmt: skip with (args.out / "records2.pkl").open("rb") as f: records, store = pickle.load(f) print(write_layout2(records, store, args.out)) return 0 from .rom import write_layout from .stream import encode_clip records = encode_clip(paths, args.out, args.limit) print(write_layout(records, args.out)) return 0 if args.cmd == "layout": import pickle from .rom import write_layout, write_layout2 if (args.out / "records2.pkl").exists(): with (args.out / "records2.pkl").open("rb") as f: records, store = pickle.load(f) print(write_layout2(records, store, args.out)) return 0 with (args.out / "records.pkl").open("rb") as f: records = pickle.load(f) print(write_layout(records, args.out)) return 0 if args.cmd == "build-stream": defines = {"CODEBOOK": int(args.codebook), "AUDIO": 0} if args.audio or args.audio_tone: from .audio import SAMPLES_PER_VIDEO_FRAME, prepare_audio info = prepare_audio(args.out, args.audio, args.audio_rate, args.audio_tone, args.audio_skip, args.audio_length) defines.update({"AUDIO": 1, "AUDIO_PAGE": info["page"], "AUDIO_SPF_FP": int(round(SAMPLES_PER_VIDEO_FRAME * 65536))}) # fmt: skip print(info) assemble_68k(ROOT / "player" / "stream.s", args.rom, listing=args.rom.with_suffix(".lst"), include_dirs=(args.out,), defines=defines) # fmt: skip from .rom import finalize_header print(f"{args.rom}: {args.rom.stat().st_size:,} bytes") print(f"header: {finalize_header(args.rom)}") return 0 if args.cmd == "verify-clip": return verify_clip(args.rom, args.out, args.machine, args.hw_frames, args.audio, args.recheck) if args.cmd == "measure-pixel-shade": for src in args.src: base, three, two = measure_pixel_shade(load_picture(src)) print(f"{src.name}: per-cell shade {base:6.1f} per-pixel 3-level {three:6.1f} " f"({100 * (1 - three / base):4.1f}% lower) per-pixel normal/highlight only {two:6.1f} " f"({100 * (1 - two / base):4.1f}% lower)") return 0 if args.cmd == "measure-bands": for src in args.src: result = measure_bands(load_picture(src)) base = result[1] print(src.name + ": " + " ".join( f"{n} band{'s' if n > 1 else ''}: {e:6.1f} ({100 * (1 - e / base):4.1f}% lower)" for n, e in result.items() )) return 0 if args.cmd == "frame": assets = encode_frame(load_picture(args.src)) assets.write(args.out) for key, value in assets.stats.items(): print(f"{key}: {value}") elif args.cmd == "build": assemble_68k(ROOT / "player" / "main.s", args.rom, listing=args.rom.with_suffix(".lst"), include_dirs=(args.frame_dir,)) # fmt: skip print(f"{args.rom}: {args.rom.stat().st_size:,} bytes") elif args.cmd == "verify": return verify(args.rom, args.frame_dir, args.frame, args.machine) return 0 if __name__ == "__main__": sys.exit(main())