Skip to main content

pltrs_codec/gif/
mod.rs

1//! GIF files.
2//!
3//! * [`GifEncoder`] writes animated GIFs (GIF89a): RGBA frames are reduced
4//!   to one shared palette of at most 256 colours, frames identical to the
5//!   one before are merged into it, and opaque animations store only the
6//!   rectangle that changed from frame to frame.
7//! * [`decode`] reads a file's first frame as Pillow opens it: palette
8//!   indices (local or global table, interlaced or not) with the
9//!   transparent index, on the logical screen.
10
11mod decode;
12mod lzw;
13mod palette;
14
15use std::fmt;
16
17pub use self::decode::{DecodeError, decode};
18use self::palette::Palette;
19
20/// One frame of an animation: RGBA pixels, row by row, and how long the
21/// frame is shown in hundredths of a second.
22#[derive(Clone, Copy, Debug)]
23pub struct GifFrame<'a> {
24    /// `width × height × 4` bytes of straight (not premultiplied) RGBA.
25    pub pixels: &'a [u8],
26    /// The display time in centiseconds.
27    pub delay: u16,
28}
29
30/// Why frames could not be encoded.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum GifError {
33    /// A side is zero or larger than GIF's 65 535 pixels.
34    InvalidDimensions {
35        /// The requested width.
36        width: u32,
37        /// The requested height.
38        height: u32,
39    },
40    /// A frame's pixel data does not have `width × height × 4` bytes.
41    DataLengthMismatch {
42        /// The frame's position.
43        index: usize,
44        /// The bytes needed.
45        expected: usize,
46        /// The bytes given.
47        actual: usize,
48    },
49    /// There were no frames.
50    NoFrames,
51}
52
53impl fmt::Display for GifError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::InvalidDimensions { width, height } => write!(
57                f,
58                "a GIF cannot be {width} × {height} pixels (each side must be 1 to 65535)"
59            ),
60            Self::DataLengthMismatch {
61                index,
62                expected,
63                actual,
64            } => write!(
65                f,
66                "frame {index} has {actual} bytes of pixel data, expected {expected}"
67            ),
68            Self::NoFrames => f.write_str("an animation needs at least one frame"),
69        }
70    }
71}
72
73impl std::error::Error for GifError {}
74
75/// Configures and runs GIF encoding.
76///
77/// ```
78/// use pltrs_codec::gif::{GifEncoder, GifFrame};
79/// let black = vec![0, 0, 0, 255].repeat(16);
80/// let white = vec![255; 4 * 16];
81/// let frames = [
82///     GifFrame { pixels: &black, delay: 10 },
83///     GifFrame { pixels: &white, delay: 10 },
84/// ];
85/// let gif = GifEncoder::new().encode(4, 4, &frames)?;
86/// assert!(gif.starts_with(b"GIF89a"));
87/// # Ok::<(), pltrs_codec::gif::GifError>(())
88/// ```
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90pub struct GifEncoder {
91    plays: u16,
92}
93
94impl GifEncoder {
95    /// An encoder looping forever.
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    /// How often the animation plays (0, the default, loops forever).
101    #[must_use]
102    pub fn plays(mut self, plays: u16) -> Self {
103        self.plays = plays;
104        self
105    }
106
107    /// Encodes `width × height` frames into a complete GIF file.
108    ///
109    /// # Errors
110    ///
111    /// When there are no frames, a side is out of GIF's range or a frame
112    /// has the wrong amount of pixel data.
113    pub fn encode(
114        &self,
115        width: u32,
116        height: u32,
117        frames: &[GifFrame<'_>],
118    ) -> Result<Vec<u8>, GifError> {
119        let invalid = GifError::InvalidDimensions { width, height };
120        let side = |n: u32| u16::try_from(n).ok().filter(|&n| n > 0);
121        let (Some(columns), Some(rows)) = (side(width), side(height)) else {
122            return Err(invalid);
123        };
124        let screen = Screen {
125            width: columns,
126            height: rows,
127        };
128        let expected = screen.pixels() * 4;
129        if let Some((index, frame)) = frames
130            .iter()
131            .enumerate()
132            .find(|(_, frame)| frame.pixels.len() != expected)
133        {
134            return Err(GifError::DataLengthMismatch {
135                index,
136                expected,
137                actual: frame.pixels.len(),
138            });
139        }
140        if frames.is_empty() {
141            return Err(GifError::NoFrames);
142        }
143        let pixels: Vec<&[u8]> = frames.iter().map(|frame| frame.pixels).collect();
144        let palette = Palette::for_frames(&pixels);
145        let shown = merge_repeats(frames.iter().map(|frame| Shown {
146            indices: palette.indices(frame.pixels),
147            delay: frame.delay,
148        }));
149        let mut gif = Vec::new();
150        let table_bits = write_header(&mut gif, screen, &palette);
151        if self.plays != 1 {
152            write_looping(&mut gif, self.plays.saturating_sub(1));
153        }
154        let mut previous: Option<&[u8]> = None;
155        for frame in &shown {
156            // Frames with transparent pixels cannot be drawn over the one
157            // before, so each replaces it whole.
158            let changed = match (previous, palette.transparent()) {
159                (Some(previous), None) => changed_area(screen, previous, &frame.indices),
160                _ => Area::whole(screen),
161            };
162            write_frame(&mut gif, screen, frame, changed, &palette, table_bits);
163            previous = Some(&frame.indices);
164        }
165        gif.push(TRAILER);
166        Ok(gif)
167    }
168}
169
170/// Starts an extension block.
171const EXTENSION: u8 = 0x21;
172/// Starts an image.
173const IMAGE: u8 = 0x2C;
174/// Ends the file.
175const TRAILER: u8 = 0x3B;
176
177/// The size of the logical screen.
178#[derive(Clone, Copy, Debug)]
179struct Screen {
180    width: u16,
181    height: u16,
182}
183
184impl Screen {
185    fn pixels(self) -> usize {
186        usize::from(self.width) * usize::from(self.height)
187    }
188}
189
190/// A rectangle of the screen.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192struct Area {
193    left: u16,
194    top: u16,
195    width: u16,
196    height: u16,
197}
198
199impl Area {
200    fn whole(screen: Screen) -> Self {
201        Self {
202            left: 0,
203            top: 0,
204            width: screen.width,
205            height: screen.height,
206        }
207    }
208}
209
210/// A frame as shown: its palette indices and its (merged) delay.
211struct Shown {
212    indices: Vec<u8>,
213    delay: u16,
214}
215
216/// The frames with each run of identical frames merged into one showing
217/// for their summed delay.
218fn merge_repeats(frames: impl Iterator<Item = Shown>) -> Vec<Shown> {
219    let mut shown: Vec<Shown> = Vec::new();
220    for frame in frames {
221        match shown.last_mut() {
222            Some(last) if last.indices == frame.indices => {
223                last.delay = last.delay.saturating_add(frame.delay);
224            }
225            _ => shown.push(frame),
226        }
227    }
228    shown
229}
230
231/// The smallest rectangle holding every pixel that differs between two
232/// frames of different content.
233fn changed_area(screen: Screen, before: &[u8], after: &[u8]) -> Area {
234    let width = usize::from(screen.width);
235    let changed_rows = || {
236        before
237            .chunks_exact(width)
238            .zip(after.chunks_exact(width))
239            .enumerate()
240            .filter(|(_, (a, b))| a != b)
241    };
242    let top = changed_rows().next().map_or(0, |(row, _)| row);
243    let bottom = changed_rows().next_back().map_or(0, |(row, _)| row);
244    let (left, right) = changed_rows().fold((width, 0), |(left, right), (_, (a, b))| {
245        let first = a.iter().zip(b).position(|(x, y)| x != y).unwrap_or(left);
246        let last = a.iter().zip(b).rposition(|(x, y)| x != y).unwrap_or(right);
247        (left.min(first), right.max(last))
248    });
249    let coordinate = |n: usize| u16::try_from(n).expect("inside the screen");
250    Area {
251        left: coordinate(left),
252        top: coordinate(top),
253        width: coordinate(right - left + 1),
254        height: coordinate(bottom - top + 1),
255    }
256}
257
258/// Writes the signature, the screen descriptor and the global colour
259/// table; returns the table's size as a power of two.
260fn write_header(gif: &mut Vec<u8>, screen: Screen, palette: &Palette) -> u8 {
261    let colors = palette.colors();
262    // A table holds 2 to 256 colours, a power of two.
263    let bits = (1..=8).find(|&bits| colors.len() <= 1 << bits).unwrap_or(8);
264    gif.extend_from_slice(b"GIF89a");
265    gif.extend_from_slice(&screen.width.to_le_bytes());
266    gif.extend_from_slice(&screen.height.to_le_bytes());
267    // A global table of 8-bit colours.
268    gif.extend_from_slice(&[0x80 | 0x70 | (bits - 1), 0, 0]);
269    for slot in 0..1_usize << bits {
270        gif.extend_from_slice(&colors.get(slot).copied().unwrap_or_default());
271    }
272    bits
273}
274
275/// Writes the NETSCAPE2.0 extension repeating the animation `repeats`
276/// times after the first play (0 repeats forever).
277fn write_looping(gif: &mut Vec<u8>, repeats: u16) {
278    gif.extend_from_slice(&[EXTENSION, 0xFF, 11]);
279    gif.extend_from_slice(b"NETSCAPE2.0");
280    gif.extend_from_slice(&[3, 1]);
281    gif.extend_from_slice(&repeats.to_le_bytes());
282    gif.push(0);
283}
284
285/// Writes one frame: its graphic control extension, its image descriptor
286/// and the compressed indices of `area`.
287fn write_frame(
288    gif: &mut Vec<u8>,
289    screen: Screen,
290    frame: &Shown,
291    area: Area,
292    palette: &Palette,
293    table_bits: u8,
294) {
295    // Transparent frames are cleared to the background after showing (2);
296    // opaque ones stay for the next to draw over (1).
297    let (disposal, flags, transparent) = match palette.transparent() {
298        Some(index) => (2, 1, index),
299        None => (1, 0, 0),
300    };
301    gif.extend_from_slice(&[EXTENSION, 0xF9, 4, disposal << 2 | flags]);
302    gif.extend_from_slice(&frame.delay.to_le_bytes());
303    gif.extend_from_slice(&[transparent, 0]);
304    gif.push(IMAGE);
305    for value in [area.left, area.top, area.width, area.height] {
306        gif.extend_from_slice(&value.to_le_bytes());
307    }
308    gif.push(0);
309    let width = usize::from(screen.width);
310    let (left, columns) = (usize::from(area.left), usize::from(area.width));
311    let indices: Vec<u8> = frame
312        .indices
313        .chunks_exact(width)
314        .skip(usize::from(area.top))
315        .take(usize::from(area.height))
316        .flat_map(|row| &row[left..left + columns])
317        .copied()
318        .collect();
319    let min_code_size = table_bits.max(2);
320    gif.push(min_code_size);
321    for block in lzw::compress(&indices, min_code_size).chunks(255) {
322        gif.push(u8::try_from(block.len()).expect("blocks hold at most 255 bytes"));
323        gif.extend_from_slice(block);
324    }
325    gif.push(0);
326}
327
328#[cfg(test)]
329mod tests;