Skip to main content

threers_codec/gif/
decode.rs

1//! Dependency-free GIF87a/GIF89a decoder.
2//!
3//! The compositing canvas starts as transparent black, and
4//! [`DisposalMethod::RestoreBackground`] clears to transparent black. This is
5//! intentional: it preserves transparent GIF round-trips instead of treating
6//! the logical-screen background color as opaque.
7
8use std::error::Error;
9use std::fmt;
10
11/// Why a GIF could not be decoded.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum GifError {
14    /// Byte stream ended before a complete block.
15    Truncated,
16    /// Missing or invalid `GIF87a` / `GIF89a` signature.
17    BadSignature,
18    /// Signature was present but not a supported version.
19    BadVersion,
20    /// LZW bitstream could not be decoded.
21    BadLzw,
22    /// Malformed extension or image block.
23    BadBlock,
24    /// Width/height or rectangle arithmetic overflowed.
25    Overflow,
26    /// Expected more bytes in a sub-block.
27    UnexpectedEof,
28    /// Required color table missing or oversized.
29    InvalidPalette,
30    /// Disposal method value is outside 0..=3.
31    InvalidDisposal,
32    /// Requested frame index exceeds [`GifInfo::frame_count`].
33    FrameOutOfBounds,
34}
35
36impl fmt::Display for GifError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        let message = match self {
39            Self::Truncated => "truncated GIF",
40            Self::BadSignature => "invalid GIF signature",
41            Self::BadVersion => "unsupported GIF version",
42            Self::BadLzw => "invalid GIF LZW stream",
43            Self::BadBlock => "invalid GIF block",
44            Self::Overflow => "GIF dimensions overflow",
45            Self::UnexpectedEof => "unexpected end of GIF data",
46            Self::InvalidPalette => "missing or invalid GIF color table",
47            Self::InvalidDisposal => "invalid GIF disposal method",
48            Self::FrameOutOfBounds => "GIF frame index out of bounds",
49        };
50        f.write_str(message)
51    }
52}
53
54impl Error for GifError {}
55
56/// GIF version from the six-byte signature.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum GifVersion {
59    /// Original GIF87a.
60    Gif87a,
61    /// GIF89a (extensions, transparency, Netscape loop, …).
62    Gif89a,
63}
64
65/// How the decoder treats the canvas after displaying a frame (GCE field).
66#[repr(u8)]
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub enum DisposalMethod {
69    /// No disposal specified.
70    #[default]
71    None = 0,
72    /// Leave the graphic in place.
73    DoNotDispose = 1,
74    /// Restore the frame rectangle to background (transparent black here).
75    RestoreBackground = 2,
76    /// Restore the canvas as it was before this frame.
77    RestorePrevious = 3,
78}
79
80/// Logical-screen metadata from a GIF file.
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct GifInfo {
83    /// Logical-screen width in pixels.
84    pub width: u32,
85    /// Logical-screen height in pixels.
86    pub height: u32,
87    /// `GIF87a` or `GIF89a`.
88    pub version: GifVersion,
89    /// The global colour table, if the file has one.
90    pub global_palette: Option<Vec<[u8; 3]>>,
91    /// Index into the global table of the background colour.
92    pub background_index: u8,
93    /// The Netscape loop field as stored. `Some(0)` means infinite looping;
94    /// `None` means no Netscape loop extension was present.
95    pub loop_count: Option<u16>,
96    /// Image descriptors in the file.
97    pub frame_count: usize,
98    /// Comment extension payloads, in file order.
99    pub comments: Vec<Vec<u8>>,
100}
101
102/// Per-frame descriptor metadata (before LZW decode / compositing).
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct GifFrameMeta {
105    /// Frame delay in centiseconds.
106    pub delay_cs: u16,
107    /// What happens to this frame's rectangle before the next one is drawn.
108    pub disposal: DisposalMethod,
109    /// The palette index drawn as transparent, if any.
110    pub transparent: Option<u8>,
111    /// Left edge of the frame's rectangle on the canvas.
112    pub x: u16,
113    /// Top edge of the frame's rectangle on the canvas.
114    pub y: u16,
115    /// Width of the frame's rectangle.
116    pub w: u16,
117    /// Height of the frame's rectangle.
118    pub h: u16,
119    /// Whether rows are stored in the four-pass interlaced order.
120    pub interlaced: bool,
121    /// The frame's own colour table, overriding the global one.
122    pub local_palette: Option<Vec<[u8; 3]>>,
123}
124
125/// One composited full-canvas frame.
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub struct GifFrame {
128    /// Full logical-screen RGBA canvas after this frame has been composited.
129    pub rgba: Vec<u8>,
130    /// Delay numerator (centiseconds from the GCE).
131    pub delay_num: u16,
132    /// Delay denominator (always `100` for GIF centiseconds).
133    pub delay_den: u16,
134    /// The frame's descriptor, as parsed.
135    pub meta: GifFrameMeta,
136}
137
138/// The old name of [`GifFrame`].
139#[deprecated(
140    since = "0.0.7",
141    note = "renamed `GifFrame`, so it is not mistaken for the video decoder's `codec::decode::DecodedFrame`"
142)]
143pub type DecodedFrame = GifFrame;
144
145#[derive(Clone, Debug)]
146struct IndexedFrame {
147    meta: GifFrameMeta,
148    min_code_size: u8,
149    compressed: Vec<u8>,
150}
151
152/// Indexed GIF reader with lazy or eager frame decoding.
153///
154/// Call [`Self::open`] to parse the container, then [`Self::decode_frame`] /
155/// [`Self::decode_all`]. Random access to frame `i` decodes `0..=i` in order so
156/// disposal state stays correct.
157pub struct GifDecoder {
158    info: GifInfo,
159    frames: Vec<IndexedFrame>,
160    decoded: Vec<GifFrame>,
161    canvas: Vec<u8>,
162    restore_previous: Option<Vec<u8>>,
163}
164
165#[derive(Clone, Copy, Default)]
166struct GraphicControl {
167    delay_cs: u16,
168    disposal: DisposalMethod,
169    transparent: Option<u8>,
170}
171
172impl GifDecoder {
173    /// Parses the header and indexes image data. A missing final trailer is
174    /// accepted when all preceding blocks are complete.
175    pub fn open(bytes: &[u8]) -> Result<Self, GifError> {
176        if bytes.len() < 6 {
177            return Err(GifError::Truncated);
178        }
179        if &bytes[..3] != b"GIF" {
180            return Err(GifError::BadSignature);
181        }
182        let version = match &bytes[3..6] {
183            b"87a" => GifVersion::Gif87a,
184            b"89a" => GifVersion::Gif89a,
185            _ => return Err(GifError::BadVersion),
186        };
187
188        let mut reader = Reader::new(bytes, 6);
189        let width = reader.u16()? as u32;
190        let height = reader.u16()? as u32;
191        if width == 0 || height == 0 {
192            return Err(GifError::BadBlock);
193        }
194        let packed = reader.byte()?;
195        let background_index = reader.byte()?;
196        let _pixel_aspect = reader.byte()?;
197        let global_palette = if packed & 0x80 != 0 {
198            Some(reader.palette(table_len(packed))?)
199        } else {
200            None
201        };
202
203        let mut frames = Vec::new();
204        let mut comments = Vec::new();
205        let mut loop_count = None;
206        let mut gce = GraphicControl::default();
207
208        while !reader.at_end() {
209            match reader.byte()? {
210                0x3b => break,
211                0x2c => {
212                    let x = reader.u16()?;
213                    let y = reader.u16()?;
214                    let w = reader.u16()?;
215                    let h = reader.u16()?;
216                    if w == 0 || h == 0 {
217                        return Err(GifError::BadBlock);
218                    }
219                    let right = u32::from(x)
220                        .checked_add(u32::from(w))
221                        .ok_or(GifError::Overflow)?;
222                    let bottom = u32::from(y)
223                        .checked_add(u32::from(h))
224                        .ok_or(GifError::Overflow)?;
225                    if right > width || bottom > height {
226                        return Err(GifError::Overflow);
227                    }
228                    let image_packed = reader.byte()?;
229                    let local_palette = if image_packed & 0x80 != 0 {
230                        Some(reader.palette(table_len(image_packed))?)
231                    } else {
232                        None
233                    };
234                    if local_palette.is_none() && global_palette.is_none() {
235                        return Err(GifError::InvalidPalette);
236                    }
237                    let min_code_size = reader.byte()?;
238                    if !(2..=8).contains(&min_code_size) {
239                        return Err(GifError::BadLzw);
240                    }
241                    let compressed = reader.sub_blocks()?;
242                    frames.push(IndexedFrame {
243                        meta: GifFrameMeta {
244                            delay_cs: gce.delay_cs,
245                            disposal: gce.disposal,
246                            transparent: gce.transparent,
247                            x,
248                            y,
249                            w,
250                            h,
251                            interlaced: image_packed & 0x40 != 0,
252                            local_palette,
253                        },
254                        min_code_size,
255                        compressed,
256                    });
257                    gce = GraphicControl::default();
258                }
259                0x21 => {
260                    let label = reader.byte()?;
261                    match label {
262                        0xf9 => {
263                            if reader.byte()? != 4 {
264                                return Err(GifError::BadBlock);
265                            }
266                            let control = reader.byte()?;
267                            let disposal = match (control >> 2) & 7 {
268                                0 => DisposalMethod::None,
269                                1 => DisposalMethod::DoNotDispose,
270                                2 => DisposalMethod::RestoreBackground,
271                                3 => DisposalMethod::RestorePrevious,
272                                _ => return Err(GifError::InvalidDisposal),
273                            };
274                            let delay_cs = reader.u16()?;
275                            let transparent_index = reader.byte()?;
276                            if reader.byte()? != 0 {
277                                return Err(GifError::BadBlock);
278                            }
279                            gce = GraphicControl {
280                                delay_cs,
281                                disposal,
282                                transparent: (control & 1 != 0).then_some(transparent_index),
283                            };
284                        }
285                        0xfe => comments.push(reader.sub_blocks()?),
286                        0xff => {
287                            let app_len = reader.byte()? as usize;
288                            let app = reader.take(app_len)?;
289                            let data = reader.sub_blocks()?;
290                            if app == b"NETSCAPE2.0" && data.len() >= 3 && data[0] == 1 {
291                                loop_count = Some(u16::from_le_bytes([data[1], data[2]]));
292                            }
293                        }
294                        // Plain-text and unrecognized extensions are chains of
295                        // data sub-blocks and can safely be ignored.
296                        _ => {
297                            reader.sub_blocks()?;
298                        }
299                    }
300                }
301                _ => return Err(GifError::BadBlock),
302            }
303        }
304
305        let pixel_bytes = canvas_len(width, height)?;
306        let frame_count = frames.len();
307        Ok(Self {
308            info: GifInfo {
309                width,
310                height,
311                version,
312                global_palette,
313                background_index,
314                loop_count,
315                frame_count,
316                comments,
317            },
318            frames,
319            decoded: Vec::new(),
320            canvas: Vec::with_capacity(pixel_bytes.min(4096)),
321            restore_previous: None,
322        })
323    }
324
325    /// The file-level information parsed by [`open`](Self::open).
326    pub fn info(&self) -> &GifInfo {
327        &self.info
328    }
329
330    /// Frames in the file.
331    pub fn frame_count(&self) -> usize {
332        self.frames.len()
333    }
334
335    /// Frame `i`'s descriptor, without decoding it.
336    pub fn frame_meta(&self, i: usize) -> Result<&GifFrameMeta, GifError> {
337        self.frames
338            .get(i)
339            .map(|frame| &frame.meta)
340            .ok_or(GifError::FrameOutOfBounds)
341    }
342
343    /// Decodes sequentially through `i`; already decoded frames are cached.
344    pub fn decode_frame(&mut self, i: usize) -> Result<GifFrame, GifError> {
345        if i >= self.frames.len() {
346            return Err(GifError::FrameOutOfBounds);
347        }
348        while self.decoded.len() <= i {
349            self.decode_next()?;
350        }
351        Ok(self.decoded[i].clone())
352    }
353
354    /// Decode and composite every frame.
355    pub fn decode_all(mut self) -> Result<Vec<GifFrame>, GifError> {
356        while self.decoded.len() < self.frames.len() {
357            self.decode_next()?;
358        }
359        Ok(self.decoded)
360    }
361
362    fn decode_next(&mut self) -> Result<(), GifError> {
363        let index = self.decoded.len();
364        if index == 0 {
365            let len = canvas_len(self.info.width, self.info.height)?;
366            self.canvas
367                .try_reserve_exact(len)
368                .map_err(|_| GifError::Overflow)?;
369            self.canvas.resize(len, 0);
370        } else {
371            let previous = &self.frames[index - 1].meta;
372            match previous.disposal {
373                DisposalMethod::None | DisposalMethod::DoNotDispose => {}
374                DisposalMethod::RestoreBackground => {
375                    clear_rect(&mut self.canvas, self.info.width, previous)
376                }
377                DisposalMethod::RestorePrevious => {
378                    let backup = self.restore_previous.take().ok_or(GifError::BadBlock)?;
379                    self.canvas = backup;
380                }
381            }
382        }
383
384        let frame = &self.frames[index];
385        self.restore_previous = if frame.meta.disposal == DisposalMethod::RestorePrevious {
386            Some(self.canvas.clone())
387        } else {
388            None
389        };
390        let expected = usize::from(frame.meta.w)
391            .checked_mul(usize::from(frame.meta.h))
392            .ok_or(GifError::Overflow)?;
393        let mut indices = lzw_decode(&frame.compressed, frame.min_code_size, expected)?;
394        if frame.meta.interlaced {
395            indices = deinterlace(&indices, frame.meta.w as usize, frame.meta.h as usize);
396        }
397        let palette = frame
398            .meta
399            .local_palette
400            .as_deref()
401            .or(self.info.global_palette.as_deref())
402            .ok_or(GifError::InvalidPalette)?;
403        composite(
404            &mut self.canvas,
405            self.info.width,
406            &frame.meta,
407            palette,
408            &indices,
409        )?;
410        self.decoded.push(GifFrame {
411            rgba: self.canvas.clone(),
412            delay_num: frame.meta.delay_cs,
413            delay_den: 100,
414            meta: frame.meta.clone(),
415        });
416        Ok(())
417    }
418}
419
420/// Decode an entire GIF into logical-screen metadata and composited RGBA frames.
421pub fn decode_gif(bytes: &[u8]) -> Result<(GifInfo, Vec<GifFrame>), GifError> {
422    let decoder = GifDecoder::open(bytes)?;
423    let info = decoder.info.clone();
424    let frames = decoder.decode_all()?;
425    Ok((info, frames))
426}
427
428fn table_len(packed: u8) -> usize {
429    1usize << (usize::from(packed & 7) + 1)
430}
431
432fn canvas_len(width: u32, height: u32) -> Result<usize, GifError> {
433    usize::try_from(width)
434        .ok()
435        .and_then(|w| usize::try_from(height).ok().and_then(|h| w.checked_mul(h)))
436        .and_then(|pixels| pixels.checked_mul(4))
437        .ok_or(GifError::Overflow)
438}
439
440fn clear_rect(canvas: &mut [u8], canvas_width: u32, meta: &GifFrameMeta) {
441    let stride = canvas_width as usize * 4;
442    for y in usize::from(meta.y)..usize::from(meta.y) + usize::from(meta.h) {
443        let start = y * stride + usize::from(meta.x) * 4;
444        let end = start + usize::from(meta.w) * 4;
445        canvas[start..end].fill(0);
446    }
447}
448
449fn composite(
450    canvas: &mut [u8],
451    canvas_width: u32,
452    meta: &GifFrameMeta,
453    palette: &[[u8; 3]],
454    indices: &[u8],
455) -> Result<(), GifError> {
456    let w = usize::from(meta.w);
457    let stride = canvas_width as usize;
458    for (offset, &color_index) in indices.iter().enumerate() {
459        if meta.transparent == Some(color_index) {
460            continue;
461        }
462        let rgb = palette
463            .get(color_index as usize)
464            .ok_or(GifError::InvalidPalette)?;
465        let x = usize::from(meta.x) + offset % w;
466        let y = usize::from(meta.y) + offset / w;
467        let dst = (y * stride + x) * 4;
468        canvas[dst..dst + 3].copy_from_slice(rgb);
469        canvas[dst + 3] = 255;
470    }
471    Ok(())
472}
473
474fn deinterlace(input: &[u8], width: usize, height: usize) -> Vec<u8> {
475    let mut output = vec![0; input.len()];
476    let mut source = 0;
477    for (start, step) in [(0usize, 8usize), (4, 8), (2, 4), (1, 2)] {
478        for y in (start..height).step_by(step) {
479            output[y * width..(y + 1) * width].copy_from_slice(&input[source..source + width]);
480            source += width;
481        }
482    }
483    output
484}
485
486fn lzw_decode(data: &[u8], min_code_size: u8, expected: usize) -> Result<Vec<u8>, GifError> {
487    let clear = 1u16 << min_code_size;
488    let end = clear + 1;
489    let mut dictionary = Vec::<Vec<u8>>::with_capacity(4096);
490    reset_dictionary(&mut dictionary, clear);
491    let mut next_code = end + 1;
492    let mut code_size = u32::from(min_code_size) + 1;
493    let mut bits = BitReader::new(data);
494    let mut previous: Option<Vec<u8>> = None;
495    let mut output = Vec::with_capacity(expected);
496    let mut saw_end = false;
497
498    while let Some(code) = bits.read(code_size) {
499        if code == clear {
500            reset_dictionary(&mut dictionary, clear);
501            next_code = end + 1;
502            code_size = u32::from(min_code_size) + 1;
503            previous = None;
504            continue;
505        }
506        if code == end {
507            saw_end = true;
508            break;
509        }
510        if code >= 4096 {
511            return Err(GifError::BadLzw);
512        }
513
514        let entry = if let Some(entry) = dictionary.get(code as usize) {
515            entry.clone()
516        } else if code == next_code {
517            let mut entry = previous.clone().ok_or(GifError::BadLzw)?;
518            let first = *entry.first().ok_or(GifError::BadLzw)?;
519            entry.push(first);
520            entry
521        } else {
522            return Err(GifError::BadLzw);
523        };
524        if output
525            .len()
526            .checked_add(entry.len())
527            .ok_or(GifError::Overflow)?
528            > expected
529        {
530            return Err(GifError::BadLzw);
531        }
532        output.extend_from_slice(&entry);
533
534        // Once the required pixels are complete, the encoder writes EOI
535        // without adding another dictionary entry. Avoid a spurious width
536        // bump at exactly that boundary.
537        if output.len() < expected
538            && let Some(previous_entry) = previous.as_ref()
539            && next_code < 4096
540        {
541            let mut new_entry = previous_entry.clone();
542            new_entry.push(entry[0]);
543            if dictionary.len() != next_code as usize {
544                return Err(GifError::BadLzw);
545            }
546            dictionary.push(new_entry);
547            next_code += 1;
548            // The decoder reconstructs an encoder dictionary entry one
549            // emitted code later. Grow as soon as the reconstructed
550            // `next_code` reaches the encoder's width boundary, before
551            // reading the following code.
552            if next_code == (1 << code_size) && code_size < 12 {
553                code_size += 1;
554            }
555        }
556        previous = Some(entry);
557    }
558
559    if !saw_end || output.len() != expected {
560        return Err(GifError::BadLzw);
561    }
562    Ok(output)
563}
564
565fn reset_dictionary(dictionary: &mut Vec<Vec<u8>>, clear: u16) {
566    dictionary.clear();
567    dictionary.extend((0..clear).map(|value| vec![value as u8]));
568    // Reserve slots for Clear and EOI so code indices line up directly.
569    dictionary.push(Vec::new());
570    dictionary.push(Vec::new());
571}
572
573struct BitReader<'a> {
574    data: &'a [u8],
575    byte: usize,
576    buffer: u32,
577    bits: u32,
578}
579
580impl<'a> BitReader<'a> {
581    fn new(data: &'a [u8]) -> Self {
582        Self {
583            data,
584            byte: 0,
585            buffer: 0,
586            bits: 0,
587        }
588    }
589
590    fn read(&mut self, width: u32) -> Option<u16> {
591        while self.bits < width {
592            let byte = *self.data.get(self.byte)?;
593            self.byte += 1;
594            self.buffer |= u32::from(byte) << self.bits;
595            self.bits += 8;
596        }
597        let code = self.buffer & ((1 << width) - 1);
598        self.buffer >>= width;
599        self.bits -= width;
600        Some(code as u16)
601    }
602}
603
604struct Reader<'a> {
605    bytes: &'a [u8],
606    position: usize,
607}
608
609impl<'a> Reader<'a> {
610    fn new(bytes: &'a [u8], position: usize) -> Self {
611        Self { bytes, position }
612    }
613
614    fn at_end(&self) -> bool {
615        self.position == self.bytes.len()
616    }
617
618    fn byte(&mut self) -> Result<u8, GifError> {
619        let byte = self
620            .bytes
621            .get(self.position)
622            .copied()
623            .ok_or(GifError::UnexpectedEof)?;
624        self.position += 1;
625        Ok(byte)
626    }
627
628    fn u16(&mut self) -> Result<u16, GifError> {
629        let bytes = self.take(2)?;
630        Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
631    }
632
633    fn take(&mut self, length: usize) -> Result<&'a [u8], GifError> {
634        let end = self
635            .position
636            .checked_add(length)
637            .ok_or(GifError::Overflow)?;
638        let bytes = self
639            .bytes
640            .get(self.position..end)
641            .ok_or(GifError::UnexpectedEof)?;
642        self.position = end;
643        Ok(bytes)
644    }
645
646    fn palette(&mut self, length: usize) -> Result<Vec<[u8; 3]>, GifError> {
647        let bytes = self.take(length.checked_mul(3).ok_or(GifError::Overflow)?)?;
648        Ok(bytes
649            .as_chunks::<3>()
650            .0
651            .iter()
652            .map(|rgb| [rgb[0], rgb[1], rgb[2]])
653            .collect())
654    }
655
656    fn sub_blocks(&mut self) -> Result<Vec<u8>, GifError> {
657        let mut output = Vec::new();
658        loop {
659            let length = self.byte()? as usize;
660            if length == 0 {
661                return Ok(output);
662            }
663            let block = self.take(length)?;
664            output
665                .try_reserve(block.len())
666                .map_err(|_| GifError::Overflow)?;
667            output.extend_from_slice(block);
668        }
669    }
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675    use crate::gif::{DisposalMode, GifEncoder, GifOptions, PaletteMode};
676
677    fn solid(w: u32, h: u32, color: [u8; 4]) -> Vec<u8> {
678        color.repeat((w * h) as usize)
679    }
680
681    fn close(actual: &[u8], expected: &[u8], tolerance: i16) {
682        assert_eq!(actual.len(), expected.len());
683        for (a, b) in actual.iter().zip(expected) {
684            assert!((i16::from(*a) - i16::from(*b)).abs() <= tolerance);
685        }
686    }
687
688    #[test]
689    fn round_trip_solid_frames() {
690        let mut encoder = GifEncoder::new(4, 3, 0)
691            .dither(false)
692            .diff_rects(false)
693            .palette_mode(PaletteMode::Local);
694        encoder.add_frame(&solid(4, 3, [240, 20, 10, 255]), 3, 100);
695        encoder.add_frame(&solid(4, 3, [10, 30, 230, 255]), 7, 100);
696        let (info, frames) = decode_gif(&encoder.finish()).unwrap();
697        assert_eq!((info.width, info.height, info.frame_count), (4, 3, 2));
698        assert_eq!(info.loop_count, Some(0));
699        close(&frames[0].rgba[..4], &[240, 20, 10, 255], 4);
700        close(&frames[1].rgba[..4], &[10, 30, 230, 255], 4);
701        assert_eq!((frames[1].delay_num, frames[1].delay_den), (7, 100));
702    }
703
704    #[test]
705    fn encoder_lzw_decodes_every_index() {
706        let mut pixels = Vec::new();
707        for i in 0..256u16 {
708            pixels.extend_from_slice(&[(i & 255) as u8, (255 - i) as u8, 17, 255]);
709        }
710        let mut encoder = GifEncoder::new(16, 16, 1)
711            .colors(256)
712            .dither(false)
713            .diff_rects(false)
714            .transparency(false);
715        encoder.add_frame(&pixels, 1, 100);
716        let (_, frames) = decode_gif(&encoder.finish()).unwrap();
717        assert_eq!(frames[0].rgba.len(), pixels.len());
718        assert!(frames[0]
719            .rgba
720            .as_chunks::<4>()
721            .0
722            .iter()
723            .all(|pixel| pixel[3] == 255));
724    }
725
726    #[test]
727    fn truncated_and_bad_signature_are_errors() {
728        assert!(matches!(
729            GifDecoder::open(b"GIF89"),
730            Err(GifError::Truncated)
731        ));
732        assert!(matches!(
733            GifDecoder::open(b"NOPE89a"),
734            Err(GifError::BadSignature)
735        ));
736    }
737
738    #[test]
739    fn interlaced_content_matches_plain_content() {
740        let mut pixels = Vec::new();
741        for y in 0..13u8 {
742            for x in 0..9u8 {
743                pixels.extend_from_slice(&[x * 20, y * 17, x ^ y, 255]);
744            }
745        }
746        let options = GifOptions::default()
747            .colors(256)
748            .dither(false)
749            .diff_rects(false)
750            .transparency(false);
751        let mut plain = GifEncoder::new(9, 13, 1).options(options.clone());
752        plain.add_frame(&pixels, 1, 100);
753        let mut interlaced = GifEncoder::new(9, 13, 1).options(options.interlace(true));
754        interlaced.add_frame(&pixels, 1, 100);
755        let (_, plain_frames) = decode_gif(&plain.finish()).unwrap();
756        let (_, interlaced_frames) = decode_gif(&interlaced.finish()).unwrap();
757        assert_eq!(plain_frames[0].rgba, interlaced_frames[0].rgba);
758        assert!(interlaced_frames[0].meta.interlaced);
759    }
760
761    #[test]
762    fn dirty_rect_keeps_unchanged_canvas_pixels() {
763        let first = solid(8, 8, [10, 20, 30, 255]);
764        let mut second = first.clone();
765        for y in 3..5 {
766            for x in 2..4 {
767                let offset = (y * 8 + x) * 4;
768                second[offset..offset + 4].copy_from_slice(&[240, 5, 10, 255]);
769            }
770        }
771        let mut encoder = GifEncoder::new(8, 8, 1)
772            .dither(false)
773            .diff_rects(true)
774            .disposal(DisposalMode::Keep);
775        encoder.add_frame(&first, 1, 100);
776        encoder.add_frame(&second, 1, 100);
777        let bytes = encoder.finish();
778        let mut decoder = GifDecoder::open(&bytes).unwrap();
779        decoder.decode_frame(0).unwrap();
780        let second_frame = decoder.decode_frame(1).unwrap();
781        close(&second_frame.rgba[0..4], &[10, 20, 30, 255], 4);
782        let changed = (3 * 8 + 2) * 4;
783        close(
784            &second_frame.rgba[changed..changed + 4],
785            &[240, 5, 10, 255],
786            4,
787        );
788    }
789}