"""Frames to pictures. Comparisons are by colour index (docs/vdp.md); RGB is a display choice made here, derived from TI's table 2-3 levels for the 9928A, not a measurement.""" from __future__ import annotations import struct import zlib from pathlib import Path from tms9918_python import LEVELS_9928A def _palette(gain: float = 1.4) -> tuple[tuple[int, int, int], ...]: """Y, R-Y, B-Y (0.47 = no colour difference) to RGB with Rec. 601 weights. ``gain`` is how far the colour-difference swing reaches; chosen by eye, not measured.""" colours = [] for level in LEVELS_9928A: if level is None: # transparent: shown as black when it reaches the screen colours.append((0, 0, 0)) continue y, r_y, b_y = level r = y + gain * (r_y - 0.47) b = y + gain * (b_y - 0.47) g = (y - 0.299 * r - 0.114 * b) / 0.587 colours.append(tuple(max(0, min(255, round(c * 255))) for c in (r, g, b))) return tuple(colours) PALETTE = _palette() def frame_rgb(pixels: tuple[bytes, ...]) -> bytes: lut = [bytes(c) for c in PALETTE] return b"".join(b"".join(lut[i] for i in row) for row in pixels) def write_png(path: str | Path, pixels: tuple[bytes, ...]) -> None: """A 256 x 192 RGB PNG of a frame's colour indices.""" height, width = len(pixels), len(pixels[0]) lut = [bytes(c) for c in PALETTE] raw = b"".join(b"\x00" + b"".join(lut[i] for i in row) for row in pixels) def chunk(kind: bytes, data: bytes) -> bytes: body = kind + data return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw, 9)) Path(path).write_bytes(png + chunk(b"IEND", b""))