"""Phase-3 check: every emulator frame is one of the encoder's expected pictures, shown in order, each for two fields. Frames are compared at the 5-bit level (value >> 3), so BlastEm's `v << 3` and sega32x-python's `v << 3 | v >> 2` both compare exactly. py -3.12 -m r32x.verify_run out32/c1v_0 out32/c1v_0/run --pattern "f{:05d}-32x.png" py -3.12 -m r32x.verify_run out32/c1v_0 out32/c1v_0/blastem --pattern "f{:05d}.png" """ from __future__ import annotations import argparse import hashlib import json from collections import Counter from pathlib import Path import numpy as np from PIL import Image def key(img: np.ndarray) -> str: if img.shape[0] == 240: img = img[8:232] return hashlib.sha1((img[..., :3] >> 3).astype(np.uint8).tobytes()).hexdigest() def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("enc", type=Path) ap.add_argument("frames", type=Path) ap.add_argument("--pattern", default="f{:05d}-32x.png") a = ap.parse_args() s = json.loads((a.enc / "summary.json").read_text()) first, count = s["first"], s["count"] step, width = s.get("step", 1), s.get("width", 320) x0 = (320 - width) // 2 lookup: dict[str, int] = {} for n in range(count): i = first + n * step e = np.asarray(Image.open(a.enc / "expected" / f"e{i:05d}.png").convert("RGB")) if width != 320: # the 32X shows a narrower picture centred, black borders e = np.pad(e, ((0, 0), (x0, 320 - width - x0), (0, 0))) lookup.setdefault(key(e), n) # video frame index within the stream shown: list[int | None] = [] hw = 0 while not (a.frames / a.pattern.format(hw)).exists() and hw < 10: hw += 1 # the runners start numbering at 0, 1 or 2 start_hw = hw while True: p = a.frames / a.pattern.format(hw) if not p.exists(): break shown.append(lookup.get(key(np.asarray(Image.open(p).convert("RGB"))))) hw += 1 known = [(h, v) for h, v in enumerate(shown) if v is not None] if not known: print(f"{len(shown)} frames read, none is an expected picture") return start = known[0][0] tail = shown[start:] unknown_in_play = sum(v is None for v in tail[: max(i for i, v in enumerate(tail) if v is not None) + 1]) runs: list[tuple[int, int]] = [] for v in tail: if v is None: continue if runs and runs[-1][0] == v: runs[-1] = (v, runs[-1][1] + 1) else: runs.append((v, 1)) seq = [v for v, _ in runs] in_order = all(b == a_ + 1 for a_, b in zip(seq, seq[1:])) distinct = len(set(seq)) durations = Counter(n for _, n in runs[:-1]) # the last frame is held for ever print(f"first picture at hw frame {start + start_hw}; {distinct} of {count} video frames seen " f"({seq[0]}..{seq[-1]}), in order: {in_order}, unknown frames during play: {unknown_in_play}") print(f"fields per video frame (last one excluded): {dict(sorted(durations.items()))}") if not in_order: bad = [(x, y) for x, y in zip(seq, seq[1:]) if y != x + 1][:10] print("out-of-order steps:", bad) if __name__ == "__main__": main()