"""C1 video format, version 3: the spec, in the form of the reference decoder. Picture: 320 x 192 stored rows, 4:2:0 YCbCr 8-bit planes; shown as 32X direct colour (RGB555, priority bit 0) with the line table repeating rows to 224 lines (display line i -> stored row i * 192 // 224). Stream (big-endian): "C1V3" u16 width u16 rows u32 frames then per frame u16 payload length L, L payload bytes. Payload: u16 q u16 H (byte offset of half 2 from the payload's start) u8 S (1-239) half 1 (MBs 0..S-1) from byte 5, half 2 (MBs S..239) from byte H; each half is its own bit run, MSB first, zero-padded to a byte, so the two SH-2s decode one each. The encoder picks S per frame so the two halves cost the SH-2s about the same. Each half codes its macroblocks (16x16, raster order) as: while pos < end: run = ue(); pos += run (run SKIP MBs) if pos == end: stop mode = '1' INTER | '01' INTER0 | '00' INTRA; pos += 1 INTER0/INTER: se(dy - py) se(dx - px); (py, px) = the last vector sent in this MB row and this half, (0, 0) at the start of each. Full-pel; chroma uses (dy >> 1, dx >> 1). Reference samples outside the plane clamp to its edge. INTER: 6-bit CBP (Y0 Y1 Y2 Y3 Cb Cr, MSB first), then for each coded block run-level pairs from zigzag 0: ue(run) ue(vmap) u1(last); vmap = 2(|level| - 1) + (level < 0). coef = level * q. INTRA: per block Y0..Y3 Cb Cr: se(dc') u1(has_ac) [pairs from zigzag 1]; dc' = dc for Y0, Cb, Cr and dc - previous Y dc for Y1..Y3. coef DC = dc * 8, AC = level * max(1, (q * M[k] + 8) >> 4), M = MPEG-1 intra. q is the same for both halves. Reconstruction: INTER/INTER0 = clip(pred + idct), SKIP = the reference, INTRA = clip(128 + idct). idct is the integer two-pass transform below (exact in int32). """ from __future__ import annotations import struct from dataclasses import dataclass import numpy as np W, ROWS = 320, 192 MBX, MBY = W // 16, ROWS // 16 NMB = MBX * MBY DISPLAY_LINES = 224 LINE_ROW = (np.arange(DISPLAY_LINES) * ROWS) // DISPLAY_LINES SKIP, INTER0, INTER, INTRA = range(4) _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) #: K[k][n]: basis k at sample n, x 4096. K = np.rint(_DCT * 4096).astype(np.int64) M_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.int64) # 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 intra_steps(q: int) -> np.ndarray: s = np.maximum(1, (q * M_INTRA + 8) >> 4) s[0, 0] = 8 return s def idct_int(x: np.ndarray) -> np.ndarray: """(..., 8, 8) int coefficients -> (..., 8, 8) int samples, the decoder's exact arithmetic: T = (X K + 2048) >> 12, then out = (K^T T + 2048) >> 12.""" x = x.astype(np.int64) t = (x @ K + 2048) >> 12 return (np.swapaxes(K, 0, 1) @ t + 2048) >> 12 # -- colour ------------------------------------------------------------------------- _c = np.arange(256) - 128 #: Chroma terms in 16.16 fixed point, (K * (c - 128) + 32768) >> 16 (arithmetic shift): #: the decoder may compute them with a multiply or look them up. K_RCR, K_GCB, K_GCR, K_BCB = 91881, -22554, -46802, 116130 RCR = (K_RCR * _c + 32768) >> 16 GCB = (K_GCB * _c + 32768) >> 16 GCR = (K_GCR * _c + 32768) >> 16 BCB = (K_BCB * _c + 32768) >> 16 #: CL5[v + 256]: clip(v, 0, 255) to 5 bits, rounded, for v in -256..511. CL5 = ((np.clip(np.arange(-256, 512), 0, 255) * 31 + 127) // 255).astype(np.int64) def to_rgb555(y: np.ndarray, cb: np.ndarray, cr: np.ndarray) -> np.ndarray: """Planes -> (ROWS, W) uint16 RGB555 words, r | g << 5 | b << 10.""" cbu = np.repeat(np.repeat(cb, 2, 0), 2, 1).astype(np.int64) cru = np.repeat(np.repeat(cr, 2, 0), 2, 1).astype(np.int64) yi = y.astype(np.int64) r = CL5[yi + RCR[cru] + 256] g = CL5[yi + GCB[cbu] + GCR[cru] + 256] b = CL5[yi + BCB[cbu] + 256] return (r | (g << 5) | (b << 10)).astype(np.uint16) def display_rgb(words: np.ndarray) -> np.ndarray: """(ROWS, W) RGB555 -> the 32X's (224, W, 3) picture, levels v << 3 | v >> 2 (sega32x-python's rgb_levels).""" shown = words[LINE_ROW].astype(np.uint16) ch = np.stack([shown & 31, (shown >> 5) & 31, (shown >> 10) & 31], -1) return ((ch << 3) | (ch >> 2)).astype(np.uint8) # -- bits --------------------------------------------------------------------------- class BitWriter: def __init__(self) -> None: self.bits: list[int] = [] def u(self, v: int, n: int) -> None: for i in range(n - 1, -1, -1): self.bits.append((v >> i) & 1) def ue(self, v: int) -> None: v += 1 n = v.bit_length() self.u(0, n - 1) self.u(v, n) def se(self, v: int) -> None: self.ue(2 * v - 1 if v > 0 else -2 * v) def bytes(self) -> bytes: b = self.bits + [0] * (-len(self.bits) % 8) return bytes(int("".join(map(str, b[i : i + 8])), 2) for i in range(0, len(b), 8)) class BitReader: def __init__(self, data: bytes) -> None: self.data = data self.pos = 0 def u(self, n: int) -> int: v = 0 for _ in range(n): byte = self.data[self.pos >> 3] v = (v << 1) | ((byte >> (7 - (self.pos & 7))) & 1) self.pos += 1 return v def ue(self, ) -> int: z = 0 while self.u(1) == 0: z += 1 return (1 << z) - 1 + self.u(z) def se(self) -> int: k = self.ue() return (k + 1) // 2 if k & 1 else -(k // 2) def ue_len(v: int) -> int: return 2 * (v + 1).bit_length() - 1 def se_len(v: int) -> int: return ue_len(2 * v - 1 if v > 0 else -2 * v) # -- the stream --------------------------------------------------------------------- @dataclass class Planes: y: np.ndarray # (ROWS, W) uint8 cb: np.ndarray # (ROWS/2, W/2) uint8 cr: np.ndarray @staticmethod def blank() -> "Planes": return Planes(np.full((ROWS, W), 16, np.uint8), np.full((ROWS // 2, W // 2), 128, np.uint8), np.full((ROWS // 2, W // 2), 128, np.uint8)) def copy(self) -> "Planes": return Planes(self.y.copy(), self.cb.copy(), self.cr.copy()) HALF = NMB // 2 def set_width(w: int) -> None: """Experiments only (option 3, a narrower stored picture): the stored width, a multiple of 16. The player is built for 320; a narrower stream is a study.""" global W, MBX, NMB, HALF assert w % 16 == 0 and 16 <= w <= 320 W, MBX = w, w // 16 NMB = MBX * MBY HALF = NMB // 2 def stream_header(frames: int) -> bytes: return b"C1V3" + struct.pack(">HHI", W, ROWS, frames) def split_stream(data: bytes) -> list[bytes]: assert data[:4] == b"C1V3" w, rows, n = struct.unpack(">HHI", data[4:12]) assert (w, rows) == (W, ROWS) out, p = [], 12 for _ in range(n): (ln,) = struct.unpack(">H", data[p : p + 2]) out.append(data[p + 2 : p + 2 + ln]) p += 2 + ln return out def _clamped(plane: np.ndarray, y0: int, x0: int, n: int) -> np.ndarray: h, w = plane.shape ys = np.clip(np.arange(y0, y0 + n), 0, h - 1) xs = np.clip(np.arange(x0, x0 + n), 0, w - 1) return plane[np.ix_(ys, xs)] def _pairs(r: BitReader, start: int) -> np.ndarray: zz = np.zeros(64, np.int64) pos = start while True: pos += r.ue() k = r.ue() mag = (k >> 1) + 1 zz[pos] = -mag if k & 1 else mag pos += 1 if r.u(1): break blk = np.zeros(64, np.int64) blk[ZIGZAG] = zz return blk.reshape(8, 8) def decode_frame(payload: bytes, ref: Planes) -> tuple[Planes, list[int]]: """One payload against the reference -> (new planes, per-MB modes).""" q, h2, split = struct.unpack(">HHB", payload[:5]) assert 1 <= split < NMB cur = ref.copy() modes = [SKIP] * NMB _decode_half(BitReader(payload[5:h2]), q, 0, split, ref, cur, modes) _decode_half(BitReader(payload[h2:]), q, split, NMB, ref, cur, modes) return cur, modes def _decode_half(r: "BitReader", q: int, pos: int, end: int, ref: Planes, cur: Planes, modes: list[int]) -> None: si = intra_steps(q) py = px = 0 row = -1 while pos < end: pos += r.ue() if pos >= end: break if r.u(1): mode = INTER elif r.u(1): mode = INTER0 else: mode = INTRA my, mx = divmod(pos, MBX) if my != row: row, py, px = my, 0, 0 modes[pos] = mode ys, xs = my * 16, mx * 16 if mode in (INTER0, INTER): dy = py + r.se() dx = px + r.se() py, px = dy, dx pred = [_clamped(ref.y, ys + dy, xs + dx, 16).astype(np.int64), _clamped(ref.cb, my * 8 + (dy >> 1), mx * 8 + (dx >> 1), 8).astype(np.int64), _clamped(ref.cr, my * 8 + (dy >> 1), mx * 8 + (dx >> 1), 8).astype(np.int64)] if mode == INTER: cbp = r.u(6) for b in range(6): if cbp & (32 >> b): res = idct_int(_pairs(r, 0) * q) if b < 4: oy, ox = (b >> 1) * 8, (b & 1) * 8 pred[0][oy : oy + 8, ox : ox + 8] += res else: pred[b - 3] += res cur.y[ys : ys + 16, xs : xs + 16] = np.clip(pred[0], 0, 255) cur.cb[my * 8 : my * 8 + 8, mx * 8 : mx * 8 + 8] = np.clip(pred[1], 0, 255) cur.cr[my * 8 : my * 8 + 8, mx * 8 : mx * 8 + 8] = np.clip(pred[2], 0, 255) else: prev_dc = 0 for b in range(6): d = r.se() dc = prev_dc + d if b in (1, 2, 3) else d if b < 4: prev_dc = dc coef = _pairs(r, 1) * si if r.u(1) else np.zeros((8, 8), np.int64) coef[0, 0] = dc * 8 pix = np.clip(128 + idct_int(coef), 0, 255) if b < 4: oy, ox = (b >> 1) * 8, (b & 1) * 8 cur.y[ys + oy : ys + oy + 8, xs + ox : xs + ox + 8] = pix elif b == 4: cur.cb[my * 8 : my * 8 + 8, mx * 8 : mx * 8 + 8] = pix else: cur.cr[my * 8 : my * 8 + 8, mx * 8 : mx * 8 + 8] = pix pos += 1