forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gif.rs591 lines, 20.2 KiBHistoryRawDownload
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
17use crate::{AllocBudget, AnimationFrame, Image, ImageFormat, Info, Limits, Metadata, Pixels};
18use ec_core::{Error, Result};
19
20/// GIF interlace: `(start, step)` for each of the four passes.
21const 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).
24const MAX_CODE_SIZE: u8 = 12;
25
26/// Maximum number of entries in the LZW dictionary.
27const 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.
35struct 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
55impl 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.
141fn 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 out.len() >= expected {
154 // Output already satisfies the declared frame size; a bomb-style
155 // stream can keep growing the dictionary and emitting further
156 // codes after this point, so stop before decoding any more of
157 // them rather than let `out` expand unbounded (LZW bomb).
158 break;
159 }
160 if code == lzw.clear_code {
161 lzw.reset();
162 continue;
163 }
164 if code == lzw.end_code {
165 break;
166 }
167
168 if lzw.first {
169 // The first code after a clear outputs directly and seeds `prev`
170 // but creates no dictionary entry — the GIF LZW variant does not
171 // add an entry for the very first code in a run.
172 if code >= lzw.next_code {
173 return Err(Error::corrupt(format!(
174 "GIF: first LZW code {code} ≥ next {}",
175 lzw.next_code
176 )));
177 }
178 lzw.reconstruct(code, &mut out);
179 lzw.prev = code;
180 lzw.first = false;
181 continue;
182 }
183
184 let first_byte = if code < lzw.next_code {
185 // Code is already in the dictionary.
186 lzw.reconstruct(code, &mut out)
187 } else if code == lzw.next_code {
188 // The `cScSc` special case: the code references the entry that is
189 // about to be created. Its expansion is `prev + prev[0]`.
190 let f = lzw.reconstruct(lzw.prev, &mut out);
191 out.push(f);
192 f
193 } else {
194 return Err(Error::corrupt(format!(
195 "GIF: LZW code {code} > next {}",
196 lzw.next_code
197 )));
198 };
199
200 lzw.derive(lzw.prev, first_byte);
201 lzw.prev = code;
202 }
203
204 if out.len() < expected {
205 return Err(Error::corrupt(format!(
206 "GIF: LZW produced {} indices, expected {expected}",
207 out.len()
208 )));
209 }
210 out.truncate(expected);
211 Ok(out)
212}
213
214/// Cursor over the raw GIF bytes with bounds-checked primitives.
215struct Reader<'a> {
216 data: &'a [u8],
217 pos: usize,
218}
219
220impl<'a> Reader<'a> {
221 fn new(data: &'a [u8]) -> Self {
222 Reader { data, pos: 0 }
223 }
224
225 fn u8(&mut self) -> Result<u8> {
226 let b = self
227 .data
228 .get(self.pos)
229 .copied()
230 .ok_or_else(|| Error::corrupt("GIF: unexpected end of data"))?;
231 self.pos += 1;
232 Ok(b)
233 }
234
235 fn u16(&mut self) -> Result<u16> {
236 let lo = u16::from(self.u8()?);
237 let hi = u16::from(self.u8()?);
238 Ok(lo | (hi << 8))
239 }
240
241 fn bytes(&mut self, n: usize) -> Result<&'a [u8]> {
242 let slice = self
243 .data
244 .get(self.pos..self.pos + n)
245 .ok_or_else(|| Error::corrupt("GIF: unexpected end of data"))?;
246 self.pos += n;
247 Ok(slice)
248 }
249
250 /// Read a sub-block chain (size-prefixed segments, terminated by a 0
251 /// size byte) into one contiguous buffer.
252 fn sub_blocks(&mut self) -> Result<Vec<u8>> {
253 let mut out = Vec::new();
254 loop {
255 let size = self.u8()? as usize;
256 if size == 0 {
257 break;
258 }
259 out.extend_from_slice(self.bytes(size)?);
260 }
261 Ok(out)
262 }
263
264 /// Skip a sub-block chain without copying.
265 fn skip_sub_blocks(&mut self) -> Result<()> {
266 loop {
267 let size = self.u8()? as usize;
268 if size == 0 {
269 break;
270 }
271 self.bytes(size)?;
272 }
273 Ok(())
274 }
275}
276
277/// Graphic Control Extension fields that affect compositing.
278#[derive(Debug, Clone, Copy)]
279struct Gce {
280 disposal: u8,
281 has_transparent: bool,
282 transparent_index: u8,
283 /// Delay in centiseconds (1/100 s).
284 delay: u16,
285}
286
287/// One image descriptor plus its decoded palette indices and pending GCE.
288struct RawFrame {
289 left: u32,
290 top: u32,
291 width: u32,
292 height: u32,
293 interlaced: bool,
294 palette: Vec<[u8; 3]>,
295 indices: Vec<u8>,
296 gce: Option<Gce>,
297}
298
299/// Reorder rows from GIF's four-pass interlace order into sequential order.
300fn deinterlace(indices: &[u8], width: usize, height: usize) -> Vec<u8> {
301 let mut out = vec![0u8; width * height];
302 let mut src = 0usize;
303 for &(start, step) in &INTERLACE {
304 let mut dst = start;
305 while dst < height {
306 out[dst * width..(dst + 1) * width]
307 .copy_from_slice(&indices[src * width..(src + 1) * width]);
308 src += 1;
309 dst += step;
310 }
311 }
312 out
313}
314
315/// Map palette indices to RGBA pixels; the transparent index becomes a fully
316/// transparent pixel, which is what the compositing step tests for.
317fn indices_to_rgba(indices: &[u8], palette: &[[u8; 3]], gce: Option<&Gce>) -> Result<Vec<[u8; 4]>> {
318 let transparent = gce
319 .filter(|g| g.has_transparent)
320 .map(|g| g.transparent_index);
321 let mut out = Vec::with_capacity(indices.len());
322 for &idx in indices {
323 if Some(idx) == transparent {
324 out.push([0, 0, 0, 0]);
325 } else {
326 let c = palette
327 .get(idx as usize)
328 .ok_or_else(|| Error::corrupt(format!("GIF: colour index {idx} past palette")))?;
329 out.push([c[0], c[1], c[2], 255]);
330 }
331 }
332 Ok(out)
333}
334
335/// Composite every raw frame onto a full-canvas buffer: blend the frame over
336/// the canvas, then apply its disposal method to the canvas the next frame
337/// starts from.
338fn composite(
339 frames: Vec<RawFrame>,
340 canvas_w: u32,
341 canvas_h: u32,
342 limits: &Limits,
343 budget: &mut AllocBudget,
344) -> Result<Vec<AnimationFrame>> {
345 let cw = canvas_w as usize;
346 let ch = canvas_h as usize;
347 let n = cw * ch;
348
349 let mut canvas = vec![[0u8; 4]; n];
350 let mut result: Vec<(Vec<[u8; 4]>, u32)> = Vec::with_capacity(frames.len());
351
352 for frame in frames {
353 // Every frame clones the whole canvas -- the real multiplier a
354 // single buffer's own bound never catches -- so it is spent from the
355 // decode-wide budget just like the frame's own indices were above.
356 budget.spend(limits, "GIF composited canvas", n * 4)?;
357 let indices = if frame.interlaced {
358 deinterlace(&frame.indices, frame.width as usize, frame.height as usize)
359 } else {
360 frame.indices
361 };
362 let rgba = indices_to_rgba(&indices, &frame.palette, frame.gce.as_ref())?;
363
364 let fw = frame.width as usize;
365 let fh = frame.height as usize;
366 let fl = frame.left as usize;
367 let ft = frame.top as usize;
368 let disposal = frame.gce.map(|g| g.disposal).unwrap_or(0);
369
370 // Start from the current canvas (out-of-bounds pixels keep canvas).
371 let mut output = canvas.clone();
372
373 for fy in 0..fh {
374 let cy = ft + fy;
375 if cy >= ch {
376 break;
377 }
378 for fx in 0..fw {
379 let cx = fl + fx;
380 if cx >= cw {
381 break;
382 }
383 let src = &rgba[fy * fw + fx];
384 let idx = cy * cw + cx;
385 // Blend: a transparent frame pixel inherits the canvas.
386 let composited = if src[3] == 0 { canvas[idx] } else { *src };
387 output[idx] = composited;
388 // Dispose: update the canvas for the *next* frame.
389 match disposal {
390 2 => canvas[idx] = [0, 0, 0, 0], // Background
391 3 => { /* Previous: leave canvas unchanged */ }
392 _ => canvas[idx] = composited, // Keep / Any / unspecified
393 }
394 }
395 }
396
397 let delay = frame.gce.map(|g| g.delay).unwrap_or(0);
398 result.push((output, u32::from(delay)));
399 }
400
401 // One colour form for the whole animation: a caller that walks the frames
402 // must not have the pixel layout change under it halfway through, so a
403 // single transparent pixel anywhere makes every frame RGBA.
404 let any_alpha = result
405 .iter()
406 .any(|(output, _)| output.iter().any(|p| p[3] < 255));
407
408 Ok(result
409 .into_iter()
410 .map(|(output, delay)| {
411 let pixels = if any_alpha {
412 Pixels::Rgba8(output.iter().flat_map(|p| *p).collect())
413 } else {
414 Pixels::Rgb8(output.iter().flat_map(|p| p[..3].to_vec()).collect())
415 };
416 AnimationFrame {
417 image: Image {
418 width: canvas_w,
419 height: canvas_h,
420 pixels,
421 meta: Metadata::default(),
422 },
423 delay_num: delay,
424 delay_den: 100,
425 }
426 })
427 .collect())
428}
429
430/// Dimensions and format from the logical screen descriptor alone.
431pub fn info(data: &[u8]) -> Result<Info> {
432 if data.len() < 13 {
433 return Err(Error::corrupt("GIF: shorter than the 13-byte header"));
434 }
435 let sig = &data[..6];
436 if sig != b"GIF87a" && sig != b"GIF89a" {
437 return Err(Error::corrupt("GIF: bad signature"));
438 }
439 let width = u16::from_le_bytes([data[6], data[7]]) as u32;
440 let height = u16::from_le_bytes([data[8], data[9]]) as u32;
441 Ok(Info {
442 format: ImageFormat::Gif,
443 width,
444 height,
445 // GIF has no EXIF; the orientation is the identity.
446 orientation: 1,
447 })
448}
449
450/// Decode a GIF, returning the first composited frame as a still [`Image`].
451pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
452 let frames = decode_animation(data, limits)?;
453 frames
454 .into_iter()
455 .next()
456 .map(|f| f.image)
457 .ok_or_else(|| Error::corrupt("GIF: no frames"))
458}
459
460/// Decode every frame of a GIF, composited onto a full-canvas buffer.
461pub fn decode_animation(data: &[u8], limits: Limits) -> Result<Vec<AnimationFrame>> {
462 let mut r = Reader::new(data);
463
464 // Header / signature
465 let sig = r.bytes(6)?;
466 if sig != b"GIF87a" && sig != b"GIF89a" {
467 return Err(Error::corrupt("GIF: bad signature"));
468 }
469
470 // Logical Screen Descriptor
471 let canvas_w = u32::from(r.u16()?);
472 let canvas_h = u32::from(r.u16()?);
473 limits.check(canvas_w, canvas_h)?;
474 let packed = r.u8()?;
475 let _bg = r.u8()?;
476 let _aspect = r.u8()?;
477
478 // The canvas-sized RGBA buffer is the largest allocation; check it
479 // against max_alloc before requesting it.
480 let canvas_bytes = limits.check_output(canvas_w, canvas_h, 4)?;
481
482 let has_gct = packed & 0x80 != 0;
483 let gct_len = 1usize << ((packed & 0x07) + 1);
484
485 let global_palette: Vec<[u8; 3]> = if has_gct {
486 let raw = r.bytes(gct_len * 3)?;
487 raw.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect()
488 } else {
489 Vec::new()
490 };
491
492 // Block loop
493 let mut frames = Vec::new();
494 let mut pending_gce: Option<Gce> = None;
495 let mut budget = AllocBudget::default();
496 budget.spend(&limits, "GIF canvas", canvas_bytes)?;
497
498 loop {
499 let block = r.u8()?;
500 match block {
501 0x2C => {
502 // Image Descriptor
503 let left = u32::from(r.u16()?);
504 let top = u32::from(r.u16()?);
505 let width = u32::from(r.u16()?);
506 let height = u32::from(r.u16()?);
507 let fpacked = r.u8()?;
508
509 if width == 0 || height == 0 {
510 return Err(Error::corrupt("GIF: zero-size frame"));
511 }
512 // A frame's own rectangle is a header field like any other --
513 // nothing says it has to fit inside the canvas the logical
514 // screen descriptor already bounded, so it gets its own check
515 // before it sizes the indices buffer below.
516 limits.check(width, height)?;
517 let indices_bytes =
518 limits.check_bytes("GIF frame indices", (width as usize).checked_mul(height as usize))?;
519 budget.spend(&limits, "GIF frame indices", indices_bytes)?;
520
521 let has_lct = fpacked & 0x80 != 0;
522 let interlaced = fpacked & 0x40 != 0;
523 let lct_len = 1usize << ((fpacked & 0x07) + 1);
524
525 let palette = if has_lct {
526 let raw = r.bytes(lct_len * 3)?;
527 raw.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect()
528 } else if global_palette.is_empty() {
529 return Err(Error::corrupt("GIF: no colour table for frame"));
530 } else {
531 global_palette.clone()
532 };
533
534 // Image data: LZW min code size + sub-block chain.
535 let min_code_size = r.u8()?;
536 let lzw_data = r.sub_blocks()?;
537 let indices = lzw_decode(
538 min_code_size,
539 &lzw_data,
540 (width as usize) * (height as usize),
541 )?;
542
543 frames.push(RawFrame {
544 left,
545 top,
546 width,
547 height,
548 interlaced,
549 palette,
550 indices,
551 gce: pending_gce.take(),
552 });
553 }
554 0x21 => {
555 // Extension
556 let label = r.u8()?;
557 if label == 0xF9 {
558 // Graphic Control Extension
559 let gce_data = r.sub_blocks()?;
560 if gce_data.len() < 4 {
561 return Err(Error::corrupt("GIF: GCE shorter than 4 bytes"));
562 }
563 let gpacked = gce_data[0];
564 let delay = u16::from_le_bytes([gce_data[1], gce_data[2]]);
565 let transparent_index = gce_data[3];
566 pending_gce = Some(Gce {
567 disposal: (gpacked >> 2) & 0x07,
568 has_transparent: gpacked & 0x01 != 0,
569 transparent_index,
570 delay,
571 });
572 } else {
573 // Application, comment, plain-text — skip the sub-blocks.
574 r.skip_sub_blocks()?;
575 }
576 }
577 0x3B => break, // Trailer
578 _ => {
579 return Err(Error::corrupt(format!(
580 "GIF: unknown block type 0x{block:02X}"
581 )));
582 }
583 }
584 }
585
586 if frames.is_empty() {
587 return Err(Error::corrupt("GIF: no image data"));
588 }
589
590 composite(frames, canvas_w, canvas_h, &limits, &mut budget)
591}