"""Streaming encoder with a ROM-side tile codebook (PLAN.md 3.1 steps 5-8, first cut). Every distinct tile the whole clip ever shows is stored in ROM exactly once, in first-use order (the *store*). VRAM's ring slots hold references into the store. For each cell of each frame, cheapest first: 1. **keep** the entry on screen, if within KEEP_TOL of the best fresh quantization; 2. **vram** any tile currently in VRAM, under any flip, within REUSE_TOL (a patch); 3. **rom** any tile already in the store, within ROM_TOL: DMA it back into a free slot (a descriptor, no new ROM bytes); 4. **new** append to the store (ROM bytes + a descriptor). Candidate search is a 16-dimensional luma-signature prefilter (4x4 block means of the source cell, against each tile's pens seen through the cell's palette line and shade) followed by an exact cost gather on the top K - which is also what makes the encoder ~an order of magnitude faster than the exhaustive Phase-2 search. Per-frame DMA cost is modelled in 68000 cycles (one descriptor ~100, one tile's 16 words ~76 at the blanking rate) against a VBlank budget; a frame over budget has its tolerances doubled and is redone. """ from __future__ import annotations import json import pickle from dataclasses import dataclass, field from pathlib import Path import numpy as np from PIL import Image from .encode import LINES, PENS, LUMA_W, load_picture from .palette import fit_lines_lloyd from .stream import SHOT_SAMPLE_FRAMES, SHOT_THRESHOLD, _cell_pixels, cost_tables, detect_shots from .vdp import CELLS_X, CELLS_Y, HEIGHT, NORMAL, SHADOW, TILE, WIDTH, cram_word, raw_to_rgb RING_END = 1536 CELLS = CELLS_X * CELLS_Y KEEP_TOL = 25.0 * TILE * TILE REUSE_TOL = 40.0 * TILE * TILE ROM_TOL = 40.0 * TILE * TILE TOP_K = 24 DESCRIPTOR_CYCLES = 200 # the player expands an 8-byte descriptor into the six VDP writes DESCRIPTOR_BYTES = 8 TILE_DMA_CYCLES = 16 * 4.78 #: PAL V28: 89 blank lines x 488 cycles = 43.4k. Stay well inside it: anything that #: spills into the display runs 11x slower per DMA word, holds the 68000 for lines on #: end and keeps V_GO low, which starves the Z80's sample refills. VBLANK_BUDGET_CYCLES = 40_000 #: The highest tolerance multiplier the budget climb will try. The hardest cut in the song #: (frame 187) needs ~10x base at 2,340 B/frame, and a run at 2,750 B/frame starting its #: climb from 4.45x reached 8.9x, failed, and raised, because the old ceiling of 8 was #: tested before the doubling: it only reached 10x when the climb happened to start above #: 5x. The ceiling is a sanity bound on a runaway, not a quality knob, so it is high. RETRY_CEILING = 64.0 RETRY_RESOLUTION = 1.15 # stop bisecting once the fitting and failing multipliers are this close RATE_INTEGRAL_CLAMP = 0.12 # per-frame bound (in log space) on the controller's cumulative term STORE_GROWTH = 1 << 16 FLIPS = ((False, False), (True, False), (False, True), (True, True)) _PIX = np.arange(TILE * TILE) _GRID = np.arange(TILE * TILE).reshape(TILE, TILE) #: For each flip, the pixel index permutation turning an unflipped tile into that view. FLIP_PERM = np.stack([ _GRID.reshape(-1), _GRID[:, ::-1].reshape(-1), _GRID[::-1, :].reshape(-1), _GRID[::-1, ::-1].reshape(-1), ]) #: Block (4x4 means of a 2x2-pixel block grid... here 4x4 blocks of 2x2 pixels) membership. _BLOCK = (np.arange(TILE)[:, None] // 2) * 4 + (np.arange(TILE)[None, :] // 2) # (8, 8) -> block 0..15 BLOCK_OF_PIXEL = _BLOCK.reshape(-1) BLOCK_MATRIX = np.zeros((TILE * TILE, 16), dtype=np.float32) BLOCK_MATRIX[np.arange(TILE * TILE), BLOCK_OF_PIXEL] = 0.25 _BGRID = np.arange(16).reshape(4, 4) BLOCK_FLIP_PERM = np.stack([ _BGRID.reshape(-1), _BGRID[:, ::-1].reshape(-1), _BGRID[::-1, :].reshape(-1), _BGRID[::-1, ::-1].reshape(-1) ]) LUMA = np.array([0.299, 0.587, 0.114], dtype=np.float32) @dataclass class FrameRecord2: video_frame: int runs: list[tuple[int, int, int]] # (slot, store tile id, count): store ids consecutive patches: list[tuple[int, int]] cram: list[int] | None expected: np.ndarray stats: dict = field(default_factory=dict) class Store: """The ROM tile store plus the per-(line, shade) luma signatures of every tile.""" def __init__(self) -> None: self.pens = np.zeros((STORE_GROWTH, TILE * TILE), dtype=np.uint8) self.n = 1 # tile 0: blank self.sig: dict[tuple[int, int], np.ndarray] = {} # (line, shade) -> (cap, 16) self.sig_valid: dict[tuple[int, int], int] = {} # how many tiles have signatures self.luma_tables: dict[tuple[int, int], np.ndarray] = {} # pen -> luma def set_palette(self, lines: np.ndarray) -> None: self.luma_tables = {} self.sig = {} self.sig_valid = {} for line in range(LINES): for shade in (NORMAL, SHADOW): rgb = raw_to_rgb(lines[line], shade).astype(np.float32) self.luma_tables[(line, shade)] = rgb @ LUMA def add(self, pens64: np.ndarray) -> int: if self.n == len(self.pens): self.pens = np.concatenate([self.pens, np.zeros_like(self.pens)]) self.pens[self.n] = pens64 self.n += 1 return self.n - 1 def truncate(self, n: int) -> None: """Roll the store back to ``n`` tiles (a rejected frame attempt).""" self.n = n for key in self.sig_valid: self.sig_valid[key] = min(self.sig_valid[key], n) def signatures(self, key: tuple[int, int]) -> np.ndarray: """(n, 16) block-mean luma of every stored tile under palette ``key``.""" valid = self.sig_valid.get(key, 0) if valid < self.n: table = self.luma_tables[key] new = table[self.pens[valid : self.n]] @ BLOCK_MATRIX # (k, 16) if key in self.sig and len(self.sig[key]) >= self.n: self.sig[key][valid : self.n] = new else: cap = max(self.n, 2 * len(self.sig.get(key, ())), STORE_GROWTH) arr = np.zeros((cap, 16), dtype=np.float32) if key in self.sig: arr[:valid] = self.sig[key][:valid] arr[valid : self.n] = new self.sig[key] = arr self.sig_valid[key] = self.n return self.sig[key][: self.n] class CodebookEncoder: def __init__(self, keep_tol: float = KEEP_TOL, reuse_tol: float = REUSE_TOL, rom_tol: float = ROM_TOL, rate_floor: float = 0.25) -> None: # fmt: skip self.tols = (keep_tol, reuse_tol, rom_tol) self.rate_mult = 1.0 # the rate controller's current scaling of the tolerances # The floor on that scaling. It exists to stop the feedback loop running away, # but it also caps quality: at 0.25 the controller spent most of the full song # pinned against it, asking for budget it was not allowed to use, while 2 MB of # the cartridge went unspent. Frames that cannot afford a tighter tolerance are # already caught by the VBlank budget, which doubles tolerances and retries. self.rate_floor = rate_floor # Per-cell tolerance multipliers for the frame being encoded (rrmd.roi), or None # for uniform tolerances. Set by encode_clip before each frame. self.roi: np.ndarray | None = None self.eff_mult = 1.0 # the multiplier the last frame actually encoded at (after any retry) self.store = Store() self.slot_tile = np.full(RING_END, -1, dtype=np.int64) # slot -> store id self.slot_tile[0] = 0 self.tile_slot: dict[int, int] = {0: 0} # store id -> slot while resident self.head = 1 self.shown = np.full((CELLS, 4), -1, dtype=np.int64) # (slot, flip, line, shade) self.shown_words = np.zeros(CELLS, dtype=np.uint16) self.lines: np.ndarray | None = None # -- helpers -- @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 _view(self, tile: int, flip: int) -> np.ndarray: return self.store.pens[tile][FLIP_PERM[flip]] def _error(self, c: np.ndarray, tile: int, flip: int) -> float: return float(c[_PIX, self._view(tile, flip)].sum()) def _candidates(self, cell_sig: np.ndarray, key: tuple[int, int], ids: np.ndarray | None, k: int) -> list[tuple[int, int]]: """Top-k (tile, flip) by signature distance, over ``ids`` or the whole store.""" sigs = self.store.signatures(key) # (n, 16) if ids is not None: if len(ids) == 0: return [] sigs = sigs[ids] n = len(sigs) dists = np.empty((4, n), dtype=np.float32) for f in range(4): d = sigs[:, BLOCK_FLIP_PERM[f]] - cell_sig[None, :] dists[f] = np.einsum("ij,ij->i", d, d) if ids is None: dists[:, 0] = np.inf # tile 0 is the blank, never a candidate flat = dists.reshape(-1) k = min(k, flat.size) idx = np.argpartition(flat, k - 1)[:k] if k < flat.size else np.arange(flat.size) idx = idx[np.isfinite(flat[idx])] out = [] for i in idx: t = int(i % n) out.append((int(ids[t]) if ids is not None else t, int(i // n))) return out def _alloc(self, busy: np.ndarray) -> int: 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 # -- state snapshots around a frame attempt -- def _snapshot(self, n0: int) -> tuple: """Everything a greedy pass mutates: new store tiles since ``n0``, the slot map, the ring head and what is on screen.""" return (self.store.n, self.store.pens[n0 : self.store.n].copy(), self.slot_tile.copy(), dict(self.tile_slot), self.head, self.shown, self.shown_words) # fmt: skip def _restore(self, n0: int, snap: tuple) -> None: n, pens, slot_tile, tile_slot, head, shown, shown_words = snap self.store.truncate(n0) self.store.pens[n0:n] = pens self.store.n = n self.slot_tile = slot_tile.copy() self.tile_slot = dict(tile_slot) self.head = head self.shown = shown self.shown_words = shown_words # -- one frame -- def encode_frame(self, rgb: np.ndarray, video_frame: int, new_palette: bool) -> FrameRecord2: assert self.lines is not None costs = cost_tables(rgb, self.lines) best_err = costs.min(axis=-1).sum(axis=-1) 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) cell_luma = _cell_pixels(rgb) @ LUMA # (CELLS, 64) cell_sig = cell_luma @ BLOCK_MATRIX # (CELLS, 16) # A frame that will not fit the VBlank budget has its tolerances raised and is # tried again. The old escape hatch doubled the tolerances until a pass fit, and # across the full song that is what set the quality: about 85% of frames were # budget-bound, and the first rung of a x2 ladder that fits lands at roughly half # the 40k-cycle budget on average, so half the DMA time the hardware offers went # unused. Now the climb is followed by a geometric bisection between the last # failing and the first fitting multiplier, down to RETRY_RESOLUTION, so the frame # encodes near the tightest tolerance the budget allows. A fitting attempt is # snapshotted rather than re-run when a tighter one is tried next. The climb's # range is absolute (RETRY_CEILING) so it reaches the hardest cuts from any # starting multiplier. n0 = self.store.n pre = self._snapshot(n0) def attempt_at(m: float): self._restore(n0, pre) tols = tuple(t * m for t in self.tols) rec = self._try(rgb, video_frame, new_palette, costs, base, best_line, best_shade, best_pens, cell_sig, tols) if rec is None: return None rec.stats["tols"] = [t / (TILE * TILE) for t in tols] return rec, self._snapshot(n0) mult = self.rate_mult attempts = 0 hit = attempt_at(mult) if hit is None: lo = hi = mult # lo always fails; hi is the first multiplier that fit # The controller usually stepped down from the multiplier the previous frame # fit at, and neighbouring frames are alike, so that multiplier is the first # rung to try: when it fits, the bisection has a bracket a quarter the width # of a doubling and the frame costs three passes instead of five. if self.eff_mult > mult: hi = self.eff_mult attempts += 1 hit = attempt_at(hi) if hit is None: lo = hi while hit is None: if hi * 2 > RETRY_CEILING: raise RuntimeError(f"frame {video_frame}: over budget at every tolerance " f"up to {hi:.2f}x the base") # fmt: skip lo, hi = hi, hi * 2 attempts += 1 hit = attempt_at(hi) while hi / lo > RETRY_RESOLUTION: mid = (lo * hi) ** 0.5 attempts += 1 h = attempt_at(mid) if h is None: lo = mid else: hi, hit = mid, h mult = hi rec, post = hit self._restore(n0, post) self.eff_mult = mult rec.stats["attempt"] = attempts rec.stats["mult"] = mult rec.stats["bytes"] = 32 * rec.stats["new"] + 140 + 2 * rec.stats["patches"] + DESCRIPTOR_BYTES * rec.stats["runs"] return rec def rate_update(self, frame_bytes: int, target: float, cum_over_frames: float) -> None: """Steer the tolerance multiplier toward ``target`` bytes/frame: a nudge from the last frame's miss plus a slower pull from how many frames' worth of budget the stream is over (or under) so far. Clamped so one odd frame cannot run away. The step starts from the multiplier the last frame *actually* encoded at, not the one the controller asked for: when the VBlank budget forced a retry, asking for the old value again only buys the same climb. The cumulative term is bounded per frame, otherwise a long budget-bound stretch (bytes under target for hundreds of frames, through no fault of the tolerance) winds it up until it drags the multiplier to the floor every frame regardless of what the last frame needed.""" last = (frame_bytes - target) / target integral = float(np.clip(0.03 * cum_over_frames, -RATE_INTEGRAL_CLAMP, RATE_INTEGRAL_CLAMP)) self.rate_mult = self.eff_mult * float(np.exp(0.12 * last + integral)) self.rate_mult = float(np.clip(self.rate_mult, self.rate_floor, 64.0)) def _try(self, rgb, video_frame, new_palette, costs, base, best_line, best_shade, best_pens, cell_sig, tols): keep_tol, reuse_tol, rom_tol = tols saved = (self.store.n, self.slot_tile.copy(), dict(self.tile_slot), 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 dma: list[tuple[int, int]] = [] # (slot, tile) in order counts = {"keep": 0, "vram": 0, "rom": 0, "new": 0, "forced": 0} err_total = 0.0 cycles = 0.0 def resident_ids() -> np.ndarray: return np.fromiter((t for t in self.tile_slot if t > 0), dtype=np.int64, count=len(self.tile_slot) - 1) def pay(slot: int, tile: int) -> None: nonlocal cycles if dma and dma[-1][0] + 1 == slot and dma[-1][1] + 1 == tile: cycles += TILE_DMA_CYCLES else: cycles += DESCRIPTOR_CYCLES + TILE_DMA_CYCLES dma.append((slot, tile)) order = np.argsort(-base) for cell in order: cell = int(cell) line, shade = int(best_line[cell]), int(best_shade[cell]) key = (line, shade) b = float(base[cell]) wc = float(self.roi[cell]) if self.roi is not None else 1.0 # region weight c = costs[line, shade, cell] # 1. keep s0, f0, l0, sh0 = (int(v) for v in self.shown[cell]) if s0 > 0 and self.slot_tile[s0] >= 0: e = float(costs[l0, sh0, cell][_PIX, self._view(int(self.slot_tile[s0]), f0)].sum()) if e <= b + keep_tol * wc: entries[cell] = (s0, f0, l0, sh0) busy[s0] = True counts["keep"] += 1 err_total += e continue # 2. a tile resident in VRAM cands = self._candidates(cell_sig[cell], key, resident_ids(), TOP_K) best_v = (np.inf, -1, -1) for tile, flip in cands: e = self._error(c, tile, flip) if e < best_v[0]: best_v = (e, tile, flip) if best_v[1] >= 0 and best_v[0] <= b + reuse_tol * wc: slot = self.tile_slot[best_v[1]] entries[cell] = (slot, best_v[2], line, shade) busy[slot] = True counts["vram"] += 1 err_total += best_v[0] continue # 3. a tile already in ROM cands = self._candidates(cell_sig[cell], key, None, TOP_K) best_r = (np.inf, -1, -1) for tile, flip in cands: if tile in self.tile_slot: continue e = self._error(c, tile, flip) if e < best_r[0]: best_r = (e, tile, flip) slot = self._alloc(busy) if slot < 0: # ring full: fall back to the nearest resident tile regardless of tolerance if best_v[1] >= 0: s = self.tile_slot[best_v[1]] entries[cell] = (s, best_v[2], line, shade) busy[s] = True err_total += best_v[0] else: entries[cell] = (0, 0, line, shade) err_total += float(c[:, 0].sum()) counts["forced"] += 1 continue if best_r[1] >= 0 and best_r[0] <= b + rom_tol * wc: tile, flip, e = best_r[1], best_r[2], best_r[0] counts["rom"] += 1 else: tile, flip, e = self.store.add(best_pens[cell]), 0, b counts["new"] += 1 # evict whatever the slot held, install the tile old = int(self.slot_tile[slot]) if old > 0: self.tile_slot.pop(old, None) self.slot_tile[slot] = tile self.tile_slot[tile] = slot busy[slot] = True pay(slot, tile) entries[cell] = (slot, flip, line, shade) err_total += e if cycles > VBLANK_BUDGET_CYCLES: n0, self.slot_tile, self.tile_slot, self.head = saved self.store.truncate(n0) return None 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] # fmt: skip runs: list[list[int]] = [] for slot, tile in dma: if runs and runs[-1][0] + runs[-1][2] == slot and runs[-1][1] + runs[-1][2] == tile: runs[-1][2] += 1 else: runs.append([slot, tile, 1]) expected = self._render(entries) self.shown = entries self.shown_words = words 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 = dict(counts) stats.update({ "patches": len(patches), "runs": len(runs), "dma_cycles": int(cycles), "error_per_pixel": err_total / (WIDTH * HEIGHT), "base_error_per_pixel": float(base.sum()) / (WIDTH * HEIGHT), "store_tiles": self.store.n, }) # fmt: skip return FrameRecord2(video_frame, [tuple(r) for r in runs], 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._view(int(self.slot_tile[slot]), flip).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) def fit_shot_lines(frames: list[np.ndarray]) -> np.ndarray: """The shot's four palette lines from a sample of its frames: median cut for a start, then rrmd.palette's Lloyd rounds on the DAC lattice under the encoder's metric. Measured over the 109 shots of the song (tools/palette_study.py, saturation 1.3): colour floor -24 % song-weighted on held-out frames, every shot improved, ~6 s a shot.""" step = max(1, len(frames) // SHOT_SAMPLE_FRAMES) sample = frames[::step][:SHOT_SAMPLE_FRAMES] lines, _history = fit_lines_lloyd(np.concatenate(sample, axis=0)) return lines def denoise_temporal(frames: list[np.ndarray], threshold: float, blend: float) -> list[np.ndarray]: """Recursive per-pixel temporal filter: where a pixel moved less than ``threshold`` (per channel) since the filtered previous frame it is blended ``blend`` toward it; elsewhere it is taken as is. Tape noise averages out, motion is left alone.""" out = [frames[0].astype(np.float32)] for f in frames[1:]: cur = f.astype(np.float32) prev = out[-1] still = np.all(np.abs(cur - prev) < threshold, axis=-1, keepdims=True) out.append(np.where(still, prev * blend + cur * (1 - blend), cur)) return [np.clip(np.rint(f), 0, 255).astype(np.uint8) for f in out] def original_error(expected: np.ndarray, original: np.ndarray) -> float: diff = expected.astype(np.float64) - original.astype(np.float64) return float(np.sum(diff * diff * LUMA_W) / (WIDTH * HEIGHT)) def encode_clip(paths: list[Path], out: Path, limit: int | None = None, tols_per_pixel: tuple[float, float, float] | None = None, target_frame_bytes: float | None = None, denoise: tuple[float, float] | None = None, rate_floor: float = 0.25, roi: Path | None = None, saturation: float = 1.0, roi_weights: tuple[float, float, float] | None = None, first: int = 0) -> None: # fmt: skip from .roi import load_roi, saturate originals = [load_picture(p) for p in paths[first : (first + limit) if limit else None]] raw = originals if saturation != 1.0: # The adjusted picture is the target from here on; `raw` keeps the real source # so error_vs_original still means what it says. originals = [saturate(f, saturation) for f in originals] if roi_weights: from .roi import set_weights set_weights(*roi_weights) weights = load_roi(roi, first + len(originals))[first:] if roi else None # indexed by source frame frames = denoise_temporal(originals, *denoise) if denoise else originals shots = detect_shots(frames) shot_ends = shots[1:] + [len(frames)] print(f"{len(frames)} frames, {len(shots)} shots at {shots}", flush=True) enc = (CodebookEncoder(*(t * TILE * TILE for t in tols_per_pixel), rate_floor=rate_floor) if tols_per_pixel else CodebookEncoder(rate_floor=rate_floor)) cum_bytes = 0 records: list[FrameRecord2] = [] expected_dir = out / "expected" expected_dir.mkdir(parents=True, exist_ok=True) for old in expected_dir.glob("*.png"): old.unlink() for shot, (start, end) in enumerate(zip(shots, shot_ends)): enc.lines = fit_shot_lines(frames[start:end]) enc.store.set_palette(enc.lines) for i in range(start, end): enc.roi = weights[i] if weights else None rec = enc.encode_frame(frames[i], i, new_palette=(i == start)) rec.stats["error_vs_original"] = original_error(rec.expected, raw[i]) records.append(rec) Image.fromarray(rec.expected).save(expected_dir / f"e{i:05d}.png") s = rec.stats cum_bytes += s["bytes"] if target_frame_bytes: enc.rate_update(s["bytes"], target_frame_bytes, (cum_bytes - target_frame_bytes * (i + 1)) / target_frame_bytes) print(f"frame {i:4d} shot {shot:2d}: keep {s['keep']:4d} vram {s['vram']:4d} rom {s['rom']:4d} new {s['new']:4d} " f"forced {s['forced']:3d} patches {s['patches']:4d} runs {s['runs']:3d} cyc {s['dma_cycles']:6d} " f"err {s['error_per_pixel']:6.1f} (base {s['base_error_per_pixel']:6.1f}) store {s['store_tiles']:6d} " f"bytes {s['bytes']:5d} mult {enc.rate_mult:5.2f} attempt {s['attempt']} eff {s['mult']:5.2f}", flush=True) # Both arrays are dead now: the prediction has been scored and written out, # and this source frame will not be read again - its shot's palette lines # were fitted before the loop over the shot began. Holding all 5,274 of each # costs about 2.3 GB, which gets a full-song encode killed part-way through. rec.expected = None frames[i] = None if originals is not frames: originals[i] = None if raw is not originals: raw[i] = None patch_bytes = sum(140 + 2 * len(r.patches) for r in records) # packed: change mask + words errs = [r.stats["error_per_pixel"] for r in records] bases = [r.stats["base_error_per_pixel"] for r in records] vs_orig = [r.stats["error_vs_original"] for r in records] summary = { "frames": len(records), "shots": shots, "store_tiles": enc.store.n, "store_bytes": enc.store.n * 32, "patch_bytes": patch_bytes, "descriptor_bytes": sum(DESCRIPTOR_BYTES * len(r.runs) for r in records), "mean_error_per_pixel": sum(errs) / len(errs), "mean_base_error_per_pixel": sum(bases) / len(bases), "mean_error_vs_original": sum(vs_orig) / len(vs_orig), "denoise": denoise, "tols_per_pixel": [t / (TILE * TILE) for t in enc.tols], "target_frame_bytes": target_frame_bytes, "mean_frame_bytes": cum_bytes / len(records), "final_rate_mult": enc.rate_mult, "rate_floor": rate_floor, "roi": str(roi) if roi else None, "saturation": saturation, } (out / "summary.json").write_text(json.dumps(summary, indent=2)) print(json.dumps(summary, indent=2)) slim = [FrameRecord2(r.video_frame, r.runs, r.patches, r.cram, np.zeros(0), r.stats) for r in records] with (out / "records2.pkl").open("wb") as f: pickle.dump((slim, enc.store.pens[: enc.store.n].copy()), f)