Skip to content

Video to GIF Converter — Python source

Convert a video clip to an animated GIF — frame capture, palette quantization and GIF encoding all run locally with our own encoder. Nothing uploads.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""video-to-gif — pure GIF89a encoder: quantize RGBA frames to one shared
palette (median cut), nearest-color map, GIF-variant LZW, assemble bytes.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `video-to-gif` tool, ported from
src/lib/gif-encode.ts.

GIF allows a single 256-color table per animation, so every frame shares one
palette, quantized from a down-sampled mix of ALL frames. TS ``Math.round``
(half up) is mirrored as ``int(x + 0.5)`` — Python's built-in ``round()`` uses
banker's rounding and would drift on .5 averages. No video decode: frames
arrive as RGBA bytes (4 bytes/pixel, top-left origin).

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

from typing import List, NamedTuple, Sequence, Tuple

Pixel = Tuple[int, int, int]
Swatch = Tuple[int, int, int, int]  # (r, g, b, population)


class GifFrame(NamedTuple):
    """One input frame; delay_ms is stored in the stream as centiseconds."""

    width: int
    height: int
    rgba: bytes  # RGBA, 4 bytes per pixel, top-left origin
    delay_ms: int


def extract_palette(rgba: Sequence[int], max_colors: int = 8) -> List[Swatch]:
    """Median-cut quantization: split the widest-range bucket until max_colors.

    Skips fully transparent pixels; returns swatches sorted by descending
    population, so populous colors get the low palette indices.
    """
    total = len(rgba) // 4
    stride = max(1, total // 16384)  # bounded samples
    pixels: List[Pixel] = [
        (rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2])
        for i in range(0, total, stride)
        if rgba[i * 4 + 3] > 0
    ]
    if not pixels:
        return []

    def bounds(bucket: List[Pixel]) -> Tuple[int, int, int]:
        lo, hi = [255, 255, 255], [0, 0, 0]
        for p in bucket:
            for c in range(3):
                lo[c] = min(lo[c], p[c])
                hi[c] = max(hi[c], p[c])
        return hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]

    buckets: List[List[Pixel]] = [pixels]
    while len(buckets) < max_colors:
        spreads = [bounds(b) for b in buckets]
        best_idx, best_range = -1, 1  # range 1 (duplicates only) never splits
        for i, s in enumerate(spreads):
            if max(s) > best_range:
                best_range, best_idx = max(s), i
        if best_idx == -1:
            break  # every bucket is uniform — done
        spread = spreads[best_idx]
        channel = 0  # widest channel; ties toward r then g (TS reduce order)
        if spread[1] > spread[channel]:
            channel = 1
        if spread[2] > spread[channel]:
            channel = 2
        bucket = buckets.pop(best_idx)  # pop keeps the rest in order
        bucket.sort(key=lambda p, c=channel: p[c])  # sort is stable
        mid = len(bucket) // 2
        buckets += [bucket[:mid], bucket[mid:]]

    swatches = [  # average each surviving bucket (Math.round: half up)
        tuple(int(sum(p[c] for p in b) / len(b) + 0.5) for c in range(3)) + (len(b),)
        for b in buckets
        if b
    ]
    return sorted(swatches, key=lambda s: -s[3])  # stable, descending population


