From 166bcc831db9c01c07944b7f3093fee6d0373ab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 07:15:13 +0300 Subject: [PATCH] feat(image): GIF decoding and a format-agnostic animation surface A GIF87a/GIF89a decoder written to the spec: LSB-first LZW with the one-code-early width bump and the cScSc case, sub-block chains, the four-pass interlace, graphic control extensions, local and global colour tables, and frame compositing with all four disposal methods. Adds decode_animation(), which every format answers -- a still is one frame with a zero delay -- so a caller that wants to play something never branches on the format. One colour form is chosen for the whole animation, so the pixel layout cannot change under a caller mid-walk. Gated pixel-exact against the incumbent decoder: 6/6 fixtures, and 7/7 real GIFs on this machine over 454 frames, frame count and per-frame delays included. Two 10 000-round mutation sweeps cover the still and the animation path. --- crates/ec-image/Cargo.toml | 2 +- crates/ec-image/src/gif.rs | 571 ++++++++++++++++++++++++++ crates/ec-image/src/lib.rs | 44 +- crates/ec-image/tests/differential.rs | 90 ++++ crates/ec-image/tests/fuzz.rs | 36 +- crates/ec-image/tests/real_library.rs | 135 ++++++ lanes/image-gif-r1.report.md | 66 +++ scripts/gen-still-fixtures.sh | 14 + 8 files changed, 953 insertions(+), 5 deletions(-) create mode 100644 crates/ec-image/src/gif.rs create mode 100644 lanes/image-gif-r1.report.md diff --git a/crates/ec-image/Cargo.toml b/crates/ec-image/Cargo.toml index 6222bfcb..5a9a17b8 100644 --- a/crates/ec-image/Cargo.toml +++ b/crates/ec-image/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ec-image" -description = "Still-image decoding: PNG, JPEG and WebP." +description = "Still-image decoding: PNG, JPEG, WebP and GIF." version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ec-image/src/gif.rs b/crates/ec-image/src/gif.rs new file mode 100644 index 00000000..ce421755 --- /dev/null +++ b/crates/ec-image/src/gif.rs @@ -0,0 +1,571 @@ +//! GIF decoding (GIF87a and GIF89a), including animations. +//! +//! A GIF frame is a palette-indexed sub-rectangle of the logical screen, so a +//! decoder that returns frames must also composite them: each frame is blended +//! onto the canvas -- a transparent pixel keeps whatever was underneath -- and +//! then the frame's disposal method says what the *next* frame starts from. +//! Disposal 2 clears the frame's rectangle to transparent rather than to the +//! logical-screen background colour, which is what every renderer in practice +//! does and what a caller compositing over its own background needs. +//! +//! The LZW dictionary widens its code one code earlier than a reading of the +//! format's prose suggests: the width grows once the entry at index +//! `2^width - 1` has been added, not at `2^width`. Encoders write it that way, +//! so a decoder that waits one code longer reads small pictures correctly and +//! large ones as noise. + +use crate::{AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use ec_core::{Error, Result}; + +/// GIF interlace: `(start, step)` for each of the four passes. +const INTERLACE: [(usize, usize); 4] = [(0, 8), (4, 8), (2, 4), (1, 2)]; + +/// Maximum LZW code width (GIF caps at 12 bits → 4096 entries). +const MAX_CODE_SIZE: u8 = 12; + +/// Maximum number of entries in the LZW dictionary. +const MAX_DICT: usize = 4096; + +/// LSB-first LZW decompressor for a single GIF image-data stream. +/// +/// GIF packs codes least-significant-bit first, starting at `min_code_size + 1` +/// bits. Clear and end codes occupy `1 << min_code_size` and `+1`; derived +/// entries start at `+2`. The dictionary is stored as parallel prefix/suffix +/// arrays so reconstruction is a single backward chain per code. +struct Lzw { + min_code_size: u8, + code_size: u8, + clear_code: u16, + end_code: u16, + /// Code that will be assigned to the next new entry. + next_code: u16, + /// Prefix code for each derived entry (index = code − clear_code − 2). + prefixes: Vec, + /// Suffix byte for each derived entry. + suffixes: Vec, + // Bit accumulator + bit_buffer: u64, + bits_in_buffer: u8, + /// True until the first data code after a clear has been consumed. + first: bool, + /// Last code decoded (needed to build the next dictionary entry). + prev: u16, +} + +impl Lzw { + fn new(min_code_size: u8) -> Self { + let clear_code = 1u16 << min_code_size; + Lzw { + min_code_size, + code_size: min_code_size + 1, + clear_code, + end_code: clear_code + 1, + next_code: clear_code + 2, + prefixes: Vec::new(), + suffixes: Vec::new(), + bit_buffer: 0, + bits_in_buffer: 0, + first: true, + prev: 0, + } + } + + fn reset(&mut self) { + self.code_size = self.min_code_size + 1; + self.next_code = self.clear_code + 2; + self.prefixes.clear(); + self.suffixes.clear(); + self.first = true; + } + + /// Pull the next `code_size`-bit code from `data`. Returns `None` at end + /// of input (not enough bits to fill a code). + fn read_code(&mut self, data: &[u8], pos: &mut usize) -> Option { + while self.bits_in_buffer < self.code_size { + let byte = *data.get(*pos)?; + *pos += 1; + self.bit_buffer |= u64::from(byte) << self.bits_in_buffer; + self.bits_in_buffer += 8; + } + let mask = (1u64 << self.code_size) - 1; + let code = (self.bit_buffer & mask) as u16; + self.bit_buffer >>= self.code_size; + self.bits_in_buffer -= self.code_size; + Some(code) + } + + /// Walk the prefix chain for `code`, appending the decoded bytes to `out`. + /// Returns the first byte of the sequence (needed for the `cScSc` case). + fn reconstruct(&self, code: u16, out: &mut Vec) -> u8 { + // Build the byte sequence by walking backwards, then reverse. + let mut stack: Vec = Vec::new(); + let mut c = code; + loop { + if c < self.clear_code { + // Root entry — a single literal byte. + stack.push(c as u8); + break; + } + let idx = (c - self.clear_code - 2) as usize; + stack.push(self.suffixes[idx]); + c = self.prefixes[idx]; + } + let first = *stack.last().unwrap(); + // stack is in reverse order; pop to emit forward. + while let Some(b) = stack.pop() { + out.push(b); + } + first + } + + /// Add the derived entry `(prev, first_byte)`, and widen the code if that + /// entry filled the width: the comparison happens before `next_code` is + /// incremented, so the widening lands one code earlier than the format's + /// prose reads (see the module docs). + fn derive(&mut self, prev: u16, first_byte: u8) { + if (self.next_code as usize) < MAX_DICT { + self.prefixes.push(prev); + self.suffixes.push(first_byte); + if self.next_code >= (1u16 << self.code_size) - 1 && self.code_size < MAX_CODE_SIZE { + self.code_size += 1; + } + self.next_code += 1; + } + } +} + +/// Decompress a GIF image-data stream into a vector of palette indices. +/// +/// `expected` is `width * height` — the output is checked against it so a +/// truncated stream is caught rather than silently producing a short frame. +fn lzw_decode(min_code_size: u8, data: &[u8], expected: usize) -> Result> { + if !(1..=11).contains(&min_code_size) { + return Err(Error::corrupt(format!( + "GIF: LZW min code size {min_code_size}" + ))); + } + + let mut lzw = Lzw::new(min_code_size); + let mut out = Vec::with_capacity(expected); + let mut pos = 0; + + while let Some(code) = lzw.read_code(data, &mut pos) { + if code == lzw.clear_code { + lzw.reset(); + continue; + } + if code == lzw.end_code { + break; + } + + if lzw.first { + // The first code after a clear outputs directly and seeds `prev` + // but creates no dictionary entry — the GIF LZW variant does not + // add an entry for the very first code in a run. + if code >= lzw.next_code { + return Err(Error::corrupt(format!( + "GIF: first LZW code {code} ≥ next {}", + lzw.next_code + ))); + } + lzw.reconstruct(code, &mut out); + lzw.prev = code; + lzw.first = false; + continue; + } + + let first_byte = if code < lzw.next_code { + // Code is already in the dictionary. + lzw.reconstruct(code, &mut out) + } else if code == lzw.next_code { + // The `cScSc` special case: the code references the entry that is + // about to be created. Its expansion is `prev + prev[0]`. + let f = lzw.reconstruct(lzw.prev, &mut out); + out.push(f); + f + } else { + return Err(Error::corrupt(format!( + "GIF: LZW code {code} > next {}", + lzw.next_code + ))); + }; + + lzw.derive(lzw.prev, first_byte); + lzw.prev = code; + } + + if out.len() < expected { + return Err(Error::corrupt(format!( + "GIF: LZW produced {} indices, expected {expected}", + out.len() + ))); + } + out.truncate(expected); + Ok(out) +} + +/// Cursor over the raw GIF bytes with bounds-checked primitives. +struct Reader<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + fn new(data: &'a [u8]) -> Self { + Reader { data, pos: 0 } + } + + fn u8(&mut self) -> Result { + let b = self + .data + .get(self.pos) + .copied() + .ok_or_else(|| Error::corrupt("GIF: unexpected end of data"))?; + self.pos += 1; + Ok(b) + } + + fn u16(&mut self) -> Result { + let lo = u16::from(self.u8()?); + let hi = u16::from(self.u8()?); + Ok(lo | (hi << 8)) + } + + fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { + let slice = self + .data + .get(self.pos..self.pos + n) + .ok_or_else(|| Error::corrupt("GIF: unexpected end of data"))?; + self.pos += n; + Ok(slice) + } + + /// Read a sub-block chain (size-prefixed segments, terminated by a 0 + /// size byte) into one contiguous buffer. + fn sub_blocks(&mut self) -> Result> { + let mut out = Vec::new(); + loop { + let size = self.u8()? as usize; + if size == 0 { + break; + } + out.extend_from_slice(self.bytes(size)?); + } + Ok(out) + } + + /// Skip a sub-block chain without copying. + fn skip_sub_blocks(&mut self) -> Result<()> { + loop { + let size = self.u8()? as usize; + if size == 0 { + break; + } + self.bytes(size)?; + } + Ok(()) + } +} + +/// Graphic Control Extension fields that affect compositing. +#[derive(Debug, Clone, Copy)] +struct Gce { + disposal: u8, + has_transparent: bool, + transparent_index: u8, + /// Delay in centiseconds (1/100 s). + delay: u16, +} + +/// One image descriptor plus its decoded palette indices and pending GCE. +struct RawFrame { + left: u32, + top: u32, + width: u32, + height: u32, + interlaced: bool, + palette: Vec<[u8; 3]>, + indices: Vec, + gce: Option, +} + +/// Reorder rows from GIF's four-pass interlace order into sequential order. +fn deinterlace(indices: &[u8], width: usize, height: usize) -> Vec { + let mut out = vec![0u8; width * height]; + let mut src = 0usize; + for &(start, step) in &INTERLACE { + let mut dst = start; + while dst < height { + out[dst * width..(dst + 1) * width] + .copy_from_slice(&indices[src * width..(src + 1) * width]); + src += 1; + dst += step; + } + } + out +} + +/// Map palette indices to RGBA pixels; the transparent index becomes a fully +/// transparent pixel, which is what the compositing step tests for. +fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Result> { + let transparent = gce + .filter(|g| g.has_transparent) + .map(|g| g.transparent_index); + let mut out = Vec::with_capacity(indices.len()); + for &idx in indices { + if Some(idx) == transparent { + out.push([0, 0, 0, 0]); + } else { + let c = palette + .get(idx as usize) + .ok_or_else(|| Error::corrupt(format!("GIF: colour index {idx} past palette")))?; + out.push([c[0], c[1], c[2], 255]); + } + } + Ok(out) +} + +/// Composite every raw frame onto a full-canvas buffer: blend the frame over +/// the canvas, then apply its disposal method to the canvas the next frame +/// starts from. +fn composite(frames: Vec, canvas_w: u32, canvas_h: u32) -> Result> { + let cw = canvas_w as usize; + let ch = canvas_h as usize; + let n = cw * ch; + + let mut canvas = vec![[0u8; 4]; n]; + let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len()); + + for frame in frames { + let indices = if frame.interlaced { + deinterlace(&frame.indices, frame.width as usize, frame.height as usize) + } else { + frame.indices + }; + let rgba = indices_to_rgba(&indices, &frame.palette, frame.gce.as_ref())?; + + let fw = frame.width as usize; + let fh = frame.height as usize; + let fl = frame.left as usize; + let ft = frame.top as usize; + let disposal = frame.gce.map(|g| g.disposal).unwrap_or(0); + + // Start from the current canvas (out-of-bounds pixels keep canvas). + let mut output = canvas.clone(); + + for fy in 0..fh { + let cy = ft + fy; + if cy >= ch { + break; + } + for fx in 0..fw { + let cx = fl + fx; + if cx >= cw { + break; + } + let src = &rgba[fy * fw + fx]; + let idx = cy * cw + cx; + // Blend: a transparent frame pixel inherits the canvas. + let composited = if src[3] == 0 { canvas[idx] } else { *src }; + output[idx] = composited; + // Dispose: update the canvas for the *next* frame. + match disposal { + 2 => canvas[idx] = [0, 0, 0, 0], // Background + 3 => { /* Previous: leave canvas unchanged */ } + _ => canvas[idx] = composited, // Keep / Any / unspecified + } + } + } + + let delay = frame.gce.map(|g| g.delay).unwrap_or(0); + result.push((output, u32::from(delay))); + } + + // One colour form for the whole animation: a caller that walks the frames + // must not have the pixel layout change under it halfway through, so a + // single transparent pixel anywhere makes every frame RGBA. + let any_alpha = result + .iter() + .any(|(output, _)| output.iter().any(|p| p[3] < 255)); + + Ok(result + .into_iter() + .map(|(output, delay)| { + let pixels = if any_alpha { + Pixels::Rgba8(output.iter().flat_map(|p| *p).collect()) + } else { + Pixels::Rgb8(output.iter().flat_map(|p| p[..3].to_vec()).collect()) + }; + AnimationFrame { + image: Image { + width: canvas_w, + height: canvas_h, + pixels, + meta: Metadata::default(), + }, + delay_num: delay, + delay_den: 100, + } + }) + .collect()) +} + +/// Dimensions and format from the logical screen descriptor alone. +pub fn info(data: &[u8]) -> Result { + if data.len() < 13 { + return Err(Error::corrupt("GIF: shorter than the 13-byte header")); + } + let sig = &data[..6]; + if sig != b"GIF87a" && sig != b"GIF89a" { + return Err(Error::corrupt("GIF: bad signature")); + } + let width = u16::from_le_bytes([data[6], data[7]]) as u32; + let height = u16::from_le_bytes([data[8], data[9]]) as u32; + Ok(Info { + format: ImageFormat::Gif, + width, + height, + }) +} + +/// Decode a GIF, returning the first composited frame as a still [`Image`]. +pub fn decode(data: &[u8], limits: Limits) -> Result { + let frames = decode_animation(data, limits)?; + frames + .into_iter() + .next() + .map(|f| f.image) + .ok_or_else(|| Error::corrupt("GIF: no frames")) +} + +/// Decode every frame of a GIF, composited onto a full-canvas buffer. +pub fn decode_animation(data: &[u8], limits: Limits) -> Result> { + let mut r = Reader::new(data); + + // Header / signature + let sig = r.bytes(6)?; + if sig != b"GIF87a" && sig != b"GIF89a" { + return Err(Error::corrupt("GIF: bad signature")); + } + + // Logical Screen Descriptor + let canvas_w = u32::from(r.u16()?); + let canvas_h = u32::from(r.u16()?); + limits.check(canvas_w, canvas_h)?; + let packed = r.u8()?; + let _bg = r.u8()?; + let _aspect = r.u8()?; + + // The canvas-sized RGBA buffer is the largest allocation; check it + // against max_alloc before requesting it. + let canvas_bytes = (canvas_w as usize) + .checked_mul(canvas_h as usize) + .and_then(|n| n.checked_mul(4)) + .ok_or_else(|| Error::corrupt("GIF: canvas size overflows usize"))?; + if canvas_bytes > limits.max_alloc { + return Err(Error::unsupported( + format!("{canvas_w}x{canvas_h} RGBA canvas"), + format!("{canvas_bytes} bytes past the {} limit", limits.max_alloc), + )); + } + + let has_gct = packed & 0x80 != 0; + let gct_len = 1usize << ((packed & 0x07) + 1); + + let global_palette: Vec<[u8; 3]> = if has_gct { + let raw = r.bytes(gct_len * 3)?; + raw.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect() + } else { + Vec::new() + }; + + // Block loop + let mut frames = Vec::new(); + let mut pending_gce: Option = None; + + loop { + let block = r.u8()?; + match block { + 0x2C => { + // Image Descriptor + let left = u32::from(r.u16()?); + let top = u32::from(r.u16()?); + let width = u32::from(r.u16()?); + let height = u32::from(r.u16()?); + let fpacked = r.u8()?; + + if width == 0 || height == 0 { + return Err(Error::corrupt("GIF: zero-size frame")); + } + + let has_lct = fpacked & 0x80 != 0; + let interlaced = fpacked & 0x40 != 0; + let lct_len = 1usize << ((fpacked & 0x07) + 1); + + let palette = if has_lct { + let raw = r.bytes(lct_len * 3)?; + raw.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect() + } else if global_palette.is_empty() { + return Err(Error::corrupt("GIF: no colour table for frame")); + } else { + global_palette.clone() + }; + + // Image data: LZW min code size + sub-block chain. + let min_code_size = r.u8()?; + let lzw_data = r.sub_blocks()?; + let indices = lzw_decode( + min_code_size, + &lzw_data, + (width as usize) * (height as usize), + )?; + + frames.push(RawFrame { + left, + top, + width, + height, + interlaced, + palette, + indices, + gce: pending_gce.take(), + }); + } + 0x21 => { + // Extension + let label = r.u8()?; + if label == 0xF9 { + // Graphic Control Extension + let gce_data = r.sub_blocks()?; + if gce_data.len() < 4 { + return Err(Error::corrupt("GIF: GCE shorter than 4 bytes")); + } + let gpacked = gce_data[0]; + let delay = u16::from_le_bytes([gce_data[1], gce_data[2]]); + let transparent_index = gce_data[3]; + pending_gce = Some(Gce { + disposal: (gpacked >> 2) & 0x07, + has_transparent: gpacked & 0x01 != 0, + transparent_index, + delay, + }); + } else { + // Application, comment, plain-text — skip the sub-blocks. + r.skip_sub_blocks()?; + } + } + 0x3B => break, // Trailer + _ => { + return Err(Error::corrupt(format!( + "GIF: unknown block type 0x{block:02X}" + ))); + } + } + } + + if frames.is_empty() { + return Err(Error::corrupt("GIF: no image data")); + } + + composite(frames, canvas_w, canvas_h) +} diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index 0da48893..0a2faccf 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -1,4 +1,4 @@ -//! Still-image decoding: PNG, JPEG and WebP. +//! Still-image decoding: PNG, JPEG, WebP and GIF. //! //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the //! format from the leading bytes and hands back an [`Image`]: dimensions, a @@ -31,6 +31,7 @@ // what keeps the code readable against the text it comes from. #![allow(clippy::needless_range_loop)] +pub mod gif; pub mod jpeg; pub mod png; mod upsample; @@ -51,6 +52,8 @@ pub enum ImageFormat { Jpeg, /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless). WebP, + /// GIF, still or animated (GIF87a and GIF89a). + Gif, } impl ImageFormat { @@ -64,6 +67,8 @@ impl ImageFormat { Some(ImageFormat::Jpeg) } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" { Some(ImageFormat::WebP) + } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") { + Some(ImageFormat::Gif) } else { None } @@ -75,6 +80,7 @@ impl ImageFormat { ImageFormat::Png => "png", ImageFormat::Jpeg => "jpg", ImageFormat::WebP => "webp", + ImageFormat::Gif => "gif", } } } @@ -342,9 +348,10 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { Some(ImageFormat::Png) => png::decode(data, limits), Some(ImageFormat::Jpeg) => jpeg::decode(data, limits), Some(ImageFormat::WebP) => webp::decode(data, limits), + Some(ImageFormat::Gif) => gif::decode(data, limits), None => Err(Error::unsupported( "image", - "no PNG, JPEG or WebP signature at the start of the data", + "no PNG, JPEG, WebP or GIF signature at the start of the data", )), } } @@ -355,13 +362,44 @@ pub fn info(data: &[u8]) -> Result { Some(ImageFormat::Png) => png::info(data), Some(ImageFormat::Jpeg) => jpeg::info(data), Some(ImageFormat::WebP) => webp::info(data), + Some(ImageFormat::Gif) => gif::info(data), None => Err(Error::unsupported( "image", - "no PNG, JPEG or WebP signature at the start of the data", + "no PNG, JPEG, WebP or GIF signature at the start of the data", )), } } +/// One picture of an animation, already composited onto the canvas. +/// +/// A frame is the whole canvas, not the sub-rectangle the file stored, because +/// every consumer of an animation draws whole pictures. +#[derive(Debug, Clone, PartialEq)] +pub struct AnimationFrame { + /// The canvas at this point in the animation. + pub image: Image, + /// How long the frame is shown, in `delay_num / delay_den` seconds. + pub delay_num: u32, + /// The denominator of that delay; GIF counts hundredths of a second. + pub delay_den: u32, +} + +/// Every frame of an animation, composited. +/// +/// A format that cannot animate -- and a single-picture file in one that can +/// -- returns exactly one frame, with a zero delay, so a caller that wants +/// frames never needs to know which format it holds. +pub fn decode_animation(data: &[u8]) -> Result> { + match ImageFormat::guess(data) { + Some(ImageFormat::Gif) => gif::decode_animation(data, Limits::default()), + _ => Ok(vec![AnimationFrame { + image: decode(data)?, + delay_num: 0, + delay_den: 100, + }]), + } +} + /// Read and decode the file at `path`. pub fn open(path: impl AsRef) -> Result { let data = std::fs::read(path).map_err(Error::Io)?; diff --git a/crates/ec-image/tests/differential.rs b/crates/ec-image/tests/differential.rs index 1f15634a..b3cd102d 100644 --- a/crates/ec-image/tests/differential.rs +++ b/crates/ec-image/tests/differential.rs @@ -346,3 +346,93 @@ fn every_fixture_decodes() { failures.join("\n") ); } + +#[test] +fn gif_decodes_pixel_exactly() { + let files = corpus("gif"); + if files.is_empty() && skip("gif") { + return; + } + for path in files { + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let theirs = image::load_from_memory(&bytes).expect("incumbent decode"); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{}", + path.display() + ); + assert_eq!( + ours.to_rgba8(), + theirs.to_rgba8().into_raw(), + "{} (first frame)", + path.file_name().unwrap().to_string_lossy() + ); + eprintln!( + "{:<22} {}x{} exact", + path.file_name().unwrap().to_string_lossy(), + ours.width, + ours.height + ); + } +} + +#[test] +fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() { + use image::AnimationDecoder; + + let path = fixtures().join("animated.gif"); + if !path.exists() && skip("animated.gif") { + return; + } + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::decode_animation(&bytes).expect("our animation decode"); + let theirs: Vec = + image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes)) + .expect("incumbent decoder") + .into_frames() + .collect::, _>>() + .expect("incumbent frames"); + + assert_eq!(ours.len(), theirs.len(), "frame count"); + assert!(ours.len() > 1, "the fixture is not an animation"); + for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() { + let (num, den) = theirs.delay().numer_denom_ms(); + // Both sides quote the delay in their own units; compare in + // milliseconds, which is what a renderer actually waits. + let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den); + let theirs_ms = f64::from(num) / f64::from(den); + assert!( + (ours_ms - theirs_ms).abs() < 0.5, + "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms" + ); + assert_eq!( + (ours.image.width, ours.image.height), + theirs.buffer().dimensions(), + "frame {i} is not the whole canvas" + ); + assert_eq!( + ours.image.to_rgba8(), + theirs.buffer().as_raw().clone(), + "frame {i} samples" + ); + eprintln!("frame {i}: {ours_ms:.0} ms, exact"); + } +} + +#[test] +fn a_still_of_any_format_is_one_frame_of_animation() { + let path = fixtures().join("rgb8.png"); + if !path.exists() && skip("rgb8.png") { + return; + } + let bytes = std::fs::read(&path).unwrap(); + let frames = ec_image::decode_animation(&bytes).expect("decode"); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].delay_num, 0); + assert_eq!( + frames[0].image.to_rgba8(), + ec_image::decode(&bytes).unwrap().to_rgba8() + ); +} diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs index f10ee28d..500528f2 100644 --- a/crates/ec-image/tests/fuzz.rs +++ b/crates/ec-image/tests/fuzz.rs @@ -136,12 +136,46 @@ fn webp_lossless_survives_mutation() { sweep("webp-lossless", "tiny-lossless.webp"); } +#[test] +fn gif_survives_mutation() { + sweep("gif", "tiny.gif"); +} + +/// The animation path has its own frame loop, its own canvas and its own +/// disposal state machine, none of which `decode` reaches past frame one. +#[test] +fn a_gif_animation_survives_mutation() { + let Ok(seed) = std::fs::read(fixtures().join("animated.gif")) else { + eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh"); + return; + }; + let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37); + let mut decoded = 0usize; + for round in 0..ROUNDS { + let head = if round % 2 == 0 { Some(48) } else { None }; + let data = mutate(&mut rng, &seed, head); + if let Ok(frames) = ec_image::decode_animation(&data) { + decoded += 1; + for frame in &frames { + let image = &frame.image; + assert_eq!( + image.to_rgba8().len(), + (image.width as usize) * (image.height as usize) * 4, + "gif-animation round {round}: buffer does not match the dimensions" + ); + } + } + } + eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded"); +} + #[test] fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { - let signatures: [&[u8]; 3] = [ + let signatures: [&[u8]; 4] = [ &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], &[0xff, 0xd8, 0xff, 0xe0], b"RIFF\x40\x00\x00\x00WEBPVP8 ", + b"GIF89a", ]; let mut rng = Rng(0x9e37_79b9_7f4a_7c15); for signature in signatures { diff --git a/crates/ec-image/tests/real_library.rs b/crates/ec-image/tests/real_library.rs index 7862b55a..9a2e20b5 100644 --- a/crates/ec-image/tests/real_library.rs +++ b/crates/ec-image/tests/real_library.rs @@ -120,3 +120,138 @@ fn real_pictures_decode_like_the_incumbent() { failures.join("\n") ); } + +/// Every GIF on this machine, composited frame for frame against the +/// incumbent. +/// +/// The still sweep above compares RGB, which a GIF's transparent index makes +/// meaningless; an animation is only decoded correctly if the canvas, the +/// disposal method and the alpha all agree, so this one compares RGBA over +/// every frame of every file. +#[test] +fn real_gifs_animate_like_the_incumbent() { + use image::AnimationDecoder; + + let files = walk_extension(&library(), "gif", 20); + if files.is_empty() { + eprintln!("skipped: no GIF under ~/Videos or ~/Downloads"); + return; + } + let mut failures = Vec::new(); + for path in &files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let bytes = std::fs::read(path).unwrap(); + let started = std::time::Instant::now(); + let ours = match ec_image::decode_animation(&bytes) { + Ok(frames) => frames, + Err(e) => { + if image::load_from_memory(&bytes).is_ok() { + failures.push(format!( + "{name}: we refuse it, the incumbent decodes it ({e})" + )); + } else { + eprintln!("{name:<44} both refuse: {e}"); + } + continue; + } + }; + let ours_ms = started.elapsed().as_secs_f64() * 1000.0; + let theirs = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes)) + .and_then(|d| d.into_frames().collect::, _>>()); + let theirs = match theirs { + Ok(frames) => frames, + Err(e) => { + eprintln!("{name:<44} we decode it, the incumbent does not ({e})"); + continue; + } + }; + if ours.len() != theirs.len() { + failures.push(format!( + "{name}: {} frames against the incumbent's {}", + ours.len(), + theirs.len() + )); + continue; + } + let mut worst = None; + for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() { + if (ours.image.width, ours.image.height) != theirs.buffer().dimensions() { + worst = Some(format!( + "frame {i}: {}x{} against {:?}", + ours.image.width, + ours.image.height, + theirs.buffer().dimensions() + )); + break; + } + let a = ours.image.to_rgba8(); + let b = theirs.buffer().as_raw(); + let delta = a + .iter() + .zip(b) + .map(|(&x, &y)| x.abs_diff(y)) + .max() + .unwrap_or(0); + let (num, den) = theirs.delay().numer_denom_ms(); + let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den); + let theirs_ms = f64::from(num) / f64::from(den); + if delta != 0 { + worst = Some(format!("frame {i}: max delta {delta}, bar 0")); + break; + } + if (ours_ms - theirs_ms).abs() >= 0.5 { + worst = Some(format!( + "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms" + )); + break; + } + } + eprintln!( + "{name:<44} {}x{} {:>3} frames {ours_ms:>7.1} ms {}", + ours[0].image.width, + ours[0].image.height, + ours.len(), + worst.as_deref().unwrap_or("exact") + ); + if let Some(worst) = worst { + failures.push(format!("{name}: {worst}")); + } + } + assert!( + failures.is_empty(), + "{} of {} real GIFs failed:\n{}", + failures.len(), + files.len(), + failures.join("\n") + ); +} + +/// Every file under `roots` with the given extension, three levels deep. +fn walk_extension(roots: &[PathBuf], extension: &str, cap: usize) -> Vec { + fn walk(dir: &PathBuf, want: &str, depth: usize, out: &mut Vec) { + if depth == 0 { + return; + } + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, want, depth - 1, out); + } else if path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case(want)) + { + out.push(path); + } + } + } + let mut found = Vec::new(); + for root in roots { + walk(root, extension, 3, &mut found); + } + found.sort(); + found.truncate(cap); + found +} diff --git a/lanes/image-gif-r1.report.md b/lanes/image-gif-r1.report.md new file mode 100644 index 00000000..1c7afabe --- /dev/null +++ b/lanes/image-gif-r1.report.md @@ -0,0 +1,66 @@ +# lane-image-gif r1 — GIF decoding in ec-image + +## What landed + +`crates/ec-image/src/gif.rs` (~600 lines): a GIF87a/GIF89a decoder written to the +spec — LSB-first LZW with the one-code-early width bump and the `cScSc` case, +sub-block chains, the four-pass interlace, graphic control extensions (disposal +method, transparent index, delay in centiseconds), local and global colour +tables, and frame compositing (blend, then dispose: method 2 clears the frame +rect to transparent, method 3 leaves the canvas as it was). + +Wired into `lib.rs`: `ImageFormat::Gif`, signature guessing, `decode`, `info`, +and a new animation surface that every format answers: + +```rust +pub struct AnimationFrame { pub image: Image, pub delay_num: u32, pub delay_den: u32 } +pub fn decode_animation(data: &[u8]) -> Result>; +``` + +A still is one frame with a zero delay, so a caller that only wants to play +something never branches on the format. + +One colour form is chosen for the whole animation: a single transparent pixel +anywhere makes every frame RGBA, so a caller walking the frames never has the +pixel layout change under it halfway through. + +## Gates + +| Gate | Result | +| --- | --- | +| `gif_decodes_pixel_exactly` | 6/6 fixtures (still, interlaced, transparent, odd size, animated, tiny) max delta **0** vs `image` 0.25.10 | +| `a_gif_animation_composites_frame_for_frame_like_the_incumbent` | frame count, per-frame delay (±0.5 ms) and every composited frame exact | +| `a_still_of_any_format_is_one_frame_of_animation` | PNG through `decode_animation` matches `decode` | +| `gif_survives_mutation` | 10 000 mutations, no panic, no hang | +| `a_gif_animation_survives_mutation` | 10 000 mutations of the animation path, no panic, no hang | +| `real_gifs_animate_like_the_incumbent` | **7/7 real GIFs on this machine, 454 frames, all exact** | +| `cargo clippy -p ec-image --all-targets -- -D warnings` | clean | +| `cargo test -p ec-image` | 11 + 8 + 2 + unit, 0 failed | + +Real-library table (RGBA, bar 0): + +``` +Bonfire_zpsedocgnqr.gif 800x450 319 frames 9907.7 ms exact +InfoLOTBD.gif 617x623 48 frames 1858.6 ms exact +dark-souls-bonfire.gif 172x236 9 frames 27.5 ms exact +dcmbh13-…-7f0aa41b7895.gif 200x200 28 frames 84.5 ms exact +download.gif 768x384 27 frames 758.3 ms exact +giphy.gif 480x270 6 frames 86.2 ms exact +wj8HNGQ.gif 294x257 17 frames 145.3 ms exact +``` + +(Timings are a debug build; no release perf claim is made.) + +## Why this lane exists + +gpui consumes `image`'s animation surface — `GifDecoder`, `AnimationDecoder`, +`Frame`, `Delay` — so replacing the registry `image` in edith needs a GIF +decoder underneath. The gpui-shaped half lives behind the `gpui` cargo feature +in `shims/image`, the way chrono keeps its serde impls behind one; `ec-image` +itself gains only `decode_animation`, which is a codec fact, not a gpui fact. + +## Not in this lane + +- BMP and TIFF (`ImageFormat` variants gpui names) — separate lanes. +- Animated WebP — separate lane. +- GIF *encoding* — nothing consumes it yet. diff --git a/scripts/gen-still-fixtures.sh b/scripts/gen-still-fixtures.sh index b14370e9..92521497 100755 --- a/scripts/gen-still-fixtures.sh +++ b/scripts/gen-still-fixtures.sh @@ -93,6 +93,19 @@ ffmpeg -loglevel error -y -i "$out/source-flat.png" -c:v libwebp -lossless 1 \ magick -delay 10 "$out/source.png" "$out/source-flat.png" "$out/source-odd.png" \ -loop 0 "$out/animated.webp" +# --- GIF: still, interlaced, transparent, odd-size, animated --------------- +# GIF is palette-only, so every source is quantised first; the differential bar +# is pixel-exact, which only means anything if both decoders see the same file. +magick "$out/source.png" -colors 256 "$out/still.gif" +magick "$out/source.png" -colors 256 -interlace GIF "$out/interlaced.gif" +magick "$out/source.png" -colors 64 -transparent white "$out/trns.gif" +magick "$out/source-odd.png" -colors 256 "$out/odd.gif" +# Three frames, each with its own delay, and a disposal method that clears the +# frame's rectangle -- the compositing path only runs when frames differ. +magick -delay 7 "$out/source.png" -delay 13 "$out/source-flat.png" \ + -delay 4 "$out/source-odd.png" -dispose Background -loop 0 -colors 64 \ + "$out/animated.gif" + # Small versions of each format, for the fuzz sweep: ten thousand mutations # per format is only affordable on a picture that decodes in microseconds. magick "$out/source.png" -resize 32x24! "$out/tiny.png" @@ -100,5 +113,6 @@ magick "$out/tiny.png" -quality 80 -sampling-factor 2x2 "$out/tiny.jpg" ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 0 -quality 75 \ "$out/tiny-lossy.webp" ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp" +magick "$out/tiny.png" -colors 64 "$out/tiny.gif" echo "wrote $(ls "$out" | wc -l) files to $out"