# SPDX-License-Identifier: MIT """The television: lines and VSYNC in, frames out. Nothing on the board depends on it. The TIA has no vertical counter (docs/start-here.md "The machines"): a frame is whatever the program puts between its VSYNC pulses. This stage collects the TIA's lines and starts a new frame when VSYNC ends, as a television's vertical sync does, with a bound on runaway frames for programs that stop sending it. A frame is a list of lines, each 160 bytes (the colour clocks after the 68-clock horizontal blank, ``TIA.pixels`` encoding: colour with D0 set, or 0 for blank). :func:`frame_rgb` and :func:`frame_png` turn them into colours through a palette (palettes.py, each labelled with its origin). """ from __future__ import annotations import struct import zlib from .palettes import PALETTES, Palette HBLANK_CLOCKS = 68 # DOC: SPG, 68 colour clocks of horizontal blank # A frame longer than this is cut (no VSYNC). HYPOTHESIS: a television's # vertical oscillator free-runs somewhere past 312 lines; the value only # bounds a runaway program's frame here and changes no emulated state. MAX_LINES = 400 class Television: def __init__(self, tia) -> None: self.frames_seen = 0 self.frame: list[bytes] | None = None # the last complete frame self._lines: list[bytes] = [] self._vsync = False self._tia = tia tia.on_line = self._line def _line(self, pixels: bytearray) -> None: vsync = self._tia.vsync if (self._vsync and not vsync) or len(self._lines) >= MAX_LINES: self.frame = self._lines self.frames_seen += 1 self._lines = [] self._vsync = vsync self._lines.append(bytes(pixels[HBLANK_CLOCKS:])) def frame_rgb(frame: list[bytes], palette: Palette, scale_x: int = 1) -> list[bytes]: """``frame`` as rows of RGB bytes: blank as black, each colour clock ``scale_x`` wide.""" table = [bytes(palette.rgb(v)) * scale_x if v & 1 else b"\0\0\0" * scale_x for v in range(256)] return [b"".join(table[v] for v in line) for line in frame] def frame_png(frame: list[bytes], scale_x: int = 2, palette: Palette | None = None) -> bytes: """A PNG of ``frame`` in ``palette`` (default NTSC, palettes.py).""" rows = [b"\0" + row for row in frame_rgb(frame, palette or PALETTES["ntsc"], scale_x)] width, height = len(frame[0]) * scale_x if frame else 0, len(frame) def chunk(kind: bytes, data: bytes) -> bytes: return ( struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) ) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(b"".join(rows))) + chunk(b"IEND", b"") )