"""Phase-2 streaming encoder: a sequence of pictures -> per-frame records the player executes, plus the predicted screen for every frame. VRAM is a ring of tile slots (1..RING_END) the encoder manages exactly as the player will see it. For every cell of every frame, in order of cost: 1. **keep** the entry already on screen if its error against the new source pixels is within KEEP_TOL of the best fresh quantization (temporal hysteresis at the cell level: no patch, no DMA); 2. **reuse** any live VRAM tile, under any flip, if its error is within REUSE_TOL of the best fresh quantization (a name-table patch, no DMA); 3. otherwise a **new** tile: appended to this frame's run in ROM, written to the next free ring slot (a patch and a DMA). Errors are exact luma-weighted squared distances against the source pixels, computed once per cell per (line, shade) and indexed by pen pattern, so comparing a candidate tile costs one gather. Palettes are fitted per shot (a cut in the source) and reloaded with the shot's first frame. If a frame needs more new tiles than the DMA budget allows, its tolerances are doubled and it is redone (the crude ancestor of the two-pass rate controller in PLAN.md 4.6). """ from __future__ import annotations import json from dataclasses import dataclass, field from pathlib import Path import numpy as np from PIL import Image from .encode import LINES, PENS, LUMA_W, fit_region, load_picture from .vdp import CELLS_X, CELLS_Y, HEIGHT, NORMAL, PLANE_W, SHADOW, TILE, WIDTH, cram_word, raw_to_rgb, tile_bytes RING_END = 1536 # slots 1..1535 are the cache; tile 0 stays blank CELLS = CELLS_X * CELLS_Y KEEP_TOL = 25.0 * TILE * TILE # per-tile luma-weighted error slack (25 per pixel) REUSE_TOL = 40.0 * TILE * TILE NEW_TILE_CAP = 600 # ~19 KB: one VBlank at the blanking rate plus the active display SHOT_THRESHOLD = 28.0 # mean abs RGB difference between consecutive frames SHOT_SAMPLE_FRAMES = 6 @dataclass class FrameRecord: video_frame: int runs: list[tuple[int, int, int]] # (slot, first tile index within frame tiles, count) tiles: list[bytes] # this frame's new tiles, in run order patches: list[tuple[int, int]] # (cell index, name-table word) cram: list[int] | None # 64 words when the palette changes expected: np.ndarray stats: dict = field(default_factory=dict) # -- costs ----------------------------------------------------------------------- def _cell_pixels(rgb: np.ndarray) -> np.ndarray: """(H, W, 3) -> (CELLS, 64, 3) float32.""" return ( rgb.reshape(CELLS_Y, TILE, CELLS_X, TILE, 3) .transpose(0, 2, 1, 3, 4) .reshape(CELLS, TILE * TILE, 3) .astype(np.float32) ) def cost_tables(rgb: np.ndarray, lines: np.ndarray) -> np.ndarray: """(LINES, 2, CELLS, 64, PENS) float32: the weighted squared error of showing pen p of line l under shade s at each pixel of each cell.""" pix = _cell_pixels(rgb) # (CELLS, 64, 3) out = np.empty((LINES, 2, CELLS, TILE * TILE, PENS), dtype=np.float32) w = LUMA_W.astype(np.float32) for line in range(LINES): for shade in (NORMAL, SHADOW): pal = raw_to_rgb(lines[line], shade).astype(np.float32) # (16, 3) diff = pix[:, :, None, :] - pal[None, None, :, :] out[line, shade] = np.sum(diff * diff * w, axis=-1) return out _PIX = np.arange(TILE * TILE) def _flip_pens(pens64: np.ndarray, hflip: bool, vflip: bool) -> np.ndarray: t = pens64.reshape(TILE, TILE) if hflip: t = t[:, ::-1] if vflip: t = t[::-1, :] return np.ascontiguousarray(t).reshape(TILE * TILE) FLIPS = ((False, False), (True, False), (False, True), (True, True)) # -- the encoder ------------------------------------------------------------------- class StreamEncoder: def __init__(self) -> None: self.slot_pens = np.zeros((RING_END, TILE * TILE), dtype=np.uint8) # the four flipped views of every slot, kept in step with slot_pens self.slot_views = np.zeros((4, RING_END, TILE * TILE), dtype=np.uint8) self.slot_live = np.zeros(RING_END, dtype=bool) self.head = 1 # what is on screen: per cell (slot, flip index, line, shade); -1 slot = nothing yet self.shown = np.full((CELLS, 4), -1, dtype=np.int64) self.shown_words = np.zeros(CELLS, dtype=np.uint16) self.lines: np.ndarray | None = None self.total_new_tiles = 0 # -- helpers -- def _write_slot(self, slot: int, pens64: np.ndarray) -> None: self.slot_pens[slot] = pens64 for f, (h, v) in enumerate(FLIPS): self.slot_views[f, slot] = _flip_pens(pens64, h, v) self.slot_live[slot] = True @staticmethod def _word(slot: int, flip: int, line: int, shade: int) -> int: h, v = FLIPS[flip] return ( (0x8000 if shade == NORMAL else 0) | (line << 13) | (0x1000 if v else 0) | (0x0800 if h else 0) | slot ) def _entry_error(self, costs: np.ndarray, cell: int, slot: int, flip: int, line: int, shade: int) -> float: c = costs[line, shade, cell] # (64, 16) return float(c[_PIX, self.slot_views[flip, slot]].sum()) def _best_reuse(self, costs: np.ndarray, cell: int, line: int, shade: int, forbidden: np.ndarray) -> tuple[float, int, int]: # fmt: skip """Lowest error over all live slots and flips; forbidden slots are skipped.""" c = costs[line, shade, cell] # (64, 16) best = (np.inf, -1, -1) for f in range(4): errs = c[_PIX[None, :], self.slot_views[f]].sum(axis=1) # (RING_END,) errs[~self.slot_live] = np.inf errs[forbidden] = np.inf errs[0] = np.inf s = int(np.argmin(errs)) if errs[s] < best[0]: best = (float(errs[s]), s, f) return best def _alloc(self, busy: np.ndarray) -> int: """Next ring slot not referenced by the frame on screen nor by this frame, or -1 when every slot is spoken for.""" for _ in range(RING_END): slot = self.head self.head = self.head + 1 if self.head + 1 < RING_END else 1 if not busy[slot]: return slot return -1 # -- one frame -- def encode_frame(self, rgb: np.ndarray, video_frame: int, new_palette: bool) -> FrameRecord: assert self.lines is not None costs = cost_tables(rgb, self.lines) best_err = costs.min(axis=-1).sum(axis=-1) # (LINES, 2, CELLS) flat = best_err.reshape(-1, CELLS) choice = flat.argmin(axis=0) base = flat[choice, np.arange(CELLS)] best_line, best_shade = choice // 2, choice % 2 best_pens = np.empty((CELLS, TILE * TILE), dtype=np.uint8) for cell in range(CELLS): best_pens[cell] = costs[best_line[cell], best_shade[cell], cell].argmin(axis=-1) keep_tol, reuse_tol = KEEP_TOL, REUSE_TOL for attempt in range(6): record = self._try_frame(rgb, video_frame, new_palette, costs, base, best_line, best_shade, best_pens, keep_tol, reuse_tol) # fmt: skip if len(record.tiles) <= NEW_TILE_CAP: record.stats["attempt"] = attempt record.stats["keep_tol"] = keep_tol record.stats["reuse_tol"] = reuse_tol return record keep_tol *= 2 reuse_tol *= 2 record.stats["attempt"] = attempt return record def _try_frame(self, rgb, video_frame, new_palette, costs, base, best_line, best_shade, best_pens, keep_tol, reuse_tol) -> FrameRecord: # fmt: skip # Work on copies: a rejected attempt must not leak into the ring. saved = (self.slot_pens.copy(), self.slot_views.copy(), self.slot_live.copy(), self.head) entries = np.full((CELLS, 4), -1, dtype=np.int64) busy = np.zeros(RING_END, dtype=bool) busy[0] = True shown_slots = self.shown[:, 0] busy[shown_slots[shown_slots > 0]] = True tiles: list[bytes] = [] runs: list[list[int]] = [] # [slot, first, count] n_keep = n_reuse = n_new = n_forced = 0 err_total = 0.0 order = np.argsort(-base) # hardest cells decide first (they need fresh tiles most) for cell in order: cell = int(cell) line, shade = int(best_line[cell]), int(best_shade[cell]) b = float(base[cell]) # 1. keep what is on screen s0, f0, l0, sh0 = (int(v) for v in self.shown[cell]) if s0 > 0 and self.slot_live[s0]: e_keep = self._entry_error(costs, cell, s0, f0, l0, sh0) if e_keep <= b + keep_tol: entries[cell] = (s0, f0, l0, sh0) busy[s0] = True n_keep += 1 err_total += e_keep continue # 2. reuse a live tile e_reuse, s, f = self._best_reuse(costs, cell, line, shade, forbidden=np.zeros(RING_END, dtype=bool)) if s > 0 and e_reuse <= b + reuse_tol: entries[cell] = (s, f, line, shade) busy[s] = True n_reuse += 1 err_total += e_reuse continue # 3. a new tile slot = self._alloc(busy) if slot < 0: # No free slot left (a cut after a busy frame): show the nearest live # tile anyway. These are the lowest-error cells, so it costs least here. if s > 0: entries[cell] = (s, f, line, shade) busy[s] = True err_total += e_reuse else: entries[cell] = (0, 0, line, shade) err_total += float(costs[line, shade, cell][:, 0].sum()) n_forced += 1 continue busy[slot] = True self._write_slot(slot, best_pens[cell]) tiles.append(tile_bytes(best_pens[cell].reshape(TILE, TILE))) if runs and runs[-1][0] + runs[-1][2] == slot: runs[-1][2] += 1 else: runs.append([slot, len(tiles) - 1, 1]) entries[cell] = (slot, 0, line, shade) n_new += 1 err_total += b if n_new > NEW_TILE_CAP: self.slot_pens, self.slot_views, self.slot_live, self.head = saved return FrameRecord(video_frame, [], [b""] * n_new, [], None, np.zeros((HEIGHT, WIDTH, 3), np.uint8)) words = np.array([self._word(*(int(v) for v in e)) for e in entries], dtype=np.uint16) patches = [(cell, int(words[cell])) for cell in range(CELLS) if words[cell] != self.shown_words[cell] or self.shown[cell, 0] < 0] expected = self._render(entries) self.shown = entries self.shown_words = words self.total_new_tiles += n_new cram = None if new_palette: cram = [cram_word(*map(int, self.lines[line, pen])) for line in range(LINES) for pen in range(PENS)] stats = { "keep": n_keep, "reuse": n_reuse, "new": n_new, "forced": n_forced, "patches": len(patches), "runs": len(runs), "error_per_pixel": err_total / (WIDTH * HEIGHT), "base_error_per_pixel": float(base.sum()) / (WIDTH * HEIGHT), } # fmt: skip return FrameRecord(video_frame, [tuple(r) for r in runs], tiles, patches, cram, expected, stats) def _render(self, entries: np.ndarray) -> np.ndarray: out = np.zeros((CELLS_Y, CELLS_X, TILE, TILE, 3), dtype=np.uint8) pal = {(l, s): raw_to_rgb(self.lines[l], s).astype(np.uint8) for l in range(LINES) for s in (NORMAL, SHADOW)} for cell in range(CELLS): slot, flip, line, shade = (int(v) for v in entries[cell]) pens = self.slot_views[flip, slot].reshape(TILE, TILE) out[cell // CELLS_X, cell % CELLS_X] = pal[(line, shade)][pens] return out.transpose(0, 2, 1, 3, 4).reshape(HEIGHT, WIDTH, 3) # -- shots and the whole clip ---------------------------------------------------------- def detect_shots(frames: list[np.ndarray]) -> list[int]: """Indices where a new shot starts (always includes 0).""" starts = [0] for i in range(1, len(frames)): a = frames[i - 1][::4, ::4].astype(np.int32) b = frames[i][::4, ::4].astype(np.int32) if np.abs(a - b).mean() > SHOT_THRESHOLD: starts.append(i) return starts def fit_shot_lines(frames: list[np.ndarray]) -> np.ndarray: step = max(1, len(frames) // SHOT_SAMPLE_FRAMES) sample = frames[::step][:SHOT_SAMPLE_FRAMES] lines, *_ = fit_region(np.concatenate(sample, axis=0)) return lines def encode_clip(paths: list[Path], out: Path, limit: int | None = None) -> list[FrameRecord]: frames = [load_picture(p) for p in paths[:limit]] shots = detect_shots(frames) shot_ends = shots[1:] + [len(frames)] print(f"{len(frames)} frames, {len(shots)} shots at {shots}", flush=True) enc = StreamEncoder() records: list[FrameRecord] = [] expected_dir = out / "expected" expected_dir.mkdir(parents=True, exist_ok=True) for shot, (start, end) in enumerate(zip(shots, shot_ends)): enc.lines = fit_shot_lines(frames[start:end]) for i in range(start, end): rec = enc.encode_frame(frames[i], i, new_palette=(i == start)) records.append(rec) Image.fromarray(rec.expected).save(expected_dir / f"e{i:05d}.png") s = rec.stats print(f"frame {i:4d} shot {shot:2d}: keep {s['keep']:4d} reuse {s['reuse']:4d} new {s['new']:4d} " f"forced {s['forced']:3d} patches {s['patches']:4d} runs {s['runs']:3d} err {s['error_per_pixel']:6.1f} " f"(base {s['base_error_per_pixel']:6.1f}) attempt {s['attempt']}", flush=True) summary = { "frames": len(records), "shots": shots, "total_new_tiles": enc.total_new_tiles, "tile_bytes": enc.total_new_tiles * 32, "patch_bytes": sum(4 * len(r.patches) for r in records), "mean_new_per_frame": enc.total_new_tiles / len(records), } (out / "summary.json").write_text(json.dumps(summary, indent=2)) print(json.dumps(summary, indent=2)) import pickle slim = [FrameRecord(r.video_frame, r.runs, r.tiles, r.patches, r.cram, np.zeros(0), r.stats) for r in records] with (out / "records.pkl").open("wb") as f: pickle.dump(slim, f) return records