"""Phase-2 codec study (offline only): what a 32X decoder could show at a byte budget. Candidate C1, "MPEG-lite": 16x16 macroblocks, full-pel motion compensation from the previous decoded frame, 8x8 DCT residuals, 4:2:0 YCbCr kept as 8-bit planes in SDRAM (the decoder's reference), shown either as 8bpp packed pixel through a per-scene 256-colour palette (D3) or as direct colour (RGB555). The encoder below *is* the decoder's spec: every recon is the integer result a decoder would produce. Rates are counted exactly from a real code (signed/unsigned Exp-Golomb for motion vectors, DC and run-level pairs with a last flag, 6-bit CBP), except the per-MB mode symbol, which is charged at its adaptive entropy (previous frame's counts): a small adaptive arithmetic coder on the SH-2 would realise it. Palettes cost 512 bytes each. Error is the MD project's metric (rrmd ``original_error``): luma-weighted squared RGB error per pixel against ``rrmd.encode.load_picture`` of the source field, so numbers compare directly with the MD build (``out/full-lloyd`` expected frames). py -3.12 study/codec_study.py --first 0 --count 375 --budget 675 --out out32/study """ from __future__ import annotations import argparse import json import math import sys import time from pathlib import Path import numpy as np from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from rrmd.encode import LUMA_W, load_picture # noqa: E402 FIELDS = Path(r"D:\dev\rick-roll-md\fields") MD_EXPECTED = Path(r"D:\dev\rick-roll-md\out\full-lloyd\expected") W, H = 320, 224 MBX, MBY = W // 16, H // 16 PAL_BYTES = 512 FRAME_HEADER_BYTES = 2 PALETTE_REFRESH = 50 # frames: a long shot drifts; refit at least every 2 s # -- colour ------------------------------------------------------------------------ def rgb_to_ycc(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: f = rgb.astype(np.float32) r, g, b = f[..., 0], f[..., 1], f[..., 2] y = 0.299 * r + 0.587 * g + 0.114 * b cb = -0.168736 * r - 0.331264 * g + 0.5 * b + 128.0 cr = 0.5 * r - 0.418688 * g - 0.081312 * b + 128.0 sub = lambda p: p.reshape(H // 2, 2, W // 2, 2).mean(axis=(1, 3)) # noqa: E731 return y, sub(cb), sub(cr) def ycc_to_rgb(y: np.ndarray, cb: np.ndarray, cr: np.ndarray) -> np.ndarray: """Integer planes -> float RGB (H, W, 3), chroma upsampled by repetition (what a decoder does cheaply).""" up = lambda p: np.repeat(np.repeat(p, 2, axis=0), 2, axis=1).astype(np.float32) - 128.0 # noqa: E731 yf, u, v = y.astype(np.float32), up(cb), up(cr) rgb = np.stack([yf + 1.402 * v, yf - 0.344136 * u - 0.714136 * v, yf + 1.772 * u], axis=-1) return np.clip(rgb, 0.0, 255.0) def weighted_sse(a: np.ndarray, b: np.ndarray) -> np.ndarray: d = a.astype(np.float32) - b.astype(np.float32) return np.sum(d * d * LUMA_W.astype(np.float32), axis=-1) def mb_sum(per_pixel: np.ndarray) -> np.ndarray: return per_pixel.reshape(MBY, 16, MBX, 16).sum(axis=(1, 3)) def rgb555(rgb: np.ndarray) -> np.ndarray: """float RGB -> the 5-bit levels (H, W, 3) uint8.""" return np.clip(np.rint(rgb * (31.0 / 255.0)), 0, 31).astype(np.uint8) def expand555(v: np.ndarray) -> np.ndarray: v = v.astype(np.uint16) return ((v << 3) | (v >> 2)).astype(np.uint8) # -- transform and quantisation ----------------------------------------------------- _k = np.arange(8) DCT = np.sqrt(2.0 / 8.0) * np.cos((2 * _k[None, :] + 1) * _k[:, None] * np.pi / 16.0) DCT[0, :] = np.sqrt(1.0 / 8.0) DCT = DCT.astype(np.float32) MPEG_INTRA = np.array([ [8, 16, 19, 22, 26, 27, 29, 34], [16, 16, 22, 24, 27, 29, 34, 37], [19, 22, 26, 27, 29, 34, 34, 38], [22, 22, 26, 27, 29, 34, 37, 40], [22, 26, 27, 29, 32, 35, 40, 48], [26, 27, 29, 32, 35, 40, 48, 58], [26, 27, 29, 34, 38, 46, 56, 69], [27, 29, 35, 38, 46, 56, 69, 83], ], dtype=np.float32) / 16.0 # fmt: skip def _zigzag() -> np.ndarray: order = sorted(((u, v) for u in range(8) for v in range(8)), key=lambda p: (p[0] + p[1], p[1] if (p[0] + p[1]) % 2 else p[0])) return np.array([u * 8 + v for u, v in order]) ZIGZAG = _zigzag() def fdct(b: np.ndarray) -> np.ndarray: return np.einsum("ij,...jk,lk->...il", DCT, b, DCT, optimize=True) def idct(c: np.ndarray) -> np.ndarray: return np.einsum("ji,...jk,kl->...il", DCT, c, DCT, optimize=True) def quantise(c: np.ndarray, step: np.ndarray, rounding: float) -> np.ndarray: a = np.abs(c) / step return (np.sign(c) * np.floor(a + rounding)).astype(np.int32) def ue_bits(v: np.ndarray) -> np.ndarray: return 2 * np.floor(np.log2(v.astype(np.float64) + 1.0)) + 1 def se_bits(v: np.ndarray) -> np.ndarray: v = np.asarray(v) return ue_bits(np.where(v > 0, 2 * v - 1, -2 * v)) def runlevel_bits(levels: np.ndarray, start: int) -> tuple[np.ndarray, np.ndarray]: """(N, 8, 8) quantised -> (bits, nonzero count) per block, zigzag from ``start``, each pair ue(run) + ue(magnitude/sign) + 1 last-flag bit.""" n = levels.shape[0] zz = levels.reshape(n, 64)[:, ZIGZAG][:, start:] nz = zz != 0 idx = np.arange(zz.shape[1]) pos = np.where(nz, idx, -1) prev = np.maximum.accumulate(np.concatenate([np.full((n, 1), -1), pos[:, :-1]], axis=1), axis=1) run = idx[None, :] - prev - 1 a = np.abs(zz) vmap = 2 * np.maximum(a - 1, 0) + (zz < 0) bits = np.where(nz, ue_bits(run) + ue_bits(vmap) + 1, 0).sum(axis=1) return bits, nz.sum(axis=1) # -- block layout ------------------------------------------------------------------- def y_blocks(p: np.ndarray) -> np.ndarray: """(H, W) -> (MBY, MBX, 4, 8, 8), the MB's four luma blocks in raster order.""" b = p.reshape(MBY, 2, 8, MBX, 2, 8).transpose(0, 3, 1, 4, 2, 5) return b.reshape(MBY, MBX, 4, 8, 8) def y_unblocks(b: np.ndarray) -> np.ndarray: return b.reshape(MBY, MBX, 2, 2, 8, 8).transpose(0, 2, 4, 1, 3, 5).reshape(H, W) def c_blocks(p: np.ndarray) -> np.ndarray: return p.reshape(MBY, 8, MBX, 8).transpose(0, 2, 1, 3) def c_unblocks(b: np.ndarray) -> np.ndarray: return b.transpose(0, 2, 1, 3).reshape(H // 2, W // 2) # -- motion ------------------------------------------------------------------------- SEARCH_HALF = 8 # +-8 at half resolution = +-16 full-pel PAD = 2 * SEARCH_HALF + 2 def motion_search(cur_y: np.ndarray, ref_y: np.ndarray, lam: float) -> np.ndarray: """(MBY, MBX, 2) full-pel (dy, dx): half-resolution full search, then +-1 refine. Cost SAD + lam * mv bits (zero predictor).""" c2 = cur_y.reshape(H // 2, 2, W // 2, 2).mean(axis=(1, 3)) r2 = ref_y.astype(np.float32).reshape(H // 2, 2, W // 2, 2).mean(axis=(1, 3)) s = SEARCH_HALF r2p = np.pad(r2, s, mode="edge") best = np.full((MBY, MBX), np.inf, np.float32) mv = np.zeros((MBY, MBX, 2), np.int32) for dy in range(-s, s + 1): for dx in range(-s, s + 1): shifted = r2p[s + dy : s + dy + H // 2, s + dx : s + dx + W // 2] sad = np.abs(c2 - shifted).reshape(MBY, 8, MBX, 8).sum(axis=(1, 3)) * 4.0 sad += lam * float(se_bits(2 * dy) + se_bits(2 * dx)) better = sad < best best = np.where(better, sad, best) mv[better] = (2 * dy, 2 * dx) refp = np.pad(ref_y.astype(np.float32), PAD, mode="edge") out = mv.copy() for my in range(MBY): for mx in range(MBX): cb = cur_y[my * 16 : my * 16 + 16, mx * 16 : mx * 16 + 16] cands = {(0, 0)} | {(int(mv[my, mx, 0]) + a, int(mv[my, mx, 1]) + b) for a in (-1, 0, 1) for b in (-1, 0, 1)} bc, bv = np.inf, (0, 0) for vy, vx in cands: y0, x0 = PAD + my * 16 + vy, PAD + mx * 16 + vx cost = float(np.abs(cb - refp[y0 : y0 + 16, x0 : x0 + 16]).sum()) + lam * float(se_bits(vy) + se_bits(vx)) if cost < bc: bc, bv = cost, (vy, vx) out[my, mx] = bv return out def predict(ref: tuple[np.ndarray, np.ndarray, np.ndarray], mv: np.ndarray) -> tuple[np.ndarray, ...]: """Motion-compensated prediction; chroma vectors are luma >> 1 (floor).""" ry = np.pad(ref[0], PAD, mode="edge") rc = [np.pad(p, PAD // 2 + 1, mode="edge") for p in ref[1:]] cp = PAD // 2 + 1 py = np.empty((H, W), np.uint8) pc = [np.empty((H // 2, W // 2), np.uint8) for _ in range(2)] for my in range(MBY): for mx in range(MBX): vy, vx = int(mv[my, mx, 0]), int(mv[my, mx, 1]) py[my * 16 : my * 16 + 16, mx * 16 : mx * 16 + 16] = ry[PAD + my * 16 + vy : PAD + my * 16 + vy + 16, PAD + mx * 16 + vx : PAD + mx * 16 + vx + 16] cy, cx = vy >> 1, vx >> 1 for k in range(2): pc[k][my * 8 : my * 8 + 8, mx * 8 : mx * 8 + 8] = rc[k][cp + my * 8 + cy : cp + my * 8 + cy + 8, cp + mx * 8 + cx : cp + mx * 8 + cx + 8] return py, pc[0], pc[1] # -- one frame at one quantiser ------------------------------------------------------ SKIP, INTER0, INTER, INTRA = range(4) class FrameCoder: def __init__(self, src_rgb: np.ndarray, src_ycc, ref, pred, mv, mode_bits: np.ndarray): self.src_rgb = src_rgb self.src = src_ycc self.ref = ref self.pred = pred self.mv = mv self.mode_bits = mode_bits self.ref_rgb_err = mb_sum(weighted_sse(ycc_to_rgb(*ref), src_rgb)) self.pred_rgb_err = mb_sum(weighted_sse(ycc_to_rgb(*pred), src_rgb)) # Residual and intra transforms do not depend on the quantiser. self.inter_c = self._dct_planes([s - p.astype(np.float32) for s, p in zip(src_ycc, pred)]) self.intra_c = self._dct_planes([s - 128.0 for s in src_ycc]) @staticmethod def _dct_planes(planes): y, cb, cr = planes return fdct(y_blocks(y)), fdct(c_blocks(cb)), fdct(c_blocks(cr)) @staticmethod def _recon(base, coeffs): """base planes (uint8) + idct(coeffs) -> uint8 planes.""" y = y_unblocks(idct(coeffs[0])) + base[0] cb = c_unblocks(idct(coeffs[1])) + base[1] cr = c_unblocks(idct(coeffs[2])) + base[2] return tuple(np.clip(np.rint(p), 0, 255).astype(np.uint8) for p in (y, cb, cr)) def code(self, q: float, lam: float): # Inter: flat matrix, dead-zone rounding. step_n = np.float32(q) lv_inter = [quantise(c, step_n, 1.0 / 6.0) for c in self.inter_c] # Intra: MPEG matrix for AC, DC step 8. step_i = (q * MPEG_INTRA).astype(np.float32).copy() step_i[0, 0] = 8.0 lv_intra = [quantise(c, step_i, 1.0 / 3.0) for c in self.intra_c] # Bits per MB. def blockwise(levels, start): shp = levels.shape[:-2] bits, cnt = runlevel_bits(levels.reshape(-1, 8, 8), start) return bits.reshape(shp), cnt.reshape(shp) by, cy = blockwise(lv_inter[0], 0) # (MBY, MBX, 4) bcb, ccb = blockwise(lv_inter[1], 0) bcr, ccr = blockwise(lv_inter[2], 0) inter_coef_bits = by.sum(axis=-1) + bcb + bcr inter_coded = (cy > 0).sum(axis=-1) + (ccb > 0) + (ccr > 0) mvb = se_bits(self.mv[..., 0]) + se_bits(self.mv[..., 1]) # zero predictor (decision only) ay, _ = blockwise(lv_intra[0], 1) acb, _ = blockwise(lv_intra[1], 1) acr, _ = blockwise(lv_intra[2], 1) dc = [lv_intra[0][..., 0, 0], lv_intra[1][..., 0, 0], lv_intra[2][..., 0, 0]] dc_bits = se_bits(dc[0][..., 0]) + se_bits(np.diff(dc[0], axis=-1)).sum(axis=-1) + se_bits(dc[1]) + se_bits(dc[2]) intra_bits = dc_bits + ay.sum(axis=-1) + acb + acr + 6 # 6 "has AC" flags bits = np.stack([ np.full((MBY, MBX), self.mode_bits[SKIP]), self.mode_bits[INTER0] + mvb, self.mode_bits[INTER] + mvb + 6 + inter_coef_bits, self.mode_bits[INTRA] + intra_bits, ]) # fmt: skip deq_inter = [lv.astype(np.float32) * step_n for lv in lv_inter] deq_intra = [lv.astype(np.float32) * step_i for lv in lv_intra] rec_inter = self._recon(self.pred, deq_inter) k128 = tuple(np.full_like(p, 128, dtype=np.uint8) for p in self.pred) rec_intra = self._recon(k128, deq_intra) dist = np.stack([ self.ref_rgb_err, self.pred_rgb_err, mb_sum(weighted_sse(ycc_to_rgb(*rec_inter), self.src_rgb)), mb_sum(weighted_sse(ycc_to_rgb(*rec_intra), self.src_rgb)), ]) # fmt: skip mode = np.argmin(dist + lam * bits, axis=0) # Assemble the decoder's frame. recs = [self.ref, self.pred, rec_inter, rec_intra] out = [] for k in range(3): if k == 0: stack = np.stack([y_blocks(r[0].astype(np.float32)) for r in recs]) pick = np.take_along_axis(stack, mode[None, :, :, None, None, None], axis=0)[0] out.append(y_unblocks(pick).astype(np.uint8)) else: stack = np.stack([c_blocks(r[k].astype(np.float32)) for r in recs]) pick = np.take_along_axis(stack, mode[None, :, :, None, None], axis=0)[0] out.append(c_unblocks(pick).astype(np.uint8)) # Exact bits with the real predictors (raster order; left MB's sent vector). total = 0.0 sent_mv = np.where(np.isin(mode, (INTER0, INTER))[..., None], self.mv, 0) for my in range(MBY): left = np.zeros(2, np.int32) for mx in range(MBX): m = int(mode[my, mx]) total += self.mode_bits[m] if m in (INTER0, INTER): d = self.mv[my, mx] - left total += float(se_bits(d[0]) + se_bits(d[1])) left = self.mv[my, mx] if m == INTER: total += 6 + float(inter_coef_bits[my, mx]) elif m == INTRA: total += float(intra_bits[my, mx]) counts = np.bincount(mode.ravel(), minlength=4) stats = { "coded_blocks": int(np.where(mode == INTER, inter_coded, 0).sum() + 6 * counts[INTRA]), "mc_mbs": int(counts[INTER0] + counts[INTER]), "intra_mbs": int(counts[INTRA]), "skip_mbs": int(counts[SKIP]), } return tuple(out), total, mode, stats, sent_mv # -- palettes for the 8bpp view ------------------------------------------------------ def fit_palette(samples: np.ndarray, colours: int = 256, rounds: int = 10, seed: int = 1) -> np.ndarray: """Luma-weighted k-means on (N, 3) RGB -> (colours, 3) RGB555 levels.""" rng = np.random.default_rng(seed) uniq = np.unique(rgb555(samples.astype(np.float32)), axis=0) if len(uniq) <= colours: # the samples fit exactly return np.concatenate([uniq, np.repeat(uniq[:1], colours - len(uniq), axis=0)]) pts = samples.astype(np.float32) w = np.sqrt(LUMA_W).astype(np.float32) pw = pts * w # Seed from distinct colours (identical seeds stay identical and waste entries). cent = expand555(uniq[rng.choice(len(uniq), colours, replace=False)]).astype(np.float32) * w for _ in range(rounds): d = (pw * pw).sum(1)[:, None] - 2 * pw @ cent.T + (cent * cent).sum(1)[None, :] lab = d.argmin(1) worst = np.argsort(-d[np.arange(len(pw)), lab]) spare = 0 for k in range(colours): sel = lab == k if sel.any(): cent[k] = pw[sel].mean(0) else: # reseed an empty entry on the worst-served sample cent[k] = pw[worst[spare]] spare += 1 pal = rgb555(cent / w) # Entries that round to the same RGB555 colour: move the repeats to the worst samples. _, first = np.unique(pal, axis=0, return_index=True) dup = np.setdiff1d(np.arange(colours), first) if len(dup): pr = expand555(pal[first]).astype(np.float32) * w dd = ((pw[:, None, :] - pr[None, :, :]) ** 2).sum(-1).min(1) order = np.argsort(-dd) cand = np.unique(rgb555(pts[order[: 50 * len(dup)]]), axis=0) cand = cand[~(cand[:, None, :] == pal[first][None, :, :]).all(-1).any(1)] pal[dup[: len(cand)]] = cand[: len(dup)] return pal def palette_lut(pal555: np.ndarray) -> np.ndarray: """(256, 3) RGB555 -> (32768,) nearest-entry table indexed by r<<10|g<<5|b.""" lv = expand555(np.arange(32)).astype(np.float32) grid = np.stack(np.meshgrid(lv, lv, lv, indexing="ij"), -1).reshape(-1, 3) pr = expand555(pal555).astype(np.float32) w = LUMA_W.astype(np.float32) out = np.empty(len(grid), np.uint8) for i in range(0, len(grid), 4096): g = grid[i : i + 4096] d = (((g[:, None, :] - pr[None, :, :]) ** 2) * w).sum(-1) out[i : i + 4096] = d.argmin(1) return out def scene_cuts(frames: list[np.ndarray]) -> list[int]: cuts = [0] prev_h = None for i, f in enumerate(frames): y = (0.299 * f[..., 0] + 0.587 * f[..., 1] + 0.114 * f[..., 2]).ravel() h = np.histogram(y, bins=32, range=(0, 256))[0] / y.size if prev_h is not None and np.abs(h - prev_h).sum() > 0.6: cuts.append(i) prev_h = h return cuts def set_width(w: int) -> None: global W, MBX assert w % 16 == 0 W, MBX = w, w // 16 def set_rows(rows: int) -> None: global H, MBY assert rows % 16 == 0 and rows <= 224 H, MBY = rows, rows // 16 # -- the run ------------------------------------------------------------------------ LUT_BYTES = 32768 # a palette's RGB555 -> index table, shipped in ROM ("clip" mode) def run(first: int, count: int, budget: float, out: Path, lam_k: float, save_every: int, pal_mode: str = "scene") -> dict: """pal_mode: "scene" (a palette per shot and every 50 frames, 512 B each; the decoder would have to build each one's lookup table), "clip" (one palette for the clip, its 32 KB lookup table charged as ROM bytes), "none" (direct colour only).""" t0 = time.time() paths = sorted(FIELDS.glob("f*.png"))[first : first + count] src224 = [load_picture(p) for p in paths] disp_rows = (np.arange(224) * H) // 224 # the line table: display line -> stored row if H == 224: src = src224 else: src = [np.asarray(Image.fromarray(f).resize((W, H), Image.LANCZOS)) for f in src224] cuts = scene_cuts(src) if pal_mode == "scene": pal_frames = sorted(set(cuts) | set(range(0, count, PALETTE_REFRESH))) elif pal_mode == "clip": pal_frames = [0] else: pal_frames = [] # Palettes from the source frames of each palette span. pals: dict[int, np.ndarray] = {} rng = np.random.default_rng(7) for j, start in enumerate(pal_frames): end = pal_frames[j + 1] if j + 1 < len(pal_frames) else count idx = np.linspace(start, end - 1, min(6 if pal_mode == "scene" else 24, end - start)).astype(int) pix = np.concatenate([src[i].reshape(-1, 3)[rng.choice(W * H, 4000, replace=False)] for i in idx]) pals[start] = fit_palette(pix) out.mkdir(parents=True, exist_ok=True) ref = (np.full((H, W), 16, np.uint8), np.full((H // 2, W // 2), 128, np.uint8), np.full((H // 2, W // 2), 128, np.uint8)) mode_counts = np.array([1.0, 1.0, 1.0, 50.0]) reservoir = 0.0 q_prev = 16.0 rows = [] lut = None cur_pal = None for i in range(count): if i in pals: cur_pal = pals[i] lut = palette_lut(cur_pal) src_rgb = src[i].astype(np.float32) src_ycc = rgb_to_ycc(src_rgb) mv = motion_search(src_ycc[0], ref[0], lam=max(1.0, q_prev * 0.6)) pred = predict(ref, mv) p = mode_counts / mode_counts.sum() mode_bits = -np.log2(p) coder = FrameCoder(src_rgb, src_ycc, ref, pred, mv, mode_bits) extra = FRAME_HEADER_BYTES + (PAL_BYTES + (LUT_BYTES if pal_mode == "clip" else 0) if i in pals else 0) target = budget + 0.25 * reservoir if i in cuts: target += 3 * budget if pal_mode == "clip" and i == 0: target += LUT_BYTES # the table is ROM, not picture: borrow it back over the clip # a cut borrows from the frames after it target = max(0.3 * budget, target) - extra lo, hi = math.log(1.0), math.log(600.0) best = None for _ in range(9): mid = 0.5 * (lo + hi) q = math.exp(mid) res = coder.code(q, lam_k * q * q) if res[1] / 8.0 <= target: best = (q, res) hi = mid else: lo = mid if best is None: q = math.exp(hi) best = (q, coder.code(q, lam_k * q * q)) q, (rec, bits, mode, st, _) = best used = math.ceil(bits / 8.0) + extra reservoir += budget - used mode_counts = 0.5 * mode_counts + 0.5 * (np.bincount(mode.ravel(), minlength=4) + 0.5) q_prev = q ref = rec rgb = ycc_to_rgb(*rec)[disp_rows] d555 = rgb555(rgb) direct = expand555(d555) e = lambda a: float(weighted_sse(a, src224[i]).sum() / (W * 224)) # noqa: E731 if cur_pal is not None: idx = lut[(d555[..., 0].astype(np.int32) << 10) | (d555[..., 1].astype(np.int32) << 5) | d555[..., 2]] pal8 = expand555(cur_pal)[idx] else: pal8 = direct row = {"frame": first + i, "bytes": used, "q": round(q, 2), "err_8bpp": e(pal8), "err_direct": e(direct), "err_ycc": e(rgb), **st} # fmt: skip mdp = MD_EXPECTED / f"e{first + i:05d}.png" if mdp.exists(): row["err_md"] = e(np.asarray(Image.open(mdp).convert("RGB"))) rows.append(row) if save_every and (i % save_every == 0): Image.fromarray(pal8).save(out / f"p{first + i:05d}.png") Image.fromarray(direct).save(out / f"d{first + i:05d}.png") if i % 25 == 0: print(f"{first + i:5d} {used:5d}B q={q:6.1f} 8bpp={row['err_8bpp']:7.1f} md={row.get('err_md', float('nan')):7.1f} " f"skip={st['skip_mbs']} mc={st['mc_mbs']} intra={st['intra_mbs']} {time.time() - t0:6.0f}s", flush=True) # fmt: skip mean = lambda k: float(np.mean([r[k] for r in rows if k in r])) # noqa: E731 summary = { "first": first, "count": count, "budget": budget, "lam_k": lam_k, "mean_bytes": mean("bytes"), "mean_err_8bpp": mean("err_8bpp"), "mean_err_direct": mean("err_direct"), "mean_err_ycc": mean("err_ycc"), "mean_err_md": mean("err_md") if any("err_md" in r for r in rows) else None, "palettes": len(pals), "pal_mode": pal_mode, "rows": H, "cuts": cuts, "max_coded_blocks": max(r["coded_blocks"] for r in rows), "mean_coded_blocks": mean("coded_blocks"), "seconds": round(time.time() - t0, 1), } # fmt: skip (out / "frames.json").write_text(json.dumps(rows)) (out / "summary.json").write_text(json.dumps(summary, indent=2)) print(json.dumps(summary, indent=2)) return summary def main() -> None: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--first", type=int, default=0) ap.add_argument("--count", type=int, default=375) ap.add_argument("--budget", type=float, default=675.0, help="bytes per video frame, all video side info included") ap.add_argument("--lam", type=float, default=0.25, help="lambda = LAM * q^2 (metric units per bit)") ap.add_argument("--save-every", type=int, default=25) ap.add_argument("--pal-mode", choices=("scene", "clip", "none"), default="scene") ap.add_argument("--rows", type=int, default=224, help="stored rows (multiple of 16); the line table repeats rows to 224") ap.add_argument("--out", type=Path, required=True) a = ap.parse_args() set_rows(a.rows) run(a.first, a.count, a.budget, a.out, a.lam, a.save_every, a.pal_mode) if __name__ == "__main__": main()