Skip to content

GIF Frame Extractor — Rust source

Split an animated GIF into PNG frames with per-frame delays — decoded by our own pure GIF parser, entirely in your browser. Nothing uploads.

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

//! gif-frame-extractor — decode a GIF byte stream into indexed frames.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `gif-frame-extractor` tool, ported
//! from src/lib/gif-decode.ts.
//!
//! Why this file exists: a from-scratch GIF87a/89a parser with zero
//! dependencies — signature + logical screen descriptor (canvas size, global
//! color table), extension blocks (frame delay, transparency, NETSCAPE loop
//! count), and LZW image data decompressed to palette indices. Deterministic
//! and panic-free on untrusted bytes: malformed input yields `None` (the TS
//! port's null), never an index panic; absent NETSCAPE loop count is `None`
//! where the TS port uses Infinity.

/// One decoded frame: placement, optional local palette (RGB triplets,
/// None = use global), pixel indices in natural row order, timing.
#[derive(Debug)]
pub struct GifFrame {
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
    pub palette: Option<Vec<u8>>,
    pub indices: Vec<u8>,
    /// Frame delay in milliseconds.
    pub delay_ms: u32,
    /// Transparent palette index, or -1.
    pub transparent_index: i32,
    /// Disposal method 0-7 (0/1 = keep, 2 = restore bg, 3 = restore previous).
    pub disposal: u8,
}

/// Whole-GIF parse result: logical screen size, frames, global palette and
/// NETSCAPE loop count (0 = loop forever, None when absent).
#[derive(Debug)]
pub struct GifResult {
    pub width: u16,
    pub height: u16,
    pub frames: Vec<GifFrame>,
    pub global_palette: Option<Vec<u8>>,
    pub loop_count: Option<u16>,
}

/// Byte-cursor over the GIF stream: every read is bounds-checked and
/// short-reads surface as `None`, mirroring the TS port's null bail-outs.
struct Cursor<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    fn u8(&mut self) -> Option<u8> {
        let b = *self.data.get(self.pos)?;
        self.pos += 1;
        Some(b)
    }

    fn u16le(&mut self) -> Option<u16> {
        let lo = self.u8()? as u16;
        Some(lo | ((self.u8()? as u16) << 8))
    }

    fn take(&mut self, n: usize) -> Option<&'a [u8]> {
        let slice = self.data.get(self.pos..self.pos.checked_add(n)?)?;
        self.pos += n;
        Some(slice)
    }

    /// Concatenate a sub-block chain; None on truncation.
    fn sub_blocks(&mut self) -> Option<Vec<u8>> {
        let mut out = Vec::new();
        loop {
            let size = self.u8()? as usize;
            if size == 0 {
                return Some(out); // Terminator ends the chain.
            }
            out.extend_from_slice(self.take(size)?);
        }
    }
}

/// Read one LZW code LSB-first; returns the EOI code on truncation, like the
/// TS decoder's readCode.
fn read_code(bit_pos: &mut usize, code_size: u8, data: &[u8], eoi_code: u16) -> u16 {
    if (*bit_pos + code_size as usize) >> 3 > data.len() {
        return eoi_code;
    }
    let mut code = 0u16;
    for i in 0..code_size as usize {
        let byte_idx = (*bit_pos + i) >> 3;
        if byte_idx >= data.len() {
            return eoi_code;
        }
        code |= (((data[byte_idx] >> ((*bit_pos + i) & 7)) & 1) as u16) << i;
    }
    *bit_pos += code_size as usize;
    code
}

/// Emit a code's chain onto `out`, returning the chain's FIRST byte (needed
/// for the KwKwK case).
fn emit(code: usize, prefix: &[i32; 4096], suffix: &[u8; 4096], out: &mut Vec<u8>) -> u8 {
    let mut stack = Vec::new();
    let mut c = code as i32;
    while c >= 0 {
        stack.push(suffix[c as usize]);
        c = prefix[c as usize];
    }
    for &b in stack.iter().rev() {
        out.push(b);
    }
    stack[stack.len() - 1]
}

/// GIF LZW decompression — minCodeSize 2-8, clear-code resets, growing codes
/// (3→12 bits). Dictionary is (prefix, suffix, first-byte) triples reset at
/// every clear code. Truncated or invalid data stops like browsers do.
pub fn lzw_decode(min_code_size: u8, data: &[u8]) -> Vec<u8> {
    let clear_code: u16 = 1 << 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 prefix = [-1i32; 4096];
    let mut suffix = [0u8; 4096];
    let mut first = [0u8; 4096];
    // Dictionary reset (also run at every clear code): literals 0..clear_code.
    for i in 0..clear_code as usize {
        prefix[i] = -1;
        suffix[i] = i as u8;
        first[i] = i as u8;
    }

    let mut out = Vec::new();
    let mut bit_pos = 0usize;
    let mut prev: i32 = -1;
    loop {
        let code = read_code(&mut bit_pos, code_size, data, eoi_code);
        if code == eoi_code {
            break;
        }
        if code == clear_code {
            for i in 0..clear_code as usize {
                prefix[i] = -1;
                suffix[i] = i as u8;
                first[i] = i as u8;
            }
            next_code = eoi_code + 1;
            code_size = min_code_size + 1;
            prev = -1;
            continue;
        }
        if prev == -1 {
            if code >= clear_code {
                break; // First code after clear must be a literal.
            }
            emit(code as usize, &prefix, &suffix, &mut out);
            prev = code as i32;
            continue;
        }
        if code > next_code {
            break; // Invalid — stop like browsers do.
        }
        // KwKwK: code one ahead of the dictionary decodes to prev + first(prev).
        let emitted_first = if code == next_code {
            emit(prev as usize, &prefix, &suffix, &mut out);
            let fb = first[prev as usize];
            out.push(fb);
            fb
        } else {
            emit(code as usize, &prefix, &suffix, &mut out)
        };
        if next_code < 4096 {
            // Table full: TS silently no-ops this write.
            prefix[next_code as usize] = prev;
            suffix[next_code as usize] = emitted_first;
            first[next_code as usize] = first[prev as usize];
            next_code += 1;
            if next_code == 1 << code_size && code_size < 12 {
                code_size += 1;
            }
        }
        prev = code as i32;
    }
    out
}

