Skip to main content

pltrs_codec/png/
animated.rs

1//! Animated PNG (APNG) encoding: a sequence of full frames with display
2//! durations, readable as a still PNG of the first frame by decoders
3//! without APNG support.
4
5use super::chunk::{ChunkType, SIGNATURE, write_chunk};
6use super::encoder::{chunks, compress_image};
7use super::error::EncodeError;
8use super::filter::FilterStrategy;
9use super::header::Header;
10use super::image::ImageRef;
11use crate::CompressionLevel;
12use crate::deflate::Strategy;
13
14const ACTL: ChunkType = ChunkType(*b"acTL");
15const FCTL: ChunkType = ChunkType(*b"fcTL");
16const FDAT: ChunkType = ChunkType(*b"fdAT");
17
18/// One frame of an animation: the image and how long it is shown, as a
19/// fraction of a second (`delay.0 / delay.1`).
20#[derive(Clone, Copy, Debug)]
21pub struct Frame<'a> {
22    /// The frame's pixels; every frame has the size and format of the
23    /// first.
24    pub image: ImageRef<'a>,
25    /// Numerator and denominator of the display time in seconds.
26    pub delay: (u16, u16),
27}
28
29/// Configures and runs APNG encoding.
30///
31/// ```
32/// use pltrs_codec::png::{AnimatedEncoder, Frame, ImageRef};
33/// let black = vec![0u8; 4 * 4 * 4];
34/// let white = vec![255u8; 4 * 4 * 4];
35/// let frames = [
36///     Frame { image: ImageRef::rgba8(4, 4, &black)?, delay: (1, 10) },
37///     Frame { image: ImageRef::rgba8(4, 4, &white)?, delay: (1, 10) },
38/// ];
39/// let apng = AnimatedEncoder::new().encode(&frames)?;
40/// assert!(apng.windows(4).any(|w| w == b"acTL"));
41/// # Ok::<(), pltrs_codec::png::EncodeError>(())
42/// ```
43#[derive(Clone, Debug, PartialEq)]
44pub struct AnimatedEncoder {
45    level: CompressionLevel,
46    strategy: Strategy,
47    filter: FilterStrategy,
48    plays: u32,
49}
50
51impl Default for AnimatedEncoder {
52    fn default() -> Self {
53        Self {
54            level: CompressionLevel::DEFAULT,
55            strategy: Strategy::Filtered,
56            filter: FilterStrategy::Adaptive,
57            plays: 0,
58        }
59    }
60}
61
62impl AnimatedEncoder {
63    /// An encoder looping forever with default compression.
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// How often the animation plays (0, the default, loops forever).
69    #[must_use]
70    pub fn plays(mut self, plays: u32) -> Self {
71        self.plays = plays;
72        self
73    }
74
75    /// Sets the zlib compression level.
76    #[must_use]
77    pub fn compression(mut self, level: CompressionLevel) -> Self {
78        self.level = level;
79        self
80    }
81
82    /// Sets the zlib strategy ([`Strategy::Filtered`] by default).
83    #[must_use]
84    pub fn strategy(mut self, strategy: Strategy) -> Self {
85        self.strategy = strategy;
86        self
87    }
88
89    /// Encodes the frames into a complete APNG file.
90    ///
91    /// # Errors
92    ///
93    /// When there are no frames, a frame differs in size or format from
94    /// the first, or there are more than `u32::MAX` frames.
95    pub fn encode(&self, frames: &[Frame<'_>]) -> Result<Vec<u8>, EncodeError> {
96        let first = frames.first().ok_or(EncodeError::NoFrames)?.image;
97        if let Some(index) = frames.iter().position(|frame| {
98            frame.image.width() != first.width()
99                || frame.image.height() != first.height()
100                || frame.image.format() != first.format()
101        }) {
102            return Err(EncodeError::FrameMismatch { index });
103        }
104        let count = u32::try_from(frames.len()).map_err(|_| EncodeError::ImageTooLarge)?;
105        let mut png = Vec::new();
106        png.extend_from_slice(&SIGNATURE);
107        let header = Header {
108            width: first.width(),
109            height: first.height(),
110            format: first.format(),
111            interlaced: false,
112        };
113        write_chunk(&mut png, ChunkType::IHDR, &header.to_bytes());
114        let mut control = Vec::with_capacity(8);
115        control.extend_from_slice(&count.to_be_bytes());
116        control.extend_from_slice(&self.plays.to_be_bytes());
117        write_chunk(&mut png, ACTL, &control);
118        let mut sequence = 0_u32;
119        let mut next = || {
120            let number = sequence;
121            sequence += 1;
122            number
123        };
124        for (index, frame) in frames.iter().enumerate() {
125            write_chunk(&mut png, FCTL, &frame_control(next(), frame));
126            let data = compress_image(&frame.image, self.filter, self.level, self.strategy)?;
127            // A chunk per output buffer, as Pillow writes them.
128            for part in chunks(&data) {
129                if index == 0 {
130                    write_chunk(&mut png, ChunkType::IDAT, part);
131                } else {
132                    let mut chunk = next().to_be_bytes().to_vec();
133                    chunk.extend_from_slice(part);
134                    write_chunk(&mut png, FDAT, &chunk);
135                }
136            }
137        }
138        write_chunk(&mut png, ChunkType::IEND, &[]);
139        Ok(png)
140    }
141}
142
143/// The `fcTL` chunk of a full frame: no offset, no disposal, replacing
144/// the previous frame.
145fn frame_control(sequence: u32, frame: &Frame<'_>) -> Vec<u8> {
146    let mut data = Vec::with_capacity(26);
147    data.extend_from_slice(&sequence.to_be_bytes());
148    data.extend_from_slice(&frame.image.width().to_be_bytes());
149    data.extend_from_slice(&frame.image.height().to_be_bytes());
150    data.extend_from_slice(&0_u32.to_be_bytes());
151    data.extend_from_slice(&0_u32.to_be_bytes());
152    data.extend_from_slice(&frame.delay.0.to_be_bytes());
153    data.extend_from_slice(&frame.delay.1.to_be_bytes());
154    data.extend_from_slice(&[0, 0]);
155    data
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::png::decode;
162
163    #[test]
164    fn first_frame_decodes_as_a_still_image() {
165        let red = [255u8, 0, 0, 255].repeat(6);
166        let blue = [0u8, 0, 255, 255].repeat(6);
167        let frames = [
168            Frame {
169                image: ImageRef::rgba8(3, 2, &red).unwrap(),
170                delay: (1, 2),
171            },
172            Frame {
173                image: ImageRef::rgba8(3, 2, &blue).unwrap(),
174                delay: (1, 2),
175            },
176        ];
177        let apng = AnimatedEncoder::new().plays(1).encode(&frames).unwrap();
178        let still = decode(&apng).unwrap();
179        assert_eq!(still.to_rgba8(), red);
180        let fdat = apng.windows(4).filter(|w| *w == b"fdAT").count();
181        assert_eq!(fdat, 1);
182    }
183
184    #[test]
185    fn frames_must_match() {
186        assert_eq!(
187            AnimatedEncoder::new().encode(&[]),
188            Err(EncodeError::NoFrames)
189        );
190        let small = vec![0u8; 4];
191        let large = vec![0u8; 16];
192        let frames = [
193            Frame {
194                image: ImageRef::rgba8(1, 1, &small).unwrap(),
195                delay: (1, 1),
196            },
197            Frame {
198                image: ImageRef::rgba8(2, 2, &large).unwrap(),
199                delay: (1, 1),
200            },
201        ];
202        assert_eq!(
203            AnimatedEncoder::new().encode(&frames),
204            Err(EncodeError::FrameMismatch { index: 1 })
205        );
206    }
207}