Video to GIF Converter — Rust 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 Rust 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: Rust (std only — no external crates).
//! 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. `sort_by_key`
//! (stable) and `f64::round` (half away from zero — identical to TS
//! `Math.round` for positive values) keep the output byte-identical. No video
//! decode: frames arrive as RGBA bytes (4 bytes/pixel, top-left origin).
//!
//! display source — part of CosmoDev's polyglot tool pages.
use std::collections::HashMap;
/// One input frame; `delay_ms` is stored in the stream as centiseconds.
pub struct GifFrame {
pub width: u16,
pub height: u16,
/// RGBA, 4 bytes per pixel, top-left origin.
pub rgba: Vec<u8>,
pub delay_ms: u32,
}
type Pixel = [u8; 3];
/// (r, g, b, population)
type Swatch = (u8, u8, u8, usize);
/// Median-cut quantization: split the widest-range bucket at the median of
/// its widest channel until `max_colors` (skips fully transparent pixels).
/// Swatches come back sorted by descending population — populous colors get
/// the low palette indices.
pub fn extract_palette(rgba: &[u8], max_colors: usize) -> Vec<Swatch> {
let total = rgba.len() / 4;
let stride = (total / 16384).max(1); // bounded samples
let pixels: Vec<Pixel> = (0..total)
.step_by(stride)
.filter(|&i| rgba[i * 4 + 3] > 0)
.map(|i| [rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]])
.collect();
if pixels.is_empty() {
return Vec::new();
}
// Per-channel spread of a bucket.
let bounds = |bucket: &[Pixel]| -> [i32; 3] {
let mut lo = [255i32; 3];
let mut hi = [0i32; 3];
for p in bucket {
for c in 0..3 {
lo[c] = lo[c].min(p[c] as i32);
hi[c] = hi[c].max(p[c] as i32);
}
}
[hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]
};
let mut buckets: Vec<Vec<Pixel>> = vec![pixels];
while buckets.len() < max_colors {
let spreads: Vec<[i32; 3]> = buckets.iter().map(|b| bounds(b)).collect();
let mut best_idx = usize::MAX;
let mut best_range = 1; // range 1 (duplicates only) never splits
for (i, s) in spreads.iter().enumerate() {
let range = s.iter().copied().max().unwrap();
if range > best_range {
best_range = range;
best_idx = i;
}
}
if best_idx == usize::MAX {
break; // every bucket is uniform — done
}
// Widest channel; ties toward r then g (TS reduce order).
let spread = spreads[best_idx];
let mut channel = 0;
if spread[1] > spread[channel] {
channel = 1;
}
if spread[2] > spread[channel] {
channel = 2;
}
let mut bucket = buckets.remove(best_idx); // remove keeps the rest in order
bucket.sort_by_key(|p| p[channel]); // stable sort, deterministic
let mid = bucket.len() / 2;
let right = bucket.split_off(mid);
buckets.push(bucket);
buckets.push(right);
}
let mut swatches: Vec<Swatch> = buckets
.iter()
.filter(|b| !b.is_empty())
.map(|b| {
let n = b.len();
// Average per channel (Math.round: half up for positive values).
let avg = |c: usize| -> u8 {
let s: f64 = b.iter().map(|p| p[c] as f64).sum();
(s / n as f64).round() as u8
};
(avg(0), avg(1), avg(2), n)
})
.collect();
swatches.sort_by(|a, b| b.3.cmp(&a.3)); // stable, descending population
swatches
}
/// Map RGBA to palette indices: exact-match cache, else nearest RGB distance.
pub fn map_to_palette(rgba: &[u8], palette: &[Swatch]) -> Vec<u8> {
let mut cache: HashMap<u32, u8> = HashMap::new();
let mut indices = Vec::with_capacity(rgba.len() / 4);
for i in 0..rgba.len() / 4 {
let o = i * 4;
let key =
((rgba[o] as u32) << 16) | ((rgba[o + 1] as u32) << 8) | rgba[o + 2] as u32;
let idx = *cache.entry(key).or_insert_with(|| {
let (mut best, mut best_dist) = (0u8, u32::MAX);
for (p, sw) in palette.iter().enumerate() {
let dr = rgba[o] as i32 - sw.0 as i32;
let dg = rgba[o + 1] as i32 - sw.1 as i32;
let db = rgba[o + 2] as i32 - sw.2 as i32;
let dist = (dr * dr + dg * dg + db * db) as u32;
if dist < best_dist {
best_dist = dist;
best = p as u8;
}
}
best
});
indices.push(idx);
}
indices
}
/// Pack one code LSB-first at `code_size` bits into the bit buffer / stream.
fn emit(out: &mut Vec<u8>, buf: &mut u32, count: &mut u32, code: u32, code_size: usize) {
*buf |= code << *count;
*count += code_size as u32;
while *count >= 8 {
out.push((*buf & 0xff) as u8);
*buf >>= 8;
*count -= 8;
}
}
/// GIF-variant LZW: codes packed LSB-first; the caller sub-blocks every 255.
pub fn lzw_encode(min_code_size: usize, indices: &[u8]) -> Vec<u8> {
let clear_code = 1u32 << min_code_size;
let eoi_code = clear_code + 1;
let mut code_size = min_code_size + 1;
let mut next_code = eoi_code + 1;
let mut table: HashMap<u32, u32> = HashMap::new(); // (prefix, byte) -> code
let mut out: Vec<u8> = Vec::new();
let (mut bit_buffer, mut bit_count) = (0u32, 0u32);
emit(&mut out, &mut bit_buffer, &mut bit_count, clear_code, code_size);
if indices.is_empty() {
emit(&mut out, &mut bit_buffer, &mut bit_count, eoi_code, code_size);
if bit_count > 0 {
out.push((bit_buffer & 0xff) as u8);
}
return out;
}
let mut w = indices[0] as u32;
for &byte in &indices[1..] {
let c = byte as u32;
let key = (w << 8) | c;
if let Some(&found) = table.get(&key) {
w = found;
continue;
}
emit(&mut out, &mut bit_buffer, &mut bit_count, w, code_size);
table.insert(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) && code_size < 12 {
code_size += 1;
}
w = c;
if next_code >= 4096 {
// Dictionary full — reset like encoders do.
emit(&mut out, &mut bit_buffer, &mut bit_count, clear_code, code_size);
table.clear();
next_code = eoi_code + 1;
code_size = min_code_size + 1;
w = c;
}
}
emit(&mut out, &mut bit_buffer, &mut bit_count, w, code_size);
emit(&mut out, &mut bit_buffer, &mut bit_count, eoi_code, code_size);
if bit_count > 0 {
out.push((bit_buffer & 0xff) as u8);
}
out
}
fn u16le(n: u32) -> [u8; 2] {
[(n & 0xff) as u8, ((n >> 8) & 0xff) as u8]
}
/// Encode frames into a GIF89a byte stream; empty input -> empty Vec.
/// One shared palette, one image block per frame, NETSCAPE loop-forever.
pub fn encode_gif(frames: &[GifFrame], max_colors: usize) -> Vec<u8> {
if frames.is_empty() {
return Vec::new();
}
// One shared palette, quantized from a down-sampled mix of all frames.
let mut mixed: Vec<u8> = Vec::new();
for f in frames {
let total = f.rgba.len() / 4;
let stride = (total / 4096).max(1);
let mut i = 0;
while i < total {
mixed.extend_from_slice(&f.rgba[i * 4..i * 4 + 4]);
i += stride;
}
}
let palette = extract_palette(&mixed, max_colors.min(256));
if palette.is_empty() {
return Vec::new();
}
// Color table padded to a power of two (min 2 entries).
let mut table_bits = 1usize;
while (1 << table_bits) < palette.len() {
table_bits += 1;
}
let mut out: Vec<u8> = b"GIF89a".to_vec();
out.extend_from_slice(&u16le(frames[0].width as u32));
out.extend_from_slice(&u16le(frames[0].height as u32));
out.push(0x80 | (table_bits as u8 - 1)); // GCT flag + size; bg; aspect
let table_start = out.len();
out.extend_from_slice(&[0, 0]);
out.resize(table_start + 3 * (1 << table_bits), 0); // zero-filled table
for (i, sw) in palette.iter().enumerate() {
let o = table_start + i * 3;
out[o] = sw.0;
out[o + 1] = sw.1;
out[o + 2] = sw.2;
}
out.extend_from_slice(b"\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00"); // loop forever
let min_code_size = table_bits.max(2); // GIF spec floor: 2
for f in frames {
let cs = ((f.delay_ms as f64 / 10.0).round() as i64).clamp(0, 0xffff) as u16;
out.extend_from_slice(&[0x21, 0xf9, 0x04, 0x00]); // graphic control ext
out.extend_from_slice(&u16le(cs as u32));
out.extend_from_slice(&[0, 0]);
out.push(0x2c); // image descriptor
out.extend_from_slice(&u16le(0));
out.extend_from_slice(&u16le(0));
out.extend_from_slice(&u16le(f.width as u32));
out.extend_from_slice(&u16le(f.height as u32));
out.push(0x00); // no local color table, no interlace
let data = lzw_encode(min_code_size, &map_to_palette(&f.rgba, &palette));
out.push(min_code_size as u8);
for chunk in data.chunks(255) {
// sub-blocked every 255 bytes
out.push(chunk.len() as u8);
out.extend_from_slice(chunk);
}
out.push(0x00); // block terminator
}
out.push(0x3b); // trailer
out
}
// Usage: encode_gif(&frames, 128) -> GIF89a bytes; frame = GifFrame { width, height, rgba, delay_ms }.
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 →