def map_to_palette(rgba: Sequence[int], palette: Sequence[Swatch]) -> List[int]:
    """Map RGBA to palette indices: exact-match cache, else nearest RGB distance."""
    cache = {}
    indices: List[int] = []
    for i in range(len(rgba) // 4):
        o = i * 4
        key = (rgba[o] << 16) | (rgba[o + 1] << 8) | rgba[o + 2]
        idx = cache.get(key)
        if idx is None:
            best, best_dist = 0, None
            for p, sw in enumerate(palette):
                dr, dg, db = rgba[o] - sw[0], rgba[o + 1] - sw[1], rgba[o + 2] - sw[2]
                dist = dr * dr + dg * dg + db * db
                if best_dist is None or dist < best_dist:
                    best_dist, best = dist, p
            idx = cache[key] = best
        indices.append(idx)
    return indices


def lzw_encode(min_code_size: int, indices: Sequence[int]) -> List[int]:
    """GIF-variant LZW: codes packed LSB-first; the caller sub-blocks every 255."""
    clear_code, eoi_code = 1 << min_code_size, (1 << min_code_size) + 1
    code_size, next_code = min_code_size + 1, eoi_code + 1
    table = {}  # (prefix code, byte) -> code
    out: List[int] = []
    bit = [0, 0]  # bit buffer, bit count

    def emit(code: int) -> None:
        bit[0] |= code << bit[1]
        bit[1] += code_size
        while bit[1] >= 8:
            out.append(bit[0] & 0xFF)
            bit[0] >>= 8
            bit[1] -= 8

    emit(clear_code)
    if not indices:
        emit(eoi_code)
        if bit[1]:
            out.append(bit[0] & 0xFF)
        return out

    w = indices[0]
    for c in indices[1:]:
        key = (w << 8) | c
        found = table.get(key)
        if found is not None:
            w = found
            continue
        emit(w)
        table[key] = next_code
        next_code += 1
        # Encoder width lags one entry behind the decoder: grow after 2^size.
        if next_code - 1 == (1 << code_size) and code_size < 12:
            code_size += 1
        w = c
        if next_code >= 4096:  # dictionary full — reset like encoders do
            emit(clear_code)
            table.clear()
            next_code, code_size = eoi_code + 1, min_code_size + 1
            w = c
    emit(w)
    emit(eoi_code)
    if bit[1]:
        out.append(bit[0] & 0xFF)
    return out


def _u16le(n: int) -> bytes:
    return bytes((n & 0xFF, (n >> 8) & 0xFF))


def encode_gif(frames: Sequence[GifFrame], max_colors: int = 128) -> bytes:
    """Encode frames into a GIF89a byte stream; empty input -> b"".

    One shared palette, one image block per frame, NETSCAPE loop-forever,
    no transparency.
    """
    if not frames:
        return b""

    # One shared palette, quantized from a down-sampled mix of all frames.
    mixed = bytearray()
    for f in frames:
        total = len(f.rgba) // 4
        stride = max(1, total // 4096)
        for i in range(0, total, stride):
            o = i * 4
            mixed += f.rgba[o : o + 4]
    palette = extract_palette(mixed, min(max_colors, 256))
    if not palette:
        return b""

    # Color table padded to a power of two (min 2 entries).
    table_bits = 1
    while (1 << table_bits) < len(palette):
        table_bits += 1

    out = bytearray(b"GIF89a")
    out += _u16le(frames[0].width) + _u16le(frames[0].height)
    out.append(0x80 | (table_bits - 1))  # GCT flag + size; bg; aspect
    table_start = len(out)
    out += bytes(3 * (1 << table_bits))  # zero-filled table, patched below
    for i, sw in enumerate(palette):
        o = table_start + i * 3
        out[o : o + 3] = bytes(sw[:3])
    out += b"\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00"  # loop forever

    min_code_size = max(2, table_bits)  # GIF spec floor: 2
    for f in frames:
        cs = max(0, min(0xFFFF, int(f.delay_ms / 10 + 0.5)))  # centiseconds
        out += b"\x21\xf9\x04\x00" + _u16le(cs) + b"\x00\x00"  # graphic control
        out.append(0x2C)  # image descriptor
        out += _u16le(0) + _u16le(0) + _u16le(f.width) + _u16le(f.height)
        out.append(0x00)  # no local color table, no interlace
        data = lzw_encode(min_code_size, map_to_palette(f.rgba, palette))
        out.append(min_code_size)
        for i in range(0, len(data), 255):  # sub-blocked every 255 bytes
            chunk = data[i : i + 255]
            out += bytes((len(chunk),)) + bytes(chunk)
        out.append(0x00)  # block terminator
    out.append(0x3B)  # trailer
    return bytes(out)


# Usage: encode_gif([GifFrame(4, 4, rgba_bytes, 100)], max_colors=128) -> GIF89a bytes.

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →