Skip to content

Video to GIF Converter — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * video-to-gif — pure GIF89a encoder: quantize RGBA frames to one shared
 * palette (median cut), nearest-color map, GIF-variant LZW, assemble bytes.
 *
 * Language: PHP 7.4+ (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. usort() is not
 * stable before PHP 8.0, so sorts carry the original position as a tiebreaker
 * — that reproduces the TS lib's stable Array#sort byte for byte. TS
 * Math.round (half up) is mirrored as (int)($x + 0.5). Frames arrive as RGBA
 * byte strings (PHP strings are byte buffers), 4 bytes/pixel.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** Per-channel spread of a pixel bucket (median-cut helper). */
function gif_bounds(array $bucket): array
{
    $lo = [255, 255, 255];
    $hi = [0, 0, 0];
    foreach ($bucket as $p) {
        for ($c = 0; $c < 3; $c++) {
            $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]];
}

/**
 * Median-cut quantization: split the widest-range bucket at the median of its
 * widest channel until $maxColors (skips fully transparent pixels). Returns
 * [r, g, b, population] swatches, populous colors first (low palette indices).
 */
function extract_palette(string $rgba, int $maxColors = 8): array
{
    $total = intdiv(strlen($rgba), 4);
    $stride = max(1, intdiv($total, 16384)); // bounded samples
    $pixels = [];
    for ($i = 0; $i < $total; $i += $stride) {
        $o = $i * 4;
        if (ord($rgba[$o + 3]) > 0) { // skip fully transparent
            $pixels[] = [ord($rgba[$o]), ord($rgba[$o + 1]), ord($rgba[$o + 2]), $i];
        }
    }
    if (!$pixels) {
        return [];
    }

    $buckets = [$pixels];
    while (count($buckets) < $maxColors) {
        $spreads = array_map('gif_bounds', $buckets);
        $bestIdx = -1;
        $bestRange = 1; // range 1 (duplicates only) never splits
        foreach ($spreads as $i => $s) {
            $range = max($s);
            if ($range > $bestRange) {
                $bestRange = $range;
                $bestIdx = $i;
            }
        }
        if ($bestIdx === -1) {
            break; // every bucket is uniform — done
        }
        $spread = $spreads[$bestIdx];
        $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[$bestIdx];
        unset($buckets[$bestIdx]); // splice keeps the rest in order
        $buckets = array_values($buckets);
        // usort is unstable before PHP 8.0 — index tiebreak restores stability.
        usort($bucket, fn(array $x, array $y): int => ($x[$channel] <=> $y[$channel]) ?: ($x[3] <=> $y[3]));
        $mid = intdiv(count($bucket), 2);
        $buckets[] = array_slice($bucket, 0, $mid);
        $buckets[] = array_slice($bucket, $mid);
    }

    $swatches = [];
    $order = 0;
    foreach ($buckets as $b) {
        if (!$b) {
            continue;
        }
        $n = count($b);
        $sw = [0, 0, 0];
        for ($c = 0; $c < 3; $c++) {
            $sum = 0;
            foreach ($b as $p) {
                $sum += $p[$c];
            }
            $sw[$c] = (int) ($sum / $n + 0.5); // Math.round: half up
        }
        $swatches[] = [$sw[0], $sw[1], $sw[2], $n, $order++]; // $order: tiebreak
    }
    // Populous colors get low indices; position tiebreak keeps TS-sort parity.
    usort($swatches, fn(array $x, array $y): int => ($y[3] <=> $x[3]) ?: ($x[4] <=> $y[4]));
    return array_map(fn(array $s): array => [$s[0], $s[1], $s[2], $s[3]], $swatches);
}

/** Map RGBA to palette indices: exact-match cache, else nearest RGB distance. */
function map_to_palette(string $rgba, array $palette): string
{
    $cache = [];
    $indices = '';
    $total = intdiv(strlen($rgba), 4);
    for ($i = 0; $i < $total; $i++) {
        $o = $i * 4;
        $key = (ord($rgba[$o]) << 16) | (ord($rgba[$o + 1]) << 8) | ord($rgba[$o + 2]);
        if (!isset($cache[$key])) {
            $best = 0;
            $bestDist = null;
            foreach ($palette as $p => $sw) {
                $dr = ord($rgba[$o]) - $sw[0];
                $dg = ord($rgba[$o + 1]) - $sw[1];
                $db = ord($rgba[$o + 2]) - $sw[2];
                $dist = $dr * $dr + $dg * $dg + $db * $db;
                if ($bestDist === null || $dist < $bestDist) {
                    $bestDist = $dist;
                    $best = $p;
                }
            }
            $cache[$key] = $best;
        }
        $indices .= chr($cache[$key]);
    }
    return $indices;
}

/** GIF-variant LZW: codes packed LSB-first; the caller sub-blocks every 255. */
function lzw_encode(int $minCodeSize, string $indices): array
{
    $clearCode = 1 << $minCodeSize;
    $eoiCode = $clearCode + 1;
    $codeSize = $minCodeSize + 1;
    $nextCode = $eoiCode + 1;
    $table = []; // (prefix code, byte) -> code

    $out = [];
    $bitBuffer = 0;
    $bitCount = 0;
    $emit = function (int $code) use (&$out, &$bitBuffer, &$bitCount, &$codeSize): void {
        $bitBuffer |= $code << $bitCount;
        $bitCount += $codeSize;
        while ($bitCount >= 8) {
            $out[] = $bitBuffer & 0xff;
            $bitBuffer >>= 8;
            $bitCount -= 8;
        }
    };

    $emit($clearCode);
    if ($indices === '') {
        $emit($eoiCode);
        if ($bitCount > 0) {
            $out[] = $bitBuffer & 0xff;
        }
        return $out;
    }

    $w = ord($indices[0]);
    $len = strlen($indices);
    for ($i = 1; $i < $len; $i++) {
        $c = ord($indices[$i]);
        $key = ($w << 8) | $c;
        if (isset($table[$key])) {
            $w = $table[$key];
            continue;
        }
        $emit($w);
        $table[$key] = $nextCode++;
        // Encoder width lags one entry behind the decoder: grow after 2^size.
        if ($nextCode - 1 === (1 << $codeSize) && $codeSize < 12) {
            $codeSize++;
        }
        $w = $c;
        if ($nextCode >= 4096) { // dictionary full — reset like encoders do
            $emit($clearCode);
            $table = [];
            $nextCode = $eoiCode + 1;
            $codeSize = $minCodeSize + 1;
            $w = $c;
        }
    }
    $emit($w);
    $emit($eoiCode);
    if ($bitCount > 0) {
        $out[] = $bitBuffer & 0xff;
    }
    return $out;
}

/**
 * Encode frames into a GIF89a byte string; empty input -> "".
 * Each frame: ['width' => int, 'height' => int, 'rgba' => string, 'delay_ms' => int].
 * One shared palette, one image block per frame, NETSCAPE loop-forever.
 */
function encode_gif(array $frames, int $maxColors = 128): string
{
    if (!$frames) {
        return '';
    }

    // One shared palette, quantized from a down-sampled mix of all frames.
    $mixed = '';
    foreach ($frames as $f) {
        $total = intdiv(strlen($f['rgba']), 4);
        $stride = max(1, intdiv($total, 4096));
        for ($i = 0; $i < $total; $i += $stride) {
            $o = $i * 4;
            $mixed .= substr($f['rgba'], $o, 4);
        }
    }
    $palette = extract_palette($mixed, min($maxColors, 256));
    if (!$palette) {
        return '';
    }

    // Color table padded to a power of two (min 2 entries).
    $tableBits = 1;
    while ((1 << $tableBits) < count($palette)) {
        $tableBits++;
    }

    $u16le = fn(int $n): string => chr($n & 0xff) . chr(($n >> 8) & 0xff);

    $out = 'GIF89a' . $u16le($frames[0]['width']) . $u16le($frames[0]['height']);
    $out .= chr(0x80 | ($tableBits - 1)) . "\x00\x00"; // GCT flag + size; bg; aspect
    $table = str_repeat("\x00", 3 * (1 << $tableBits)); // zero-filled, patched below
    foreach ($palette as $i => $sw) {
        $table[$i * 3] = chr($sw[0]);
        $table[$i * 3 + 1] = chr($sw[1]);
        $table[$i * 3 + 2] = chr($sw[2]);
    }
    $out .= $table;
    $out .= "\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00"; // NETSCAPE loop forever

    $minCodeSize = max(2, $tableBits); // GIF spec floor: 2
    foreach ($frames as $f) {
        $cs = max(0, min(0xffff, (int) ($f['delay_ms'] / 10 + 0.5))); // centiseconds
        $out .= "\x21\xf9\x04\x00" . $u16le($cs) . "\x00\x00"; // graphic control ext
        $out .= "\x2c" . $u16le(0) . $u16le(0) . $u16le($f['width']) . $u16le($f['height']);
        $out .= "\x00"; // no local color table, no interlace
        $data = lzw_encode($minCodeSize, map_to_palette($f['rgba'], $palette));
        $out .= chr($minCodeSize);
        foreach (array_chunk($data, 255) as $chunk) { // sub-blocked every 255 bytes
            $out .= chr(count($chunk)) . implode('', array_map('chr', $chunk));
        }
        $out .= "\x00"; // block terminator
    }
    return $out . "\x3b"; // trailer
}

// Usage: encode_gif([['width' => 4, 'height' => 4, 'rgba' => $bytes, 'delay_ms' => 100]]) -> 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 →