forge
Explore
Log in

Don't you dare go Hollow

GIF decoding and a format-agnostic animation surface

Browse files at this commit

166bcc831db9c01c07944b7f3093fee6d0373ab1Ahmet Kaan GümüşParent: 42d0bf6
  • feat
    • GIF decoding and a format-agnostic animation surface
Show full message
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.tomlmodified+1 -1
@@ -1,6 +1,6 @@
11 [package]
22 name = "ec-image"
3-description = "Still-image decoding: PNG, JPEG and WebP."
3+description = "Still-image decoding: PNG, JPEG, WebP and GIF."
44 version.workspace = true
55 edition.workspace = true
66 license.workspace = true
crates/ec-image/src/gif.rsadded+571 -0
@@ -0,0 +1,571 @@
1+//! GIF decoding (GIF87a and GIF89a), including animations.
2+//!
3+//! A GIF frame is a palette-indexed sub-rectangle of the logical screen, so a
4+//! decoder that returns frames must also composite them: each frame is blended
5+//! onto the canvas -- a transparent pixel keeps whatever was underneath -- and
6+//! then the frame's disposal method says what the *next* frame starts from.
7+//! Disposal 2 clears the frame's rectangle to transparent rather than to the
8+//! logical-screen background colour, which is what every renderer in practice
9+//! does and what a caller compositing over its own background needs.
10+//!
11+//! The LZW dictionary widens its code one code earlier than a reading of the
12+//! format's prose suggests: the width grows once the entry at index
13+//! `2^width - 1` has been added, not at `2^width`. Encoders write it that way,
14+//! so a decoder that waits one code longer reads small pictures correctly and
15+//! large ones as noise.
16+
17+use crate::{AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels};
18+use ec_core::{Error, Result};
19+
20+/// GIF interlace: `(start, step)` for each of the four passes.
21+const INTERLACE: [(usize, usize); 4] = [(0, 8), (4, 8), (2, 4), (1, 2)];
22+
23+/// Maximum LZW code width (GIF caps at 12 bits → 4096 entries).
24+const MAX_CODE_SIZE: u8 = 12;
25+
26+/// Maximum number of entries in the LZW dictionary.
27+const MAX_DICT: usize = 4096;
28+
29+/// LSB-first LZW decompressor for a single GIF image-data stream.
30+///
31+/// GIF packs codes least-significant-bit first, starting at `min_code_size + 1`
32+/// bits. Clear and end codes occupy `1 << min_code_size` and `+1`; derived
33+/// entries start at `+2`. The dictionary is stored as parallel prefix/suffix
34+/// arrays so reconstruction is a single backward chain per code.
35+struct Lzw {
36+ min_code_size: u8,
37+ code_size: u8,
38+ clear_code: u16,
39+ end_code: u16,
40+ /// Code that will be assigned to the next new entry.
41+ next_code: u16,
42+ /// Prefix code for each derived entry (index = code − clear_code − 2).
43+ prefixes: Vec<u16>,
44+ /// Suffix byte for each derived entry.
45+ suffixes: Vec<u8>,
46+ // Bit accumulator
47+ bit_buffer: u64,
48+ bits_in_buffer: u8,
49+ /// True until the first data code after a clear has been consumed.
50+ first: bool,
51+ /// Last code decoded (needed to build the next dictionary entry).
52+ prev: u16,
53+}
54+
55+impl Lzw {
56+ fn new(min_code_size: u8) -> Self {
57+ let clear_code = 1u16 << min_code_size;
58+ Lzw {
59+ min_code_size,
60+ code_size: min_code_size + 1,
61+ clear_code,
62+ end_code: clear_code + 1,
63+ next_code: clear_code + 2,
64+ prefixes: Vec::new(),
65+ suffixes: Vec::new(),
66+ bit_buffer: 0,
67+ bits_in_buffer: 0,
68+ first: true,
69+ prev: 0,
70+ }
71+ }
72+
73+ fn reset(&mut self) {
74+ self.code_size = self.min_code_size + 1;
75+ self.next_code = self.clear_code + 2;
76+ self.prefixes.clear();
77+ self.suffixes.clear();
78+ self.first = true;
79+ }
80+
81+ /// Pull the next `code_size`-bit code from `data`. Returns `None` at end
82+ /// of input (not enough bits to fill a code).
83+ fn read_code(&mut self, data: &[u8], pos: &mut usize) -> Option<u16> {
84+ while self.bits_in_buffer < self.code_size {
85+ let byte = *data.get(*pos)?;
86+ *pos += 1;
87+ self.bit_buffer |= u64::from(byte) << self.bits_in_buffer;
88+ self.bits_in_buffer += 8;
89+ }
90+ let mask = (1u64 << self.code_size) - 1;
91+ let code = (self.bit_buffer & mask) as u16;
92+ self.bit_buffer >>= self.code_size;
93+ self.bits_in_buffer -= self.code_size;
94+ Some(code)
95+ }
96+
97+ /// Walk the prefix chain for `code`, appending the decoded bytes to `out`.
98+ /// Returns the first byte of the sequence (needed for the `cScSc` case).
99+ fn reconstruct(&self, code: u16, out: &mut Vec<u8>) -> u8 {
100+ // Build the byte sequence by walking backwards, then reverse.
101+ let mut stack: Vec<u8> = Vec::new();
102+ let mut c = code;
103+ loop {
104+ if c < self.clear_code {
105+ // Root entry — a single literal byte.
106+ stack.push(c as u8);
107+ break;
108+ }
109+ let idx = (c - self.clear_code - 2) as usize;
110+ stack.push(self.suffixes[idx]);
111+ c = self.prefixes[idx];
112+ }
113+ let first = *stack.last().unwrap();
114+ // stack is in reverse order; pop to emit forward.
115+ while let Some(b) = stack.pop() {
116+ out.push(b);
117+ }
118+ first
119+ }
120+
121+ /// Add the derived entry `(prev, first_byte)`, and widen the code if that
122+ /// entry filled the width: the comparison happens before `next_code` is
123+ /// incremented, so the widening lands one code earlier than the format's
124+ /// prose reads (see the module docs).
125+ fn derive(&mut self, prev: u16, first_byte: u8) {
126+ if (self.next_code as usize) < MAX_DICT {
127+ self.prefixes.push(prev);
128+ self.suffixes.push(first_byte);
129+ if self.next_code >= (1u16 << self.code_size) - 1 && self.code_size < MAX_CODE_SIZE {
130+ self.code_size += 1;
131+ }
132+ self.next_code += 1;
133+ }
134+ }
135+}
136+
137+/// Decompress a GIF image-data stream into a vector of palette indices.
138+///
139+/// `expected` is `width * height` — the output is checked against it so a
140+/// truncated stream is caught rather than silently producing a short frame.
141+fn lzw_decode(min_code_size: u8, data: &[u8], expected: usize) -> Result<Vec<u8>> {
142+ if !(1..=11).contains(&min_code_size) {
143+ return Err(Error::corrupt(format!(
144+ "GIF: LZW min code size {min_code_size}"
145+ )));
146+ }
147+
148+ let mut lzw = Lzw::new(min_code_size);
149+ let mut out = Vec::with_capacity(expected);
150+ let mut pos = 0;
151+
152+ while let Some(code) = lzw.read_code(data, &mut pos) {
153+ if code == lzw.clear_code {
154+ lzw.reset();
155+ continue;
156+ }
157+ if code == lzw.end_code {
158+ break;
159+ }
160+
161+ if lzw.first {
162+ // The first code after a clear outputs directly and seeds `prev`
163+ // but creates no dictionary entry — the GIF LZW variant does not
164+ // add an entry for the very first code in a run.
165+ if code >= lzw.next_code {
166+ return Err(Error::corrupt(format!(
167+ "GIF: first LZW code {code} ≥ next {}",
168+ lzw.next_code
169+ )));
170+ }
171+ lzw.reconstruct(code, &mut out);
172+ lzw.prev = code;
173+ lzw.first = false;
174+ continue;
175+ }
176+
177+ let first_byte = if code < lzw.next_code {
178+ // Code is already in the dictionary.
179+ lzw.reconstruct(code, &mut out)
180+ } else if code == lzw.next_code {
181+ // The `cScSc` special case: the code references the entry that is
182+ // about to be created. Its expansion is `prev + prev[0]`.
183+ let f = lzw.reconstruct(lzw.prev, &mut out);
184+ out.push(f);
185+ f
186+ } else {
187+ return Err(Error::corrupt(format!(
188+ "GIF: LZW code {code} > next {}",
189+ lzw.next_code
190+ )));
191+ };
192+
193+ lzw.derive(lzw.prev, first_byte);
194+ lzw.prev = code;
195+ }
196+
197+ if out.len() < expected {
198+ return Err(Error::corrupt(format!(
199+ "GIF: LZW produced {} indices, expected {expected}",
200+ out.len()
201+ )));
202+ }
203+ out.truncate(expected);
204+ Ok(out)
205+}
206+
207+/// Cursor over the raw GIF bytes with bounds-checked primitives.
208+struct Reader<'a> {
209+ data: &'a [u8],
210+ pos: usize,
211+}
212+
213+impl<'a> Reader<'a> {
214+ fn new(data: &'a [u8]) -> Self {
215+ Reader { data, pos: 0 }
216+ }
217+
218+ fn u8(&mut self) -> Result<u8> {
219+ let b = self
220+ .data
221+ .get(self.pos)
222+ .copied()
223+ .ok_or_else(|| Error::corrupt("GIF: unexpected end of data"))?;
224+ self.pos += 1;
225+ Ok(b)
226+ }
227+
228+ fn u16(&mut self) -> Result<u16> {
229+ let lo = u16::from(self.u8()?);
230+ let hi = u16::from(self.u8()?);
231+ Ok(lo | (hi << 8))
232+ }
233+
234+ fn bytes(&mut self, n: usize) -> Result<&'a [u8]> {
235+ let slice = self
236+ .data
237+ .get(self.pos..self.pos + n)
238+ .ok_or_else(|| Error::corrupt("GIF: unexpected end of data"))?;
239+ self.pos += n;
240+ Ok(slice)
241+ }
242+
243+ /// Read a sub-block chain (size-prefixed segments, terminated by a 0
244+ /// size byte) into one contiguous buffer.
245+ fn sub_blocks(&mut self) -> Result<Vec<u8>> {
246+ let mut out = Vec::new();
247+ loop {
248+ let size = self.u8()? as usize;
249+ if size == 0 {
250+ break;
251+ }
252+ out.extend_from_slice(self.bytes(size)?);
253+ }
254+ Ok(out)
255+ }
256+
257+ /// Skip a sub-block chain without copying.
258+ fn skip_sub_blocks(&mut self) -> Result<()> {
259+ loop {
260+ let size = self.u8()? as usize;
261+ if size == 0 {
262+ break;
263+ }
264+ self.bytes(size)?;
265+ }
266+ Ok(())
267+ }
268+}
269+
270+/// Graphic Control Extension fields that affect compositing.
271+#[derive(Debug, Clone, Copy)]
272+struct Gce {
273+ disposal: u8,
274+ has_transparent: bool,
275+ transparent_index: u8,
276+ /// Delay in centiseconds (1/100 s).
277+ delay: u16,
278+}
279+
280+/// One image descriptor plus its decoded palette indices and pending GCE.
281+struct RawFrame {
282+ left: u32,
283+ top: u32,
284+ width: u32,
285+ height: u32,
286+ interlaced: bool,
287+ palette: Vec<[u8; 3]>,
288+ indices: Vec<u8>,
289+ gce: Option<Gce>,
290+}
291+
292+/// Reorder rows from GIF's four-pass interlace order into sequential order.
293+fn deinterlace(indices: &[u8], width: usize, height: usize) -> Vec<u8> {
294+ let mut out = vec![0u8; width * height];
295+ let mut src = 0usize;
296+ for &(start, step) in &INTERLACE {
297+ let mut dst = start;
298+ while dst < height {
299+ out[dst * width..(dst + 1) * width]
300+ .copy_from_slice(&indices[src * width..(src + 1) * width]);
301+ src += 1;
302+ dst += step;
303+ }
304+ }
305+ out
306+}
307+
308+/// Map palette indices to RGBA pixels; the transparent index becomes a fully
309+/// transparent pixel, which is what the compositing step tests for.
310+fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Result<Vec<[u8; 4]>> {
311+ let transparent = gce
312+ .filter(|g| g.has_transparent)
313+ .map(|g| g.transparent_index);
314+ let mut out = Vec::with_capacity(indices.len());
315+ for &idx in indices {
316+ if Some(idx) == transparent {
317+ out.push([0, 0, 0, 0]);
318+ } else {
319+ let c = palette
320+ .get(idx as usize)
321+ .ok_or_else(|| Error::corrupt(format!("GIF: colour index {idx} past palette")))?;
322+ out.push([c[0], c[1], c[2], 255]);
323+ }
324+ }
325+ Ok(out)
326+}
327+
328+/// Composite every raw frame onto a full-canvas buffer: blend the frame over
329+/// the canvas, then apply its disposal method to the canvas the next frame
330+/// starts from.
331+fn composite(frames: Vec<RawFrame>, canvas_w: u32, canvas_h: u32) -> Result<Vec<AnimationFrame>> {
332+ let cw = canvas_w as usize;
333+ let ch = canvas_h as usize;
334+ let n = cw * ch;
335+
336+ let mut canvas = vec![[0u8; 4]; n];
337+ let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len());
338+
339+ for frame in frames {
340+ let indices = if frame.interlaced {
341+ deinterlace(&frame.indices, frame.width as usize, frame.height as usize)
342+ } else {
343+ frame.indices
344+ };
345+ let rgba = indices_to_rgba(&indices, &frame.palette, frame.gce.as_ref())?;
346+
347+ let fw = frame.width as usize;
348+ let fh = frame.height as usize;
349+ let fl = frame.left as usize;
350+ let ft = frame.top as usize;
351+ let disposal = frame.gce.map(|g| g.disposal).unwrap_or(0);
352+
353+ // Start from the current canvas (out-of-bounds pixels keep canvas).
354+ let mut output = canvas.clone();
355+
356+ for fy in 0..fh {
357+ let cy = ft + fy;
358+ if cy >= ch {
359+ break;
360+ }
361+ for fx in 0..fw {
362+ let cx = fl + fx;
363+ if cx >= cw {
364+ break;
365+ }
366+ let src = &rgba[fy * fw + fx];
367+ let idx = cy * cw + cx;
368+ // Blend: a transparent frame pixel inherits the canvas.
369+ let composited = if src[3] == 0 { canvas[idx] } else { *src };
370+ output[idx] = composited;
371+ // Dispose: update the canvas for the *next* frame.
372+ match disposal {
373+ 2 => canvas[idx] = [0, 0, 0, 0], // Background
374+ 3 => { /* Previous: leave canvas unchanged */ }
375+ _ => canvas[idx] = composited, // Keep / Any / unspecified
376+ }
377+ }
378+ }
379+
380+ let delay = frame.gce.map(|g| g.delay).unwrap_or(0);
381+ result.push((output, u32::from(delay)));
382+ }
383+
384+ // One colour form for the whole animation: a caller that walks the frames
385+ // must not have the pixel layout change under it halfway through, so a
386+ // single transparent pixel anywhere makes every frame RGBA.
387+ let any_alpha = result
388+ .iter()
389+ .any(|(output, _)| output.iter().any(|p| p[3] < 255));
390+
391+ Ok(result
392+ .into_iter()
393+ .map(|(output, delay)| {
394+ let pixels = if any_alpha {
395+ Pixels::Rgba8(output.iter().flat_map(|p| *p).collect())
396+ } else {
397+ Pixels::Rgb8(output.iter().flat_map(|p| p[..3].to_vec()).collect())
398+ };
399+ AnimationFrame {
400+ image: Image {
401+ width: canvas_w,
402+ height: canvas_h,
403+ pixels,
404+ meta: Metadata::default(),
405+ },
406+ delay_num: delay,
407+ delay_den: 100,
408+ }
409+ })
410+ .collect())
411+}
412+
413+/// Dimensions and format from the logical screen descriptor alone.
414+pub fn info(data: &[u8]) -> Result<Info> {
415+ if data.len() < 13 {
416+ return Err(Error::corrupt("GIF: shorter than the 13-byte header"));
417+ }
418+ let sig = &data[..6];
419+ if sig != b"GIF87a" && sig != b"GIF89a" {
420+ return Err(Error::corrupt("GIF: bad signature"));
421+ }
422+ let width = u16::from_le_bytes([data[6], data[7]]) as u32;
423+ let height = u16::from_le_bytes([data[8], data[9]]) as u32;
424+ Ok(Info {
425+ format: ImageFormat::Gif,
426+ width,
427+ height,
428+ })
429+}
430+
431+/// Decode a GIF, returning the first composited frame as a still [`Image`].
432+pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
433+ let frames = decode_animation(data, limits)?;
434+ frames
435+ .into_iter()
436+ .next()
437+ .map(|f| f.image)
438+ .ok_or_else(|| Error::corrupt("GIF: no frames"))
439+}
440+
441+/// Decode every frame of a GIF, composited onto a full-canvas buffer.
442+pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFrame>> {
443+ let mut r = Reader::new(data);
444+
445+ // Header / signature
446+ let sig = r.bytes(6)?;
447+ if sig != b"GIF87a" && sig != b"GIF89a" {
448+ return Err(Error::corrupt("GIF: bad signature"));
449+ }
450+
451+ // Logical Screen Descriptor
452+ let canvas_w = u32::from(r.u16()?);
453+ let canvas_h = u32::from(r.u16()?);
454+ limits.check(canvas_w, canvas_h)?;
455+ let packed = r.u8()?;
456+ let _bg = r.u8()?;
457+ let _aspect = r.u8()?;
458+
459+ // The canvas-sized RGBA buffer is the largest allocation; check it
460+ // against max_alloc before requesting it.
461+ let canvas_bytes = (canvas_w as usize)
462+ .checked_mul(canvas_h as usize)
463+ .and_then(|n| n.checked_mul(4))
464+ .ok_or_else(|| Error::corrupt("GIF: canvas size overflows usize"))?;
465+ if canvas_bytes > limits.max_alloc {
466+ return Err(Error::unsupported(
467+ format!("{canvas_w}x{canvas_h} RGBA canvas"),
468+ format!("{canvas_bytes} bytes past the {} limit", limits.max_alloc),
469+ ));
470+ }
471+
472+ let has_gct = packed & 0x80 != 0;
473+ let gct_len = 1usize << ((packed & 0x07) + 1);
474+
475+ let global_palette: Vec<[u8; 3]> = if has_gct {
476+ let raw = r.bytes(gct_len * 3)?;
477+ raw.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect()
478+ } else {
479+ Vec::new()
480+ };
481+
482+ // Block loop
483+ let mut frames = Vec::new();
484+ let mut pending_gce: Option<Gce> = None;
485+
486+ loop {
487+ let block = r.u8()?;
488+ match block {
489+ 0x2C => {
490+ // Image Descriptor
491+ let left = u32::from(r.u16()?);
492+ let top = u32::from(r.u16()?);
493+ let width = u32::from(r.u16()?);
494+ let height = u32::from(r.u16()?);
495+ let fpacked = r.u8()?;
496+
497+ if width == 0 || height == 0 {
498+ return Err(Error::corrupt("GIF: zero-size frame"));
499+ }
500+
501+ let has_lct = fpacked & 0x80 != 0;
502+ let interlaced = fpacked & 0x40 != 0;
503+ let lct_len = 1usize << ((fpacked & 0x07) + 1);
504+
505+ let palette = if has_lct {
506+ let raw = r.bytes(lct_len * 3)?;
507+ raw.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect()
508+ } else if global_palette.is_empty() {
509+ return Err(Error::corrupt("GIF: no colour table for frame"));
510+ } else {
511+ global_palette.clone()
512+ };
513+
514+ // Image data: LZW min code size + sub-block chain.
515+ let min_code_size = r.u8()?;
516+ let lzw_data = r.sub_blocks()?;
517+ let indices = lzw_decode(
518+ min_code_size,
519+ &lzw_data,
520+ (width as usize) * (height as usize),
521+ )?;
522+
523+ frames.push(RawFrame {
524+ left,
525+ top,
526+ width,
527+ height,
528+ interlaced,
529+ palette,
530+ indices,
531+ gce: pending_gce.take(),
532+ });
533+ }
534+ 0x21 => {
535+ // Extension
536+ let label = r.u8()?;
537+ if label == 0xF9 {
538+ // Graphic Control Extension
539+ let gce_data = r.sub_blocks()?;
540+ if gce_data.len() < 4 {
541+ return Err(Error::corrupt("GIF: GCE shorter than 4 bytes"));
542+ }
543+ let gpacked = gce_data[0];
544+ let delay = u16::from_le_bytes([gce_data[1], gce_data[2]]);
545+ let transparent_index = gce_data[3];
546+ pending_gce = Some(Gce {
547+ disposal: (gpacked >> 2) & 0x07,
548+ has_transparent: gpacked & 0x01 != 0,
549+ transparent_index,
550+ delay,
551+ });
552+ } else {
553+ // Application, comment, plain-text — skip the sub-blocks.
554+ r.skip_sub_blocks()?;
555+ }
556+ }
557+ 0x3B => break, // Trailer
558+ _ => {
559+ return Err(Error::corrupt(format!(
560+ "GIF: unknown block type 0x{block:02X}"
561+ )));
562+ }
563+ }
564+ }
565+
566+ if frames.is_empty() {
567+ return Err(Error::corrupt("GIF: no image data"));
568+ }
569+
570+ composite(frames, canvas_w, canvas_h)
571+}
crates/ec-image/src/lib.rsmodified+41 -3
@@ -1,4 +1,4 @@
1-//! Still-image decoding: PNG, JPEG and WebP.
1+//! Still-image decoding: PNG, JPEG, WebP and GIF.
22 //!
33 //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the
44 //! format from the leading bytes and hands back an [`Image`]: dimensions, a
@@ -31,6 +31,7 @@
3131 // what keeps the code readable against the text it comes from.
3232 #![allow(clippy::needless_range_loop)]
3333
34+pub mod gif;
3435 pub mod jpeg;
3536 pub mod png;
3637 mod upsample;
@@ -51,6 +52,8 @@ pub enum ImageFormat {
5152 Jpeg,
5253 /// WebP: a RIFF container over VP8 (lossy) or VP8L (lossless).
5354 WebP,
55+ /// GIF, still or animated (GIF87a and GIF89a).
56+ Gif,
5457 }
5558
5659 impl ImageFormat {
@@ -64,6 +67,8 @@ impl ImageFormat {
6467 Some(ImageFormat::Jpeg)
6568 } else if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
6669 Some(ImageFormat::WebP)
70+ } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
71+ Some(ImageFormat::Gif)
6772 } else {
6873 None
6974 }
@@ -75,6 +80,7 @@ impl ImageFormat {
7580 ImageFormat::Png => "png",
7681 ImageFormat::Jpeg => "jpg",
7782 ImageFormat::WebP => "webp",
83+ ImageFormat::Gif => "gif",
7884 }
7985 }
8086 }
@@ -342,9 +348,10 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
342348 Some(ImageFormat::Png) => png::decode(data, limits),
343349 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
344350 Some(ImageFormat::WebP) => webp::decode(data, limits),
351+ Some(ImageFormat::Gif) => gif::decode(data, limits),
345352 None => Err(Error::unsupported(
346353 "image",
347- "no PNG, JPEG or WebP signature at the start of the data",
354+ "no PNG, JPEG, WebP or GIF signature at the start of the data",
348355 )),
349356 }
350357 }
@@ -355,13 +362,44 @@ pub fn info(data: &[u8]) -> Result<Info> {
355362 Some(ImageFormat::Png) => png::info(data),
356363 Some(ImageFormat::Jpeg) => jpeg::info(data),
357364 Some(ImageFormat::WebP) => webp::info(data),
365+ Some(ImageFormat::Gif) => gif::info(data),
358366 None => Err(Error::unsupported(
359367 "image",
360- "no PNG, JPEG or WebP signature at the start of the data",
368+ "no PNG, JPEG, WebP or GIF signature at the start of the data",
361369 )),
362370 }
363371 }
364372
373+/// One picture of an animation, already composited onto the canvas.
374+///
375+/// A frame is the whole canvas, not the sub-rectangle the file stored, because
376+/// every consumer of an animation draws whole pictures.
377+#[derive(Debug, Clone, PartialEq)]
378+pub struct AnimationFrame {
379+ /// The canvas at this point in the animation.
380+ pub image: Image,
381+ /// How long the frame is shown, in `delay_num / delay_den` seconds.
382+ pub delay_num: u32,
383+ /// The denominator of that delay; GIF counts hundredths of a second.
384+ pub delay_den: u32,
385+}
386+
387+/// Every frame of an animation, composited.
388+///
389+/// A format that cannot animate -- and a single-picture file in one that can
390+/// -- returns exactly one frame, with a zero delay, so a caller that wants
391+/// frames never needs to know which format it holds.
392+pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> {
393+ match ImageFormat::guess(data) {
394+ Some(ImageFormat::Gif) => gif::decode_animation(data, Limits::default()),
395+ _ => Ok(vec![AnimationFrame {
396+ image: decode(data)?,
397+ delay_num: 0,
398+ delay_den: 100,
399+ }]),
400+ }
401+}
402+
365403 /// Read and decode the file at `path`.
366404 pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> {
367405 let data = std::fs::read(path).map_err(Error::Io)?;
crates/ec-image/tests/differential.rsmodified+90 -0
@@ -346,3 +346,93 @@ fn every_fixture_decodes() {
346346 failures.join("\n")
347347 );
348348 }
349+
350+#[test]
351+fn gif_decodes_pixel_exactly() {
352+ let files = corpus("gif");
353+ if files.is_empty() && skip("gif") {
354+ return;
355+ }
356+ for path in files {
357+ let bytes = std::fs::read(&path).unwrap();
358+ let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
359+ let theirs = image::load_from_memory(&bytes).expect("incumbent decode");
360+ assert_eq!(
361+ (ours.width, ours.height),
362+ theirs.dimensions(),
363+ "{}",
364+ path.display()
365+ );
366+ assert_eq!(
367+ ours.to_rgba8(),
368+ theirs.to_rgba8().into_raw(),
369+ "{} (first frame)",
370+ path.file_name().unwrap().to_string_lossy()
371+ );
372+ eprintln!(
373+ "{:<22} {}x{} exact",
374+ path.file_name().unwrap().to_string_lossy(),
375+ ours.width,
376+ ours.height
377+ );
378+ }
379+}
380+
381+#[test]
382+fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() {
383+ use image::AnimationDecoder;
384+
385+ let path = fixtures().join("animated.gif");
386+ if !path.exists() && skip("animated.gif") {
387+ return;
388+ }
389+ let bytes = std::fs::read(&path).unwrap();
390+ let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
391+ let theirs: Vec<image::Frame> =
392+ image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes))
393+ .expect("incumbent decoder")
394+ .into_frames()
395+ .collect::<Result<Vec<_>, _>>()
396+ .expect("incumbent frames");
397+
398+ assert_eq!(ours.len(), theirs.len(), "frame count");
399+ assert!(ours.len() > 1, "the fixture is not an animation");
400+ for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() {
401+ let (num, den) = theirs.delay().numer_denom_ms();
402+ // Both sides quote the delay in their own units; compare in
403+ // milliseconds, which is what a renderer actually waits.
404+ let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den);
405+ let theirs_ms = f64::from(num) / f64::from(den);
406+ assert!(
407+ (ours_ms - theirs_ms).abs() < 0.5,
408+ "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms"
409+ );
410+ assert_eq!(
411+ (ours.image.width, ours.image.height),
412+ theirs.buffer().dimensions(),
413+ "frame {i} is not the whole canvas"
414+ );
415+ assert_eq!(
416+ ours.image.to_rgba8(),
417+ theirs.buffer().as_raw().clone(),
418+ "frame {i} samples"
419+ );
420+ eprintln!("frame {i}: {ours_ms:.0} ms, exact");
421+ }
422+}
423+
424+#[test]
425+fn a_still_of_any_format_is_one_frame_of_animation() {
426+ let path = fixtures().join("rgb8.png");
427+ if !path.exists() && skip("rgb8.png") {
428+ return;
429+ }
430+ let bytes = std::fs::read(&path).unwrap();
431+ let frames = ec_image::decode_animation(&bytes).expect("decode");
432+ assert_eq!(frames.len(), 1);
433+ assert_eq!(frames[0].delay_num, 0);
434+ assert_eq!(
435+ frames[0].image.to_rgba8(),
436+ ec_image::decode(&bytes).unwrap().to_rgba8()
437+ );
438+}
crates/ec-image/tests/fuzz.rsmodified+35 -1
@@ -136,12 +136,46 @@ fn webp_lossless_survives_mutation() {
136136 sweep("webp-lossless", "tiny-lossless.webp");
137137 }
138138
139+#[test]
140+fn gif_survives_mutation() {
141+ sweep("gif", "tiny.gif");
142+}
143+
144+/// The animation path has its own frame loop, its own canvas and its own
145+/// disposal state machine, none of which `decode` reaches past frame one.
146+#[test]
147+fn a_gif_animation_survives_mutation() {
148+ let Ok(seed) = std::fs::read(fixtures().join("animated.gif")) else {
149+ eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
150+ return;
151+ };
152+ let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37);
153+ let mut decoded = 0usize;
154+ for round in 0..ROUNDS {
155+ let head = if round % 2 == 0 { Some(48) } else { None };
156+ let data = mutate(&mut rng, &seed, head);
157+ if let Ok(frames) = ec_image::decode_animation(&data) {
158+ decoded += 1;
159+ for frame in &frames {
160+ let image = &frame.image;
161+ assert_eq!(
162+ image.to_rgba8().len(),
163+ (image.width as usize) * (image.height as usize) * 4,
164+ "gif-animation round {round}: buffer does not match the dimensions"
165+ );
166+ }
167+ }
168+ }
169+ eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded");
170+}
171+
139172 #[test]
140173 fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
141- let signatures: [&[u8]; 3] = [
174+ let signatures: [&[u8]; 4] = [
142175 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
143176 &[0xff, 0xd8, 0xff, 0xe0],
144177 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
178+ b"GIF89a",
145179 ];
146180 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
147181 for signature in signatures {
crates/ec-image/tests/real_library.rsmodified+135 -0
@@ -120,3 +120,138 @@ fn real_pictures_decode_like_the_incumbent() {
120120 failures.join("\n")
121121 );
122122 }
123+
124+/// Every GIF on this machine, composited frame for frame against the
125+/// incumbent.
126+///
127+/// The still sweep above compares RGB, which a GIF's transparent index makes
128+/// meaningless; an animation is only decoded correctly if the canvas, the
129+/// disposal method and the alpha all agree, so this one compares RGBA over
130+/// every frame of every file.
131+#[test]
132+fn real_gifs_animate_like_the_incumbent() {
133+ use image::AnimationDecoder;
134+
135+ let files = walk_extension(&library(), "gif", 20);
136+ if files.is_empty() {
137+ eprintln!("skipped: no GIF under ~/Videos or ~/Downloads");
138+ return;
139+ }
140+ let mut failures = Vec::new();
141+ for path in &files {
142+ let name = path.file_name().unwrap().to_string_lossy().to_string();
143+ let bytes = std::fs::read(path).unwrap();
144+ let started = std::time::Instant::now();
145+ let ours = match ec_image::decode_animation(&bytes) {
146+ Ok(frames) => frames,
147+ Err(e) => {
148+ if image::load_from_memory(&bytes).is_ok() {
149+ failures.push(format!(
150+ "{name}: we refuse it, the incumbent decodes it ({e})"
151+ ));
152+ } else {
153+ eprintln!("{name:<44} both refuse: {e}");
154+ }
155+ continue;
156+ }
157+ };
158+ let ours_ms = started.elapsed().as_secs_f64() * 1000.0;
159+ let theirs = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes))
160+ .and_then(|d| d.into_frames().collect::<Result<Vec<_>, _>>());
161+ let theirs = match theirs {
162+ Ok(frames) => frames,
163+ Err(e) => {
164+ eprintln!("{name:<44} we decode it, the incumbent does not ({e})");
165+ continue;
166+ }
167+ };
168+ if ours.len() != theirs.len() {
169+ failures.push(format!(
170+ "{name}: {} frames against the incumbent's {}",
171+ ours.len(),
172+ theirs.len()
173+ ));
174+ continue;
175+ }
176+ let mut worst = None;
177+ for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() {
178+ if (ours.image.width, ours.image.height) != theirs.buffer().dimensions() {
179+ worst = Some(format!(
180+ "frame {i}: {}x{} against {:?}",
181+ ours.image.width,
182+ ours.image.height,
183+ theirs.buffer().dimensions()
184+ ));
185+ break;
186+ }
187+ let a = ours.image.to_rgba8();
188+ let b = theirs.buffer().as_raw();
189+ let delta = a
190+ .iter()
191+ .zip(b)
192+ .map(|(&x, &y)| x.abs_diff(y))
193+ .max()
194+ .unwrap_or(0);
195+ let (num, den) = theirs.delay().numer_denom_ms();
196+ let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den);
197+ let theirs_ms = f64::from(num) / f64::from(den);
198+ if delta != 0 {
199+ worst = Some(format!("frame {i}: max delta {delta}, bar 0"));
200+ break;
201+ }
202+ if (ours_ms - theirs_ms).abs() >= 0.5 {
203+ worst = Some(format!(
204+ "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms"
205+ ));
206+ break;
207+ }
208+ }
209+ eprintln!(
210+ "{name:<44} {}x{} {:>3} frames {ours_ms:>7.1} ms {}",
211+ ours[0].image.width,
212+ ours[0].image.height,
213+ ours.len(),
214+ worst.as_deref().unwrap_or("exact")
215+ );
216+ if let Some(worst) = worst {
217+ failures.push(format!("{name}: {worst}"));
218+ }
219+ }
220+ assert!(
221+ failures.is_empty(),
222+ "{} of {} real GIFs failed:\n{}",
223+ failures.len(),
224+ files.len(),
225+ failures.join("\n")
226+ );
227+}
228+
229+/// Every file under `roots` with the given extension, three levels deep.
230+fn walk_extension(roots: &[PathBuf], extension: &str, cap: usize) -> Vec<PathBuf> {
231+ fn walk(dir: &PathBuf, want: &str, depth: usize, out: &mut Vec<PathBuf>) {
232+ if depth == 0 {
233+ return;
234+ }
235+ let Ok(entries) = std::fs::read_dir(dir) else {
236+ return;
237+ };
238+ for entry in entries.flatten() {
239+ let path = entry.path();
240+ if path.is_dir() {
241+ walk(&path, want, depth - 1, out);
242+ } else if path
243+ .extension()
244+ .is_some_and(|e| e.eq_ignore_ascii_case(want))
245+ {
246+ out.push(path);
247+ }
248+ }
249+ }
250+ let mut found = Vec::new();
251+ for root in roots {
252+ walk(root, extension, 3, &mut found);
253+ }
254+ found.sort();
255+ found.truncate(cap);
256+ found
257+}
lanes/image-gif-r1.report.mdadded+66 -0
@@ -0,0 +1,66 @@
1+# lane-image-gif r1 — GIF decoding in ec-image
2+
3+## What landed
4+
5+`crates/ec-image/src/gif.rs` (~600 lines): a GIF87a/GIF89a decoder written to the
6+spec — LSB-first LZW with the one-code-early width bump and the `cScSc` case,
7+sub-block chains, the four-pass interlace, graphic control extensions (disposal
8+method, transparent index, delay in centiseconds), local and global colour
9+tables, and frame compositing (blend, then dispose: method 2 clears the frame
10+rect to transparent, method 3 leaves the canvas as it was).
11+
12+Wired into `lib.rs`: `ImageFormat::Gif`, signature guessing, `decode`, `info`,
13+and a new animation surface that every format answers:
14+
15+```rust
16+pub struct AnimationFrame { pub image: Image, pub delay_num: u32, pub delay_den: u32 }
17+pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>>;
18+```
19+
20+A still is one frame with a zero delay, so a caller that only wants to play
21+something never branches on the format.
22+
23+One colour form is chosen for the whole animation: a single transparent pixel
24+anywhere makes every frame RGBA, so a caller walking the frames never has the
25+pixel layout change under it halfway through.
26+
27+## Gates
28+
29+| Gate | Result |
30+| --- | --- |
31+| `gif_decodes_pixel_exactly` | 6/6 fixtures (still, interlaced, transparent, odd size, animated, tiny) max delta **0** vs `image` 0.25.10 |
32+| `a_gif_animation_composites_frame_for_frame_like_the_incumbent` | frame count, per-frame delay (±0.5 ms) and every composited frame exact |
33+| `a_still_of_any_format_is_one_frame_of_animation` | PNG through `decode_animation` matches `decode` |
34+| `gif_survives_mutation` | 10 000 mutations, no panic, no hang |
35+| `a_gif_animation_survives_mutation` | 10 000 mutations of the animation path, no panic, no hang |
36+| `real_gifs_animate_like_the_incumbent` | **7/7 real GIFs on this machine, 454 frames, all exact** |
37+| `cargo clippy -p ec-image --all-targets -- -D warnings` | clean |
38+| `cargo test -p ec-image` | 11 + 8 + 2 + unit, 0 failed |
39+
40+Real-library table (RGBA, bar 0):
41+
42+```
43+Bonfire_zpsedocgnqr.gif 800x450 319 frames 9907.7 ms exact
44+InfoLOTBD.gif 617x623 48 frames 1858.6 ms exact
45+dark-souls-bonfire.gif 172x236 9 frames 27.5 ms exact
46+dcmbh13-…-7f0aa41b7895.gif 200x200 28 frames 84.5 ms exact
47+download.gif 768x384 27 frames 758.3 ms exact
48+giphy.gif 480x270 6 frames 86.2 ms exact
49+wj8HNGQ.gif 294x257 17 frames 145.3 ms exact
50+```
51+
52+(Timings are a debug build; no release perf claim is made.)
53+
54+## Why this lane exists
55+
56+gpui consumes `image`'s animation surface — `GifDecoder`, `AnimationDecoder`,
57+`Frame`, `Delay` — so replacing the registry `image` in edith needs a GIF
58+decoder underneath. The gpui-shaped half lives behind the `gpui` cargo feature
59+in `shims/image`, the way chrono keeps its serde impls behind one; `ec-image`
60+itself gains only `decode_animation`, which is a codec fact, not a gpui fact.
61+
62+## Not in this lane
63+
64+- BMP and TIFF (`ImageFormat` variants gpui names) — separate lanes.
65+- Animated WebP — separate lane.
66+- GIF *encoding* — nothing consumes it yet.
scripts/gen-still-fixtures.shmodified+14 -0
@@ -93,6 +93,19 @@ ffmpeg -loglevel error -y -i "$out/source-flat.png" -c:v libwebp -lossless 1 \
9393 magick -delay 10 "$out/source.png" "$out/source-flat.png" "$out/source-odd.png" \
9494 -loop 0 "$out/animated.webp"
9595
96+# --- GIF: still, interlaced, transparent, odd-size, animated ---------------
97+# GIF is palette-only, so every source is quantised first; the differential bar
98+# is pixel-exact, which only means anything if both decoders see the same file.
99+magick "$out/source.png" -colors 256 "$out/still.gif"
100+magick "$out/source.png" -colors 256 -interlace GIF "$out/interlaced.gif"
101+magick "$out/source.png" -colors 64 -transparent white "$out/trns.gif"
102+magick "$out/source-odd.png" -colors 256 "$out/odd.gif"
103+# Three frames, each with its own delay, and a disposal method that clears the
104+# frame's rectangle -- the compositing path only runs when frames differ.
105+magick -delay 7 "$out/source.png" -delay 13 "$out/source-flat.png" \
106+ -delay 4 "$out/source-odd.png" -dispose Background -loop 0 -colors 64 \
107+ "$out/animated.gif"
108+
96109 # Small versions of each format, for the fuzz sweep: ten thousand mutations
97110 # per format is only affordable on a picture that decodes in microseconds.
98111 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"
100113 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 0 -quality 75 \
101114 "$out/tiny-lossy.webp"
102115 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp"
116+magick "$out/tiny.png" -colors 64 "$out/tiny.gif"
103117
104118 echo "wrote $(ls "$out" | wc -l) files to $out"