"""Tile-codebook video encoder prototype: a short segment only, to get real bytes-per-frame numbers for the Mega Drive budget instead of estimates. Pipeline: extract one field per source frame (top field, matching the source's top-field-first order, so no deinterlace/combing step is needed) -> downscale to the board's target resolution -> quantize to one 16-colour Genesis-style palette shared across the whole segment -> split into 8x8 tiles -> deduplicate into a codebook (exact-match only; true vector quantization would compress further, so this is a conservative baseline) -> report codebook size, per-frame changed-cell counts, and both a "resend the whole name table every frame" and a "delta only" size estimate. Reports sizes/ratios only; does not display or describe the decoded content. Reconstructed preview PNGs are written to disk for visual judgement by eye, not opened here. """ from __future__ import annotations import subprocess import sys from pathlib import Path import numpy as np from PIL import Image SRC = Path(r"d:\dev\rick-roll-md\rick_astley_never_gonna_give_you_up-1987-.m2v") WORK = Path(r"d:\dev\rick-roll-md\encoder-prototype") FIELDS_DIR = WORK / "fields" PREVIEW_DIR = WORK / "preview" SEGMENTS = [("0:30", 15), ("2:30", 15)] # two separated clips: does the codebook actually reuse tiles across different content, or grow ~linearly? TARGET_SIZE = (320, 240) # Genesis H40/V30 PALETTE_COLORS = 16 # one Genesis hardware palette (4bpp tiles) TILE = 8 HYSTERESIS_TOLERANCE = 300 # squared-RGB-distance slack before a pixel switches NUM_BANDS = 6 # horizontal raster strips, each with its own palette (40 lines = 5 tile-rows each) BAND_HEIGHT = TARGET_SIZE[1] // NUM_BANDS # Measured DAC output levels, matching megadrive_python.render.RAMP/LEVELS exactly (keep in # sync if that changes): CRAM only ever stores a raw 0-7 value per channel, and shade (normal/ # shadow/highlight) picks which of these three 8-step ramps turns it into an RGB level. RAMP = (0, 29, 52, 70, 87, 101, 116, 130, 144, 158, 172, 187, 206, 228, 255) NORMAL_LEVELS = np.array(RAMP[0:15:2], dtype=np.int32) SHADOW_LEVELS = np.array(RAMP[0:8], dtype=np.int32) def extract_fields(start: str, duration: int, out_dir: Path) -> None: out_dir.mkdir(parents=True, exist_ok=True) for old in out_dir.glob("*.png"): old.unlink() # separatefields splits each interlaced frame into its two fields (480x288 # each); select keeps only the first (top) field of each pair, matching # field_order=tt, giving one field per source frame at its native 25 Hz. subprocess.run( [ "ffmpeg", "-y", "-ss", start, "-t", str(duration), "-i", str(SRC), "-vf", r"separatefields,select=not(mod(n\,2))", "-vsync", "0", str(out_dir / "f%05d.png"), ], check=True, capture_output=True, ) def load_and_downscale(in_dir: Path) -> list[Image.Image]: frames = [] for path in sorted(in_dir.glob("f*.png")): img = Image.open(path).convert("RGB").resize(TARGET_SIZE, Image.LANCZOS) frames.append(img) if not frames: raise SystemExit(f"no fields extracted in {in_dir} - check the ffmpeg step") return frames def quantize_dac(rgb: np.ndarray, levels: np.ndarray) -> np.ndarray: """Snap RGB888 channel values to the nearest of 8 real DAC steps, returning the raw 0-7 per-channel value the hardware can actually store in CRAM.""" return np.argmin(np.abs(rgb[..., None].astype(np.int32) - levels[None, :]), axis=-1).astype(np.uint8) def dac_to_rgb(raw: np.ndarray, levels: np.ndarray) -> np.ndarray: return levels[raw.astype(np.int64)] def build_palette(frames: list[Image.Image]) -> np.ndarray: stack = Image.new("RGB", (TARGET_SIZE[0], TARGET_SIZE[1] * len(frames))) for i, frame in enumerate(frames): stack.paste(frame, (0, i * TARGET_SIZE[1])) quantized_sample = stack.quantize(colors=PALETTE_COLORS, method=Image.MEDIANCUT) raw = np.array(quantized_sample.getpalette()[: PALETTE_COLORS * 3], dtype=np.int32).reshape(-1, 3) cram_raw = quantize_dac(raw, NORMAL_LEVELS) # what CRAM can actually hold, not raw 24-bit PIL output return dac_to_rgb(cram_raw, NORMAL_LEVELS).astype(np.int32) def quantize_sticky(frames: list[Image.Image], palette: np.ndarray, tolerance: int) -> list[np.ndarray]: """Per-pixel quantization with temporal hysteresis: a pixel keeps the previous frame's chosen palette index unless some other entry is now clearly closer (by more than ``tolerance`` in summed squared RGB distance) - suppressing small frame-to-frame compression noise from flipping the quantized value back and forth, the same "dead zone around the target" idea a pitch-correction effect uses to hold a slightly-wavering pitch on one note instead of sliding between two (Aubrey's "lock the pixels" suggestion).""" results = [] prev_indices: np.ndarray | None = None for frame in frames: arr = np.asarray(frame, dtype=np.int32) # (H, W, 3) diff = arr[:, :, None, :] - palette[None, None, :, :] # (H, W, P, 3) dist = np.sum(diff * diff, axis=-1) # (H, W, P) best_idx = np.argmin(dist, axis=-1) if prev_indices is None: chosen = best_idx else: best_dist = np.take_along_axis(dist, best_idx[..., None], axis=-1)[..., 0] prev_dist = np.take_along_axis(dist, prev_indices[..., None], axis=-1)[..., 0] chosen = np.where(prev_dist <= best_dist + tolerance, prev_indices, best_idx) results.append(chosen.astype(np.uint8)) prev_indices = chosen return results def build_band_palettes(frames: list[Image.Image]) -> list[np.ndarray]: """One 16-colour palette per horizontal band, fit to that band's own pixel content across the segment - the raster/H-interrupt "more colours" technique: each band gets reloaded into CRAM as the beam reaches it, so the picture is not limited to one global 16-colour set the way :func:`build_palette` is. Snapped to the real DAC ramp, same as :func:`build_palette`.""" palettes = [] for band in range(NUM_BANDS): y0, y1 = band * BAND_HEIGHT, (band + 1) * BAND_HEIGHT stack = Image.new("RGB", (TARGET_SIZE[0], (y1 - y0) * len(frames))) for i, frame in enumerate(frames): stack.paste(frame.crop((0, y0, TARGET_SIZE[0], y1)), (0, i * (y1 - y0))) quantized_sample = stack.quantize(colors=PALETTE_COLORS, method=Image.MEDIANCUT) raw = np.array(quantized_sample.getpalette()[: PALETTE_COLORS * 3], dtype=np.int32).reshape(-1, 3) cram_raw = quantize_dac(raw, NORMAL_LEVELS) palettes.append(dac_to_rgb(cram_raw, NORMAL_LEVELS).astype(np.int32)) return palettes def quantize_sticky_banded( frames: list[Image.Image], band_palettes: list[np.ndarray], tolerance: int ) -> list[np.ndarray]: """The same temporal-hysteresis quantization as :func:`quantize_sticky`, applied independently within each horizontal band against that band's own palette.""" results = [] prev_indices: np.ndarray | None = None for frame in frames: arr = np.asarray(frame, dtype=np.int32) chosen_full = np.zeros(arr.shape[:2], dtype=np.uint8) for band, palette in enumerate(band_palettes): y0, y1 = band * BAND_HEIGHT, (band + 1) * BAND_HEIGHT sub = arr[y0:y1] diff = sub[:, :, None, :] - palette[None, None, :, :] dist = np.sum(diff * diff, axis=-1) best_idx = np.argmin(dist, axis=-1) if prev_indices is None: chosen = best_idx else: prev_sub = prev_indices[y0:y1] best_dist = np.take_along_axis(dist, best_idx[..., None], axis=-1)[..., 0] prev_dist = np.take_along_axis(dist, prev_sub[..., None], axis=-1)[..., 0] chosen = np.where(prev_dist <= best_dist + tolerance, prev_sub, best_idx) chosen_full[y0:y1] = chosen results.append(chosen_full) prev_indices = chosen_full return results def reconstruct_rgb_banded(indices: np.ndarray, band_palettes: list[np.ndarray]) -> np.ndarray: out = np.zeros((*indices.shape, 3), dtype=np.uint8) for band, palette in enumerate(band_palettes): y0, y1 = band * BAND_HEIGHT, (band + 1) * BAND_HEIGHT out[y0:y1] = palette[indices[y0:y1]] return out def tile_ids_of(index_frame: np.ndarray, codebook: dict[tuple[int, bytes], int], band_height: int = 0) -> list[int]: ids = [] for ty in range(0, index_frame.shape[0], TILE): band = ty // band_height if band_height else 0 for tx in range(0, index_frame.shape[1], TILE): key = (band, index_frame[ty : ty + TILE, tx : tx + TILE].tobytes()) if key not in codebook: codebook[key] = len(codebook) ids.append(codebook[key]) return ids class VQCodebook: """Approximate ("fuzzy") tile dedup: a new tile reuses an existing codebook entry if their reconstructed RGB is within ``tolerance`` summed-squared-error, not only on an exact index-byte match - the real compression lever the plain :func:`tile_ids_of` (exact-match only) was missing. A coarse 2x2-quadrant-average bucket keeps the search to plausible neighbours only, instead of comparing against every codebook entry.""" def __init__(self, tolerance: float, bucket_step: int = 24) -> None: self.tolerance = tolerance self.bucket_step = bucket_step self.buckets: dict[tuple, list[int]] = {} self.tiles: list[np.ndarray] = [] # id -> the stored (possibly reused) RGB tile def id_for(self, band: int, rgb_tile: np.ndarray, key: tuple) -> int: full_key = (band, key) bucket = self.buckets.setdefault(full_key, []) tile32 = rgb_tile.astype(np.int32) # First match within tolerance wins (not the best possible match): scanning a # whole bucket for the optimum is O(bucket size) per call, and flat-colour # content (letterboxing, solid backgrounds) can pile thousands of near- # duplicates into one bucket, making that quadratic. Also cap how much of a # giant bucket gets scanned at all for the same reason. for tid in bucket[-50:]: if float(np.sum((self.tiles[tid] - tile32) ** 2)) <= self.tolerance: return tid new_id = len(self.tiles) self.tiles.append(tile32) bucket.append(new_id) return new_id def __len__(self) -> int: return len(self.tiles) def frame_bucket_keys(rgb: np.ndarray, bucket_step: int) -> np.ndarray: """Vectorized quadrant-average bucket keys for every 8x8 tile in a frame, shape (tiles_y, tiles_x, 12) - see :meth:`VQCodebook.id_for`.""" h, w, _ = rgb.shape tiles_y, tiles_x = h // TILE, w // TILE grid = rgb.reshape(tiles_y, TILE, tiles_x, TILE, 3) grid = grid.reshape(tiles_y, 2, TILE // 2, tiles_x, 2, TILE // 2, 3) quad = grid.mean(axis=(2, 5)) # (tiles_y, 2, tiles_x, 2, 3) quad = quad.transpose(0, 2, 1, 3, 4) # (tiles_y, tiles_x, 2, 2, 3) return (quad // bucket_step).astype(np.int32).reshape(tiles_y, tiles_x, 12) def vq_tile_ids_of(index_frame: np.ndarray, band_palettes: list[np.ndarray], vq: VQCodebook) -> list[int]: rgb = reconstruct_rgb_banded(index_frame, band_palettes) keys = frame_bucket_keys(rgb, vq.bucket_step) ids = [] for ty in range(0, index_frame.shape[0], TILE): band = ty // BAND_HEIGHT tyi = ty // TILE for tx in range(0, index_frame.shape[1], TILE): txi = tx // TILE key = tuple(keys[tyi, txi].tolist()) ids.append(vq.id_for(band, rgb[ty : ty + TILE, tx : tx + TILE], key)) return ids def reconstruct_from_vq(frame_ids: list[int], vq: VQCodebook) -> np.ndarray: """What the hardware would actually display: each cell shows its *stored* codebook tile, which for a merged (approximately-matched) cell differs slightly from the original - this is the real picture a VQ-tolerance choice buys, not an idealised one.""" tiles_x = TARGET_SIZE[0] // TILE out = np.zeros((TARGET_SIZE[1], TARGET_SIZE[0], 3), dtype=np.uint8) for cell, tid in enumerate(frame_ids): ty, tx = (cell // tiles_x) * TILE, (cell % tiles_x) * TILE out[ty : ty + TILE, tx : tx + TILE] = vq.tiles[tid].astype(np.uint8) return out def save_previews(index_frames: list[np.ndarray], band_palettes: list[np.ndarray]) -> None: PREVIEW_DIR.mkdir(parents=True, exist_ok=True) for old in PREVIEW_DIR.glob("*"): old.unlink() for i, indices in enumerate(index_frames): Image.fromarray(reconstruct_rgb_banded(indices, band_palettes)).save(PREVIEW_DIR / f"p{i:05d}.png") np.save(PREVIEW_DIR / f"p{i:05d}.npy", indices) def size_report(label: str, frame_tile_ids: list[list[int]], n_codebook: int) -> None: cells_per_frame = len(frame_tile_ids[0]) changed = [cells_per_frame] prev = frame_tile_ids[0] for ids in frame_tile_ids[1:]: changed.append(sum(1 for a, b in zip(prev, ids, strict=True) if a != b)) prev = ids avg_changed = sum(changed) / len(changed) codebook_bytes = n_codebook * (TILE * TILE // 2) # 4bpp: 32 bytes/tile print(f"{label}: {n_codebook:>7} unique tiles ({codebook_bytes / 1_000_000:6.2f} MB), " f"avg {avg_changed:6.1f} / {cells_per_frame} cells changed/frame " f"({100 * avg_changed / cells_per_frame:5.1f}%)") def measure_shadow_benefit(frames: list[Image.Image], band_palettes: list[np.ndarray]) -> None: """Per band: how much per-pixel quantization error drops, and what share of tiles would take it, if each 8x8 tile may choose STE shadow shade instead of normal for its one priority bit (CMD/Kabuto's rule: a whole low-priority tile renders through the shadow ramp) - the only shadow/highlight effect that is free at full-frame, per-tile granularity. Highlight is not measured: getting a pixel to *highlight* needs a sprite's special operator colour over it, and the sprite budget (80/frame, 40 tiles/line in H40) cannot cover a whole picture tile-by-tile the way the priority bit can.""" tiles_x = TARGET_SIZE[0] // TILE for band, palette in enumerate(band_palettes): y0, y1 = band * BAND_HEIGHT, (band + 1) * BAND_HEIGHT cram_raw = quantize_dac(palette, NORMAL_LEVELS) shadow_palette = dac_to_rgb(cram_raw, SHADOW_LEVELS).astype(np.int32) normal_only_err = 0.0 with_shadow_err = 0.0 shadow_tiles = 0 total_tiles = 0 for frame in frames: src = np.asarray(frame, dtype=np.int32)[y0:y1] n_dist = np.sum((src[:, :, None, :] - palette[None, None, :, :]) ** 2, axis=-1) n_best = np.min(n_dist, axis=-1) s_dist = np.sum((src[:, :, None, :] - shadow_palette[None, None, :, :]) ** 2, axis=-1) s_best = np.min(s_dist, axis=-1) for ty in range(0, y1 - y0, TILE): for tx in range(0, TARGET_SIZE[0], TILE): n_tile = n_best[ty : ty + TILE, tx : tx + TILE].sum() s_tile = s_best[ty : ty + TILE, tx : tx + TILE].sum() normal_only_err += n_tile with_shadow_err += min(n_tile, s_tile) shadow_tiles += s_tile < n_tile total_tiles += 1 print(f" band {band}: {100 * shadow_tiles / total_tiles:5.1f}% of tiles prefer shadow, " f"mean tile error {normal_only_err / total_tiles:9.0f} -> {with_shadow_err / total_tiles:9.0f} " f"({100 * (1 - with_shadow_err / normal_only_err):4.1f}% lower)") def main() -> None: print("extracting fields...", flush=True) seg_dirs = [FIELDS_DIR / f"seg{i}" for i in range(len(SEGMENTS))] for (start, duration), out_dir in zip(SEGMENTS, seg_dirs): extract_fields(start, duration, out_dir) seg_frames = [load_and_downscale(d) for d in seg_dirs] for i, frames in enumerate(seg_frames): print(f"segment {i} ({SEGMENTS[i][0]}): {len(frames)} fields at {TARGET_SIZE[0]}x{TARGET_SIZE[1]}", flush=True) all_frames = [f for frames in seg_frames for f in frames] # One shared set of band palettes, fit across both segments, so the codebook # comparison below isn't skewed by each segment picking its own best-fit colours. band_palettes = build_band_palettes(all_frames) # The real open question: does new content mostly reuse existing tiles, or add # roughly its own share of new ones every time? Hysteresis resets per segment # (quantize_sticky_banded is called fresh on each) since the two clips are # minutes apart in the real video, not adjacent frames. print("\nEXACT-MATCH codebook growth across separated segments (one shared codebook):") codebook_running: dict[tuple[int, bytes], int] = {} all_ids: list[list[int]] = [] banded_per_segment: list[list[np.ndarray]] = [] for i, frames in enumerate(seg_frames): banded = quantize_sticky_banded(frames, band_palettes, HYSTERESIS_TOLERANCE) banded_per_segment.append(banded) before = len(codebook_running) ids = [tile_ids_of(f, codebook_running, band_height=BAND_HEIGHT) for f in banded] all_ids.extend(ids) added = len(codebook_running) - before bytes_added = added * (TILE * TILE // 2) bytes_total = len(codebook_running) * (TILE * TILE // 2) print(f" segment {i} ({SEGMENTS[i][0]}, {len(frames)} frames): +{added:>6} new tiles " f"(+{bytes_added / 1_000_000:5.2f} MB) -> codebook {len(codebook_running):>7} tiles " f"({bytes_total / 1_000_000:6.2f} MB total)") size_report(f"{NUM_BANDS} raster-band palettes, both segments combined", all_ids, len(codebook_running)) print("\nSTE shadow-shade benefit per band (free: one priority bit/tile, zero extra CRAM):") measure_shadow_benefit(all_frames, band_palettes) board_frames_full_song = 211 * 24.85 # single-field playback, the whole song scale = board_frames_full_song / len(all_frames) seconds_sampled = sum(d for _, d in SEGMENTS) # Fuzzy (approximate) tile matching: does allowing "close enough" reuse fix the # exact-match blowup above? Same two-segment growth structure, swept across a few # tolerances (summed squared error over the whole 8x8x3 tile, so ~3x a per-pixel # tolerance of the same number times 64 pixels - these are tile-total, not per-pixel). print("\nFUZZY (VQ) tile matching - codebook growth across separated segments:") results = [] preview_choice = None for vq_tolerance in (6000, 20000, 60000, 150000): vq = VQCodebook(vq_tolerance) vq_all_ids: list[list[int]] = [] vq_all_frame_ids: list[list[int]] = [] added_per_segment = [] for i, banded in enumerate(banded_per_segment): before = len(vq) ids = [vq_tile_ids_of(f, band_palettes, vq) for f in banded] vq_all_ids.extend(ids) vq_all_frame_ids.extend(ids) added_per_segment.append(len(vq) - before) codebook_bytes = len(vq) * (TILE * TILE // 2) cells_per_frame = len(vq_all_ids[0]) changed = [cells_per_frame] prev = vq_all_ids[0] for ids in vq_all_ids[1:]: changed.append(sum(1 for a, b in zip(prev, ids, strict=True) if a != b)) prev = ids avg_changed = sum(changed) / len(changed) delta_mb_full = (sum(c * 4 for c in changed)) * scale / 1_000_000 codebook_mb_sampled = codebook_bytes / 1_000_000 print(f" tolerance {vq_tolerance:>7}: segment adds {added_per_segment} new tiles, " f"codebook {len(vq):>7} ({codebook_mb_sampled:6.2f} MB for {seconds_sampled}s), " f"avg {avg_changed:6.1f}/{cells_per_frame} changed/frame ({100 * avg_changed / cells_per_frame:5.1f}%), " f"delta full-song ~{delta_mb_full:6.2f} MB") results.append((vq_tolerance, vq, vq_all_frame_ids, codebook_mb_sampled, delta_mb_full)) if vq_tolerance == 20000: preview_choice = (vq, vq_all_frame_ids) print(f"\n(codebook MB above is only for the {seconds_sampled}s sampled, not the full song - " f"its full-song growth curve still needs the per-segment deltas printed, same caveat as " f"the exact-match version; delta MB *is* extrapolated to the full song, same as before)") if preview_choice is not None: vq, frame_ids = preview_choice PREVIEW_DIR.mkdir(parents=True, exist_ok=True) for old in PREVIEW_DIR.glob("*"): old.unlink() for i, ids in enumerate(frame_ids): rgb = reconstruct_from_vq(ids, vq) Image.fromarray(rgb).save(PREVIEW_DIR / f"p{i:05d}.png") np.save(PREVIEW_DIR / f"p{i:05d}.npy", np.array(ids, dtype=np.int32)) print(f"\npreviews written to {PREVIEW_DIR} (VQ tolerance 20000, both segments, " f"*actual* stored tiles - shows merge error where it happens, not idealised)") # Audio options (pure arithmetic: rate x duration x bytes/sample - no need to touch # the actual audio to size this), against both candidate ROM ceilings. audio_options = [ ("FM arrangement (original chiptune, not sampled)", 0.05), ("PCM mono 8-bit @ 8,000 Hz", 211 * 8_000 / 1_000_000), ("PCM mono 8-bit @ 11,025 Hz", 211 * 11_025 / 1_000_000), ("PCM mono 8-bit @ 13,000 Hz", 211 * 13_000 / 1_000_000), ("PCM mono 8-bit @ 18,000 Hz", 211 * 18_000 / 1_000_000), ] print("\ncombined ROM budget (video codebook is NOT yet fully measured for the full song - " "treat its MB below as the floor measured so far, scaled by how much it grew segment 2 " "over segment 1 above; still gives a real video+audio comparison):") for vq_tolerance, vq, _, codebook_mb_sampled, delta_mb_full in results: # crude same-rate projection of the codebook, just to put a number in the table - # flagged as approximate, unlike the delta MB which is a real linear extrapolation. codebook_mb_full_guess = codebook_mb_sampled * (211 / seconds_sampled) video_mb = delta_mb_full + codebook_mb_full_guess for audio_label, audio_mb in audio_options: total = video_mb + audio_mb fits_16 = "16MB OK" if total <= 16 else "16MB OVER" fits_32 = "32MB OK" if total <= 32 else "32MB OVER" print(f" VQ {vq_tolerance:>7} (video ~{video_mb:6.2f} MB) + {audio_label:<42} " f"(~{audio_mb:5.2f} MB) = {total:6.2f} MB [{fits_16}, {fits_32}]") if __name__ == "__main__": sys.exit(main())