Skip to content

Video to GIF Converter — JavaScript 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 JavaScript 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: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * 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. No video decode —
 * frames arrive as RGBA byte arrays (4 bytes/pixel, top-left origin).
 * Deterministic by construction: bounded samples, stable sorts, no randomness.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/**
 * 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).
 */
export function extractPalette(rgba, maxColors = 8) {
  const total = rgba.length >> 2;
  const stride = Math.max(1, Math.floor(total / 16384)); // bounded samples
  const pixels = [];
  for (let i = 0; i < total; i += stride) {
    const o = i * 4;
    if (rgba[o + 3] > 0) pixels.push([rgba[o], rgba[o + 1], rgba[o + 2]]);
  }
  if (pixels.length === 0) return [];

  // Per-channel spread of a bucket.
  const bounds = (bucket) => {
    const lo = [255, 255, 255], hi = [0, 0, 0];
    for (const p of bucket)
      for (let c = 0; c < 3; c++) {
        if (p[c] < lo[c]) lo[c] = p[c];
        if (p[c] > hi[c]) hi[c] = p[c];
      }
    return [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]];
  };

  let buckets = [pixels];
  while (buckets.length < maxColors) {
    const spreads = buckets.map(bounds);
    let bestIdx = -1, bestRange = 1; // range 1 (duplicates only) never splits
    spreads.forEach((s, i) => {
      const range = Math.max(s[0], s[1], s[2]);
      if (range > bestRange) { bestRange = range; bestIdx = i; }
    });
    if (bestIdx === -1) break; // every bucket is uniform — done
    const spread = spreads[bestIdx];
    let 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;
    const bucket = buckets.splice(bestIdx, 1)[0]; // splice keeps the rest in order
    const sorted = [...bucket].sort((x, y) => x[channel] - y[channel]); // stable
    const mid = sorted.length >> 1;
    buckets.push(sorted.slice(0, mid), sorted.slice(mid));
  }

  return buckets
    .filter((b) => b.length > 0)
    .map((b) => ([
      Math.round(b.reduce((s, p) => s + p[0], 0) / b.length), // Math.round: half up
      Math.round(b.reduce((s, p) => s + p[1], 0) / b.length),
      Math.round(b.reduce((s, p) => s + p[2], 0) / b.length),
      b.length,
    ]))
    .sort((a, b) => b[3] - a[3]);
}

/** Map RGBA to palette indices: exact-match cache, else nearest RGB distance. */
export function mapToPalette(rgba, palette) {
  const cache = new Map();
  const indices = new Uint8Array(rgba.length >> 2);
  for (let i = 0; i < indices.length; i++) {
    const o = i * 4;
    const key = (rgba[o] << 16) | (rgba[o + 1] << 8) | rgba[o + 2];
    let idx = cache.get(key);
    if (idx === undefined) {
      let best = 0, bestDist = Infinity;
      for (let p = 0; p < palette.length; p++) {
        const dr = rgba[o] - palette[p][0], dg = rgba[o + 1] - palette[p][1], db = rgba[o + 2] - palette[p][2];
        const dist = dr * dr + dg * dg + db * db;
        if (dist < bestDist) { bestDist = dist; best = p; }
      }
      cache.set(key, (idx = best));
    }
    indices[i] = idx;
  }
  return indices;
}

