1mod 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
33pub 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
63const MAX_SIDE: u32 = 1 << 14;
65
66pub 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#[derive(Clone, Copy, Debug)]
81pub struct AnimationFrame<'a> {
82 pub pixels: &'a [u8],
84 pub duration_ms: u32,
86}
87
88pub 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
123fn 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
132fn 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
158fn 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
167fn 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}