Skip to main content

threers_codec/
apng.rs

1//! APNG (Animated PNG) encoder — a universally web-supported **transparent**
2//! animation format (pure Rust, wasm-safe).
3//!
4//! APNG is the pragmatic cross-browser answer for transparent motion: every
5//! major browser (Chrome, Firefox, Safari, Edge) renders it in an `<img>`, with
6//! a full 8-bit alpha channel. For smaller files or video containers see the
7//! sibling [`crate::gif`], [`crate::vp9`] / [`crate::webm`],
8//! and [`crate::hevc`] modules.
9//!
10//! This writes truecolor-with-alpha (`color_type = 6`) frames. The DEFLATE stage
11//! currently uses *stored* (uncompressed) blocks — valid and decodable
12//! everywhere; real DEFLATE compression is a follow-up (the file is correct
13//! either way, just larger).
14
15/// CRC-32 (ISO 3309 / PNG) over a byte slice.
16fn crc32(bytes: &[u8]) -> u32 {
17    let mut crc = 0xFFFF_FFFFu32;
18    for &b in bytes {
19        crc ^= b as u32;
20        for _ in 0..8 {
21            let mask = (crc & 1).wrapping_neg();
22            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
23        }
24    }
25    !crc
26}
27
28/// Adler-32 (zlib) over a byte slice.
29fn adler32(bytes: &[u8]) -> u32 {
30    let (mut a, mut b) = (1u32, 0u32);
31    for &x in bytes {
32        a = (a + x as u32) % 65521;
33        b = (b + a) % 65521;
34    }
35    (b << 16) | a
36}
37
38/// Wrap `data` in a zlib stream using DEFLATE *stored* (uncompressed) blocks.
39fn zlib_stored(data: &[u8]) -> Vec<u8> {
40    let mut out = vec![0x78, 0x01]; // zlib header: CM=8, CINFO=7, FLEVEL fastest
41    if data.is_empty() {
42        out.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF]); // final empty block
43    } else {
44        let mut i = 0;
45        while i < data.len() {
46            let len = (data.len() - i).min(0xFFFF);
47            let is_final = (i + len >= data.len()) as u8;
48            out.push(is_final); // BFINAL | BTYPE(00 = stored)
49            out.push((len & 0xFF) as u8);
50            out.push((len >> 8) as u8);
51            let nlen = !(len as u16);
52            out.push((nlen & 0xFF) as u8);
53            out.push((nlen >> 8) as u8);
54            out.extend_from_slice(&data[i..i + len]);
55            i += len;
56        }
57    }
58    out.extend_from_slice(&adler32(data).to_be_bytes());
59    out
60}
61
62/// Append a PNG chunk (`length | type | data | crc`) to `out`.
63fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
64    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
65    let start = out.len();
66    out.extend_from_slice(kind);
67    out.extend_from_slice(data);
68    let crc = crc32(&out[start..]);
69    out.extend_from_slice(&crc.to_be_bytes());
70}
71
72/// Filter+pack RGBA scanlines (filter type 0 = none) then zlib-compress.
73fn frame_zlib(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
74    let stride = (width * 4) as usize;
75    let mut raw = Vec::with_capacity((stride + 1) * height as usize);
76    for row in 0..height as usize {
77        raw.push(0); // filter type: none
78        raw.extend_from_slice(&rgba[row * stride..(row + 1) * stride]);
79    }
80    zlib_stored(&raw)
81}
82
83/// Builds an APNG from RGBA frames.
84pub struct ApngEncoder {
85    width: u32,
86    height: u32,
87    /// Loop count (`0` = infinite).
88    plays: u32,
89    frames: Vec<(Vec<u8>, u16, u16)>, // (rgba, delay_num, delay_den)
90}
91
92impl ApngEncoder {
93    /// New encoder for `width × height` frames looping `plays` times (`0` = forever).
94    pub fn new(width: u32, height: u32, plays: u32) -> Self {
95        Self {
96            width,
97            height,
98            plays,
99            frames: Vec::new(),
100        }
101    }
102
103    /// Add a frame: tightly-packed RGBA8 (`width × height × 4`), shown for
104    /// `delay_num / delay_den` seconds.
105    pub fn add_frame(&mut self, rgba: &[u8], delay_num: u16, delay_den: u16) {
106        assert_eq!(
107            rgba.len(),
108            (self.width * self.height * 4) as usize,
109            "rgba size"
110        );
111        self.frames.push((rgba.to_vec(), delay_num, delay_den));
112    }
113
114    /// Serialize the APNG byte stream.
115    pub fn finish(&self) -> Vec<u8> {
116        let mut out = Vec::new();
117        out.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]); // signature
118
119        // IHDR: 8-bit truecolor + alpha (color type 6).
120        let mut ihdr = Vec::new();
121        ihdr.extend_from_slice(&self.width.to_be_bytes());
122        ihdr.extend_from_slice(&self.height.to_be_bytes());
123        ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // bit depth, color type, compression, filter, interlace
124        chunk(&mut out, b"IHDR", &ihdr);
125
126        // acTL: animation control.
127        let mut actl = Vec::new();
128        actl.extend_from_slice(&(self.frames.len() as u32).to_be_bytes());
129        actl.extend_from_slice(&self.plays.to_be_bytes());
130        chunk(&mut out, b"acTL", &actl);
131
132        let mut seq: u32 = 0;
133        for (i, (rgba, dnum, dden)) in self.frames.iter().enumerate() {
134            // fcTL for every frame.
135            let mut fctl = Vec::new();
136            fctl.extend_from_slice(&seq.to_be_bytes());
137            seq += 1;
138            fctl.extend_from_slice(&self.width.to_be_bytes());
139            fctl.extend_from_slice(&self.height.to_be_bytes());
140            fctl.extend_from_slice(&0u32.to_be_bytes()); // x_offset
141            fctl.extend_from_slice(&0u32.to_be_bytes()); // y_offset
142            fctl.extend_from_slice(&dnum.to_be_bytes());
143            fctl.extend_from_slice(&dden.to_be_bytes());
144            fctl.push(0); // dispose_op = NONE
145            fctl.push(0); // blend_op = SOURCE (overwrite, incl. alpha)
146            chunk(&mut out, b"fcTL", &fctl);
147
148            let zdata = frame_zlib(self.width, self.height, rgba);
149            if i == 0 {
150                chunk(&mut out, b"IDAT", &zdata);
151            } else {
152                // fdAT: sequence number + frame data.
153                let mut fdat = Vec::with_capacity(4 + zdata.len());
154                fdat.extend_from_slice(&seq.to_be_bytes());
155                seq += 1;
156                fdat.extend_from_slice(&zdata);
157                chunk(&mut out, b"fdAT", &fdat);
158            }
159        }
160        chunk(&mut out, b"IEND", &[]);
161        out
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn crc_and_adler_known_values() {
171        // CRC32 of "IEND" (the empty-IEND chunk's crc is a PNG constant).
172        assert_eq!(crc32(b"IEND"), 0xAE42_6082);
173        assert_eq!(adler32(b""), 1);
174    }
175
176    #[test]
177    fn apng_structure() {
178        let (w, h) = (4u32, 4u32);
179        let mut enc = ApngEncoder::new(w, h, 0);
180        let f0 = vec![255u8; (w * h * 4) as usize];
181        let mut f1 = vec![0u8; (w * h * 4) as usize];
182        for p in f1.chunks_mut(4) {
183            p[3] = 128; // semi-transparent
184        }
185        enc.add_frame(&f0, 1, 10);
186        enc.add_frame(&f1, 1, 10);
187        let png = enc.finish();
188
189        assert_eq!(&png[1..4], b"PNG");
190        for tag in [b"IHDR", b"acTL", b"fcTL", b"IDAT", b"fdAT", b"IEND"] {
191            assert!(
192                png.windows(4).any(|w| w == tag),
193                "missing chunk {:?}",
194                std::str::from_utf8(tag)
195            );
196        }
197    }
198}