/** GIF-variant LZW: codes packed LSB-first; the caller sub-blocks every 255. */
export function lzwEncode(minCodeSize, indices) {
  const clearCode = 1 << minCodeSize, eoiCode = clearCode + 1;
  let codeSize = minCodeSize + 1, nextCode = eoiCode + 1;
  const table = new Map(); // (prefix code, byte) -> code
  const out = [];
  let bitBuffer = 0, bitCount = 0;
  const emit = (code) => {
    bitBuffer |= code << bitCount;
    bitCount += codeSize;
    while (bitCount >= 8) { out.push(bitBuffer & 0xff); bitBuffer >>= 8; bitCount -= 8; }
  };

  emit(clearCode);
  if (indices.length === 0) { emit(eoiCode); if (bitCount > 0) out.push(bitBuffer & 0xff); return out; }

  let w = indices[0];
  for (let i = 1; i < indices.length; i++) {
    const c = indices[i];
    const key = (w << 8) | c;
    const found = table.get(key);
    if (found !== undefined) { w = found; continue; }
    emit(w);
    table.set(key, nextCode++);
    // Encoder width lags one entry behind the decoder: grow after 2^codeSize.
    if (nextCode - 1 === (1 << codeSize) && codeSize < 12) codeSize++;
    w = c;
    if (nextCode >= 4096) { // dictionary full — reset like encoders do
      emit(clearCode);
      table.clear();
      nextCode = eoiCode + 1;
      codeSize = minCodeSize + 1;
      w = c;
    }
  }
  emit(w);
  emit(eoiCode);
  if (bitCount > 0) out.push(bitBuffer & 0xff);
  return out;
}

const u16le = (n) => [n & 0xff, (n >> 8) & 0xff];

/**
 * Encode frames into a GIF89a byte stream (Uint8Array); empty input -> empty.
 * Each frame: { width, height, rgba: Uint8Array, delayMs }. One shared palette,
 * one image block per frame, NETSCAPE loop-forever, no transparency.
 */
export function encodeGif(frames, opts = {}) {
  if (frames.length === 0) return new Uint8Array(0);

  // One shared palette, quantized from a down-sampled mix of all frames.
  const mixed = frames.flatMap((f) => {
    const total = f.rgba.length >> 2;
    const stride = Math.max(1, Math.floor(total / 4096));
    const px = [];
    for (let i = 0; i < total; i += stride)
      px.push(f.rgba[i * 4], f.rgba[i * 4 + 1], f.rgba[i * 4 + 2], f.rgba[i * 4 + 3]);
    return px;
  });
  const palette = extractPalette(Uint8Array.from(mixed), Math.min(opts.maxColors ?? 128, 256));
  if (palette.length === 0) return new Uint8Array(0);

  // Color table padded to a power of two (min 2 entries).
  let tableBits = 1;
  while ((1 << tableBits) < palette.length) tableBits++;

  const out = [];
  for (const ch of 'GIF89a') out.push(ch.charCodeAt(0));
  out.push(...u16le(frames[0].width), ...u16le(frames[0].height));
  out.push(0x80 | (tableBits - 1), 0, 0); // GCT flag + size; bg; aspect
  for (let i = 0; i < (1 << tableBits); i++) {
    const sw = palette[i];
    out.push(sw ? sw[0] : 0, sw ? sw[1] : 0, sw ? sw[2] : 0);
  }
  out.push(0x21, 0xff, 0x0b); // NETSCAPE loop-forever extension
  for (const ch of 'NETSCAPE2.0') out.push(ch.charCodeAt(0));
  out.push(0x03, 0x01, 0x00, 0x00, 0x00);

  const minCodeSize = Math.max(2, tableBits); // GIF spec floor: 2
  for (const frame of frames) {
    const cs = Math.max(0, Math.min(0xffff, Math.round(frame.delayMs / 10))); // centiseconds
    out.push(0x21, 0xf9, 0x04, 0x00, ...u16le(cs), 0x00, 0x00); // graphic control ext
    out.push(0x2c, ...u16le(0), ...u16le(0), ...u16le(frame.width), ...u16le(frame.height));
    out.push(0x00); // no local color table, no interlace
    const data = lzwEncode(minCodeSize, mapToPalette(frame.rgba, palette));
    out.push(minCodeSize);
    for (let i = 0; i < data.length; i += 255) {
      const chunk = data.slice(i, i + 255); // sub-blocked every 255 bytes
      out.push(chunk.length, ...chunk);
    }
    out.push(0x00); // block terminator
  }
  out.push(0x3b); // trailer
  return Uint8Array.from(out);
}

// Usage: encodeGif([{ width, height, rgba: Uint8Array, delayMs }], { maxColors: 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 →