Skip to main content

pltrs_codec/webp/
mod.rs

1//! WebP files.
2//!
3//! * [`decode`] reads a file as Pillow opens it (through libwebp's
4//!   `WebPAnimDecoder`): the first frame on its canvas, which is RGB, or
5//!   RGBA when the file declares alpha. Lossless (VP8L) bitstreams decode
6//!   exactly; lossy (VP8) ones, with their `ALPH` alpha planes, decode to
7//!   the pixels libwebp 1.6 produces, its arithmetic and "fancy" chroma
8//!   upsampling included.
9//! * [`encode_rgba8`] writes a lossless (VP8L) file: a palette for images
10//!   of at most 256 colours, otherwise prediction, then LZ77 with a colour
11//!   cache and Huffman codes. Decoding it gives back the exact pixels.
12//!   [`encode_animation_rgba8`] writes an animation of such frames.
13//!
14//! ```
15//! use pltrs_codec::webp;
16//! let pixels = [255, 0, 0, 255, 0, 0, 255, 128];
17//! let file = webp::encode_rgba8(2, 1, &pixels)?;
18//! assert_eq!(webp::decode(&file)?.to_rgba8().concat(), pixels);
19//! # Ok::<(), Box<dyn std::error::Error>>(())
20//! ```
21
22mod alpha;
23mod container;
24mod error;
25mod lossless;
26mod lossy;
27
28pub use error::{DecodeError, EncodeError};
29
30use self::container::{Bitstream, Frame};
31use crate::raster::{MAX_PIXELS, Pixels, Raster};
32
33/// Decodes the first frame of a WebP file as Pillow does.
34///
35/// # Errors
36///
37/// When the data is not a WebP file, is truncated or malformed, or holds
38/// an image larger than Pillow accepts.
39pub fn decode(data: &[u8]) -> Result<Raster, DecodeError> {
40    let file = container::parse(data)?;
41    let (width, height) = (file.width, file.height);
42    check_size(width, height)?;
43    let frame = decode_frame(&file.frame)?;
44    let canvas = if (file.frame.width, file.frame.height) == (width, height) {
45        frame
46    } else {
47        let mut canvas = vec![[0u8; 4]; width as usize * height as usize];
48        let frame_width = file.frame.width as usize;
49        for (row, pixels) in frame.chunks_exact(frame_width).enumerate() {
50            let start = (file.frame.y as usize + row) * width as usize + file.frame.x as usize;
51            canvas[start..start + frame_width].copy_from_slice(pixels);
52        }
53        canvas
54    };
55    let pixels = if file.has_alpha {
56        Pixels::Rgba(canvas)
57    } else {
58        Pixels::Rgb(canvas.into_iter().map(|[r, g, b, _]| [r, g, b]).collect())
59    };
60    Ok(Raster::new(width, height, pixels))
61}
62
63/// The largest side of a WebP image.
64const MAX_SIDE: u32 = 1 << 14;
65
66/// Encodes `width × height` straight RGBA pixels (row by row) as a
67/// lossless WebP file.
68///
69/// # Errors
70///
71/// When a side is zero or larger than 16 384 pixels, or `pixels` does not
72/// hold `width × height × 4` bytes.
73pub fn encode_rgba8(width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>, EncodeError> {
74    check_dimensions(width, height)?;
75    let (bitstream, _) = lossless_bitstream(width, height, pixels)?;
76    Ok(container::write(*b"VP8L", &bitstream))
77}
78
79/// One frame of an animation.
80#[derive(Clone, Copy, Debug)]
81pub struct AnimationFrame<'a> {
82    /// `width × height × 4` bytes of straight RGBA, row by row.
83    pub pixels: &'a [u8],
84    /// How long the frame shows, in milliseconds (at most 16 777 215).
85    pub duration_ms: u32,
86}
87
88/// Encodes `frames` of `width × height` pixels as a lossless animated WebP
89/// that plays `loops` times (0: forever). Each frame replaces the whole
90/// canvas.
91///
92/// # Errors
93///
94/// When there are no frames, a side is zero or larger than 16 384
95/// pixels, or a frame does not hold `width × height × 4` bytes.
96pub fn encode_animation_rgba8(
97    width: u32,
98    height: u32,
99    frames: &[AnimationFrame<'_>],
100    loops: u16,
101) -> Result<Vec<u8>, EncodeError> {
102    check_dimensions(width, height)?;
103    if frames.is_empty() {
104        return Err(EncodeError::NoFrames);
105    }
106    let coded = frames
107        .iter()
108        .map(|frame| {
109            let (bitstream, alpha) = lossless_bitstream(width, height, frame.pixels)?;
110            Ok((bitstream, alpha, frame.duration_ms))
111        })
112        .collect::<Result<Vec<_>, EncodeError>>()?;
113    let uses_alpha = coded.iter().any(|&(_, alpha, _)| alpha);
114    let frames: Vec<(Vec<u8>, u32)> = coded
115        .into_iter()
116        .map(|(bitstream, _, duration)| (bitstream, duration))
117        .collect();
118    Ok(container::write_animation(
119        width, height, uses_alpha, loops, &frames,
120    ))
121}
122
123/// Rejects sizes WebP cannot hold.
124fn check_dimensions(width: u32, height: u32) -> Result<(), EncodeError> {
125    if (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height) {
126        Ok(())
127    } else {
128        Err(EncodeError::InvalidDimensions { width, height })
129    }
130}
131
132/// The VP8L bitstream of RGBA `pixels`, and whether they use alpha.
133fn lossless_bitstream(
134    width: u32,
135    height: u32,
136    pixels: &[u8],
137) -> Result<(Vec<u8>, bool), EncodeError> {
138    let expected = width as usize * height as usize * 4;
139    if pixels.len() != expected {
140        return Err(EncodeError::DataLengthMismatch {
141            expected,
142            actual: pixels.len(),
143        });
144    }
145    let argb: Vec<u32> = pixels
146        .as_chunks::<4>()
147        .0
148        .iter()
149        .map(|&[r, g, b, a]| u32::from_be_bytes([a, r, g, b]))
150        .collect();
151    let uses_alpha = argb.iter().any(|&pixel| pixel >> 24 != 0xFF);
152    Ok((
153        lossless::encode(&argb, width as usize, uses_alpha),
154        uses_alpha,
155    ))
156}
157
158/// Rejects images larger than Pillow decodes.
159fn check_size(width: u32, height: u32) -> Result<(), DecodeError> {
160    if u64::from(width) * u64::from(height) > MAX_PIXELS {
161        Err(DecodeError::TooLarge { width, height })
162    } else {
163        Ok(())
164    }
165}
166
167/// The RGBA pixels of a frame.
168fn decode_frame(frame: &Frame<'_>) -> Result<Vec<[u8; 4]>, DecodeError> {
169    match frame.bitstream {
170        Bitstream::Lossless(data) => Ok(lossless::decode(data)?
171            .into_iter()
172            .map(|argb| {
173                let [a, r, g, b] = argb.to_be_bytes();
174                [r, g, b, a]
175            })
176            .collect()),
177        Bitstream::Lossy { vp8, alpha } => {
178            check_size(frame.width, frame.height)?;
179            let rgb = lossy::decode(vp8)?;
180            let alpha = alpha
181                .map(|data| alpha::decode(data, frame.width, frame.height))
182                .transpose()?;
183            Ok(match alpha {
184                Some(levels) => rgb
185                    .into_iter()
186                    .zip(levels)
187                    .map(|([r, g, b], a)| [r, g, b, a])
188                    .collect(),
189                None => rgb.into_iter().map(|[r, g, b]| [r, g, b, 255]).collect(),
190            })
191        }
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn encoded_files_decode_to_their_pixels() {
201        let pixels: Vec<u8> = (0..30u8).flat_map(|i| [i * 8, 255 - i, i, 255]).collect();
202        let file = encode_rgba8(6, 5, &pixels).unwrap();
203        let raster = decode(&file).unwrap();
204        assert!(
205            matches!(raster.pixels(), Pixels::Rgb(_)),
206            "opaque files open as RGB"
207        );
208        assert_eq!(raster.to_rgba8().concat(), pixels);
209        assert_eq!(
210            encode_rgba8(0, 5, &[]),
211            Err(EncodeError::InvalidDimensions {
212                width: 0,
213                height: 5
214            })
215        );
216        assert_eq!(
217            encode_rgba8(2, 2, &[0; 15]),
218            Err(EncodeError::DataLengthMismatch {
219                expected: 16,
220                actual: 15
221            })
222        );
223    }
224
225    #[test]
226    fn animations_open_on_their_first_frame() {
227        let first = [10u8, 20, 30, 128].repeat(12);
228        let second = [200u8, 0, 0, 255].repeat(12);
229        let frames = [
230            AnimationFrame {
231                pixels: &first,
232                duration_ms: 40,
233            },
234            AnimationFrame {
235                pixels: &second,
236                duration_ms: 40,
237            },
238        ];
239        let file = encode_animation_rgba8(4, 3, &frames, 0).unwrap();
240        let raster = decode(&file).unwrap();
241        assert_eq!(raster.pixels(), &Pixels::Rgba(vec![[10, 20, 30, 128]; 12]));
242        assert_eq!(
243            encode_animation_rgba8(4, 3, &[], 0),
244            Err(EncodeError::NoFrames)
245        );
246    }
247}