/// Reorder interlaced rows into natural order. Identity for short frames.
pub fn de_interlace(indices: &[u8], width: u16, height: u16) -> Vec<u8> {
    if height < 4 || width == 0 {
        return indices.to_vec();
    }
    let w = width as usize;
    let mut out = vec![0u8; indices.len()];
    let mut src = 0usize; // Interlaced data is stored pass-by-pass, four passes.
    for (start, step) in [(0usize, 8usize), (4, 8), (2, 4), (1, 2)] {
        let mut row = start;
        while row < height as usize {
            out[row * w..row * w + w].copy_from_slice(&indices[src..src + w]);
            src += w;
            row += step;
        }
    }
    out
}

/// Parse signature, screen descriptor, extensions, and all frames. Returns
/// None on bad magic, truncation, or unknown block type.
pub fn decode_gif(bytes: &[u8]) -> Option<GifResult> {
    if bytes.len() < 13 || (&bytes[..6] != b"GIF87a" && &bytes[..6] != b"GIF89a") {
        return None;
    }
    let mut c = Cursor { data: bytes, pos: 6 };
    let width = c.u16le()?;
    let height = c.u16le()?;
    let packed = c.u8()?;
    c.pos += 2; // Skip bg color + aspect ratio.
    let global_palette = if packed & 0x80 != 0 {
        Some(c.take((2usize << (packed & 7)) * 3)?.to_vec())
    } else {
        None
    };

    let mut frames = Vec::new();
    let mut loop_count = None;
    let (mut delay_ms, mut transparent_index, mut disposal) = (0u32, -1i32, 0u8);
    loop {
        match c.u8()? {
            0x3b => break, // trailer
            0x21 => {
                // Extension: graphic control / NETSCAPE / skip.
                match c.u8()? {
                    0xf9 => {
                        let gce = c.sub_blocks()?;
                        if gce.len() < 4 {
                            return None;
                        }
                        disposal = (gce[0] >> 2) & 7;
                        delay_ms = u32::from(gce[1] as u16 | ((gce[2] as u16) << 8)) * 10;
                        transparent_index = if gce[0] & 1 != 0 { gce[3] as i32 } else { -1 };
                    }
                    0xff => {
                        // Sub-blocks concatenated: 11-byte name, id 1, loop lo/hi.
                        if let Some(app) = c.sub_blocks() {
                            if app.len() >= 14
                                && &app[..11] == b"NETSCAPE2.0"
                                && app[11] == 1
                            {
                                loop_count = Some(app[12] as u16 | ((app[13] as u16) << 8));
                            }
                        }
                    }
                    _ => {
                        c.sub_blocks()?;
                    }
                }
            }
            0x2c => {
                // Image descriptor: rect, local palette, LZW data.
                let (x, y) = (c.u16le()?, c.u16le()?);
                let (w, h) = (c.u16le()?, c.u16le()?);
                let ip = c.u8()?;
                let palette = if ip & 0x80 != 0 {
                    Some(c.take((2usize << (ip & 7)) * 3)?.to_vec())
                } else {
                    None
                };
                let min_code_size = c.u8()?;
                let data = c.sub_blocks()?; // Must be a complete sub-block chain.
                let indices = lzw_decode(min_code_size, &data);
                let indices = if ip & 0x40 != 0 { de_interlace(&indices, w, h) } else { indices };
                frames.push(GifFrame {
                    x, y, width: w, height: h, palette, indices,
                    delay_ms, transparent_index, disposal,
                });
                delay_ms = 0;
                transparent_index = -1;
                disposal = 0;
            }
            _ => return None, // Unknown block type — bail.
        }
    }
    Some(GifResult { width, height, frames, global_palette, loop_count })
}

fn main() {
    // 2×1 GIF89a: 2-color global palette (red, blue), one frame, pixels [0,1].
    let gif: Vec<u8> = {
        let mut v = b"GIF89a".to_vec();
        v.extend_from_slice(&[0x02, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00]); // LSD: 2×1, GCT
        v.extend_from_slice(&[0xff, 0x00, 0x00, 0x00, 0x00, 0xff]); // GCT: red, blue
        v.extend_from_slice(&[0x2c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00]);
        v.extend_from_slice(&[0x02, 0x02, 0x44, 0x0a, 0x00]); // LZW + sub-block + term.
        v.push(0x3b); // trailer
        v
    };
    let res = match decode_gif(&gif) {
        Some(r) => r,
        None => {
            eprintln!("malformed GIF");
            return;
        }
    };
    let loop_s = match res.loop_count {
        Some(n) => n.to_string(),
        None => "∞".to_string(), // TS port: Infinity when NETSCAPE is absent.
    };
    println!("{}x{}, {} frame(s), loop={}", res.width, res.height, res.frames.len(), loop_s);
    for (i, f) in res.frames.iter().enumerate() {
        let idx: Vec<String> = f.indices.iter().map(|b| b.to_string()).collect();
        println!(
            "frame {}: {}x{} at ({},{}), delay {}ms, indices [{}]",
            i, f.width, f.height, f.x, f.y, f.delay_ms, idx.join(", ")
        );
    }
}

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 →