forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

mod.rs370 lines, 12.4 KiBHistoryRawDownload
1//! WebP: the RIFF container, its lossy (`VP8 `) and lossless (`VP8L`) payloads,
2//! and the separate alpha plane (`ALPH`) an extended file may carry.
3//!
4//! Animation is refused by name. A still decoder that quietly handed back the
5//! first frame of an animation would make "this file plays" and "this file
6//! decoded" indistinguishable to its caller.
7
8pub mod vp8;
9mod vp8_tables;
10pub mod vp8l;
11
12use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels};
13use ec_core::{Error, Result};
14
15/// One RIFF chunk.
16struct Chunk<'a> {
17 tag: [u8; 4],
18 data: &'a [u8],
19}
20
21/// Walk the chunks inside a `WEBP` RIFF file.
22fn chunks(data: &[u8]) -> Result<Vec<Chunk<'_>>> {
23 let riff_size = data
24 .get(4..8)
25 .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
26 .ok_or_else(|| Error::corrupt("WebP: truncated RIFF header"))?;
27 // The declared size may exceed what is present in a truncated file; take
28 // whichever ends sooner rather than trusting the header.
29 let end = (riff_size + 8).min(data.len());
30 let mut out = Vec::new();
31 let mut at = 12usize;
32 while at + 8 <= end {
33 let tag = [data[at], data[at + 1], data[at + 2], data[at + 3]];
34 let size =
35 u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]) as usize;
36 let body = data
37 .get(at + 8..at + 8 + size)
38 .ok_or_else(|| Error::corrupt("WebP: chunk runs past the file"))?;
39 out.push(Chunk { tag, data: body });
40 // Chunks are padded to an even length.
41 at += 8 + size + (size & 1);
42 }
43 if out.is_empty() {
44 return Err(Error::corrupt("WebP: no chunks"));
45 }
46 Ok(out)
47}
48
49/// Dimensions from the container's headers alone.
50pub fn info(data: &[u8]) -> Result<Info> {
51 let chunks = chunks(data)?;
52 for chunk in &chunks {
53 match &chunk.tag {
54 b"VP8X" if chunk.data.len() >= 10 => {
55 let d = chunk.data;
56 let width = 1 + (u32::from(d[4]) | u32::from(d[5]) << 8 | u32::from(d[6]) << 16);
57 let height = 1 + (u32::from(d[7]) | u32::from(d[8]) << 8 | u32::from(d[9]) << 16);
58 return Ok(Info {
59 format: ImageFormat::WebP,
60 width,
61 height,
62 });
63 }
64 b"VP8 " => {
65 let (width, height) = vp8::dimensions(chunk.data)?;
66 return Ok(Info {
67 format: ImageFormat::WebP,
68 width,
69 height,
70 });
71 }
72 b"VP8L" => {
73 let d = chunk.data;
74 if d.len() < 5 || d[0] != 0x2f {
75 return Err(Error::corrupt("WebP: short VP8L header"));
76 }
77 let packed = u32::from_le_bytes([d[1], d[2], d[3], d[4]]);
78 return Ok(Info {
79 format: ImageFormat::WebP,
80 width: (packed & 0x3fff) + 1,
81 height: ((packed >> 14) & 0x3fff) + 1,
82 });
83 }
84 _ => {}
85 }
86 }
87 Err(Error::corrupt("WebP: no image chunk"))
88}
89
90/// Decode a WebP file.
91pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
92 let chunks = chunks(data)?;
93 let mut meta = Metadata::default();
94 let mut alpha: Option<&[u8]> = None;
95 let mut image: Option<(&[u8; 4], &[u8])> = None;
96
97 for chunk in &chunks {
98 match &chunk.tag {
99 b"VP8X" => {
100 let flags = chunk
101 .data
102 .first()
103 .copied()
104 .ok_or_else(|| Error::corrupt("WebP: empty VP8X"))?;
105 if flags & 0x02 != 0 {
106 return Err(Error::unsupported(
107 "animated WebP",
108 "this decoder returns one still picture, not a sequence of frames",
109 ));
110 }
111 }
112 b"ANIM" | b"ANMF" => {
113 return Err(Error::unsupported(
114 "animated WebP",
115 "this decoder returns one still picture, not a sequence of frames",
116 ));
117 }
118 b"ALPH" => alpha = Some(chunk.data),
119 b"VP8 " | b"VP8L" => {
120 if image.is_none() {
121 image = Some((&chunk.tag, chunk.data));
122 }
123 }
124 b"EXIF" => {
125 if let Some(o) = exif_orientation(chunk.data) {
126 meta.orientation = Some(o);
127 }
128 }
129 _ => {}
130 }
131 }
132
133 let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?;
134 if tag == b"VP8L" {
135 let argb = vp8l::decode(body, limits)?;
136 let mut rgba = Vec::with_capacity(argb.pixels.len() * 4);
137 for p in &argb.pixels {
138 rgba.extend_from_slice(&[
139 ((p >> 16) & 0xff) as u8,
140 ((p >> 8) & 0xff) as u8,
141 (p & 0xff) as u8,
142 ((p >> 24) & 0xff) as u8,
143 ]);
144 }
145 return Ok(Image {
146 width: argb.width,
147 height: argb.height,
148 pixels: Pixels::Rgba8(rgba),
149 meta,
150 });
151 }
152
153 let frame = vp8::decode(body, limits)?;
154 let (w, h) = (frame.width as usize, frame.height as usize);
155 // Chroma is stored at half resolution and upsampled with the same triangle
156 // filter libwebp uses; nearest-neighbour here costs about a decibel.
157 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
158 let crop = |plane: &[u8]| -> Vec<u8> {
159 (0..ch)
160 .flat_map(|y| plane[y * frame.stride_uv..y * frame.stride_uv + cw].to_vec())
161 .collect()
162 };
163 let u_plane = crate::upsample::upsample(&crop(&frame.u), cw, ch, w, h);
164 let v_plane = crate::upsample::upsample(&crop(&frame.v), cw, ch, w, h);
165 let alpha_plane = match alpha {
166 Some(chunk) => Some(decode_alpha(chunk, frame.width, frame.height)?),
167 None => None,
168 };
169 let channels = if alpha_plane.is_some() { 4 } else { 3 };
170 let mut out = vec![0u8; w * h * channels];
171 for y in 0..h {
172 for x in 0..w {
173 let luma = frame.y[y * frame.stride_y + x];
174 let cb = u_plane[y * w + x];
175 let cr = v_plane[y * w + x];
176 let rgb = yuv_to_rgb(luma, cb, cr);
177 let at = (y * w + x) * channels;
178 out[at..at + 3].copy_from_slice(&rgb);
179 if let Some(plane) = &alpha_plane {
180 out[at + 3] = plane[y * w + x];
181 }
182 }
183 }
184 Ok(Image {
185 width: frame.width,
186 height: frame.height,
187 pixels: if channels == 4 {
188 Pixels::Rgba8(out)
189 } else {
190 Pixels::Rgb8(out)
191 },
192 meta,
193 })
194}
195
196/// BT.601 studio-swing YCbCr to RGB, in 16-bit fixed point.
197fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] {
198 let y = (i32::from(y) - 16) * 76284;
199 let u = i32::from(u) - 128;
200 let v = i32::from(v) - 128;
201 let r = y + 104595 * v;
202 let g = y - 25624 * u - 53281 * v;
203 let b = y + 132251 * u;
204 [
205 ((r + 32768) >> 16).clamp(0, 255) as u8,
206 ((g + 32768) >> 16).clamp(0, 255) as u8,
207 ((b + 32768) >> 16).clamp(0, 255) as u8,
208 ]
209}
210
211/// Decode an `ALPH` chunk into one byte of alpha per pixel.
212fn decode_alpha(chunk: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
213 let head = *chunk
214 .first()
215 .ok_or_else(|| Error::corrupt("WebP: empty ALPH chunk"))?;
216 let method = head & 0x03;
217 let filter = (head >> 2) & 0x03;
218 let body = &chunk[1..];
219 let count = (width as usize) * (height as usize);
220 let mut plane = match method {
221 0 => {
222 if body.len() < count {
223 return Err(Error::corrupt("WebP: ALPH shorter than the picture"));
224 }
225 body[..count].to_vec()
226 }
227 1 => {
228 // Lossless-coded, dimensions implied; the alpha lives in green.
229 let argb = vp8l::decode_implicit(body, width, height)?;
230 argb.iter().map(|p| ((p >> 8) & 0xff) as u8).collect()
231 }
232 other => {
233 return Err(Error::corrupt(format!(
234 "WebP: ALPH compression method {other}"
235 )));
236 }
237 };
238 unfilter_alpha(&mut plane, width as usize, height as usize, filter);
239 Ok(plane)
240}
241
242/// Undo the alpha plane's spatial filter (none / horizontal / vertical /
243/// gradient), in place.
244fn unfilter_alpha(plane: &mut [u8], width: usize, height: usize, filter: u8) {
245 if filter == 0 {
246 return;
247 }
248 for y in 0..height {
249 for x in 0..width {
250 let index = y * width + x;
251 let left = if x > 0 { plane[index - 1] } else { 0 };
252 let above = if y > 0 { plane[index - width] } else { 0 };
253 let above_left = if x > 0 && y > 0 {
254 plane[index - width - 1]
255 } else {
256 0
257 };
258 let predictor = if x == 0 && y == 0 {
259 0
260 } else if y == 0 {
261 // The top row has no pixel above, so it predicts from the left
262 // whatever the filter says, and the left column from above.
263 left
264 } else if x == 0 {
265 above
266 } else {
267 match filter {
268 1 => left,
269 2 => above,
270 _ => (i32::from(left) + i32::from(above) - i32::from(above_left)).clamp(0, 255)
271 as u8,
272 }
273 };
274 plane[index] = predictor.wrapping_add(plane[index]);
275 }
276 }
277}
278
279/// EXIF orientation out of a bare TIFF block (no `Exif\0\0` prefix here).
280fn exif_orientation(data: &[u8]) -> Option<u8> {
281 let little = match data.get(..2)? {
282 b"II" => true,
283 b"MM" => false,
284 _ => return None,
285 };
286 let u16_at = |at: usize| -> Option<u16> {
287 let b = data.get(at..at + 2)?;
288 Some(if little {
289 u16::from_le_bytes([b[0], b[1]])
290 } else {
291 u16::from_be_bytes([b[0], b[1]])
292 })
293 };
294 let u32_at = |at: usize| -> Option<u32> {
295 let b = data.get(at..at + 4)?;
296 Some(if little {
297 u32::from_le_bytes([b[0], b[1], b[2], b[3]])
298 } else {
299 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
300 })
301 };
302 if u16_at(2)? != 42 {
303 return None;
304 }
305 let ifd = u32_at(4)? as usize;
306 let count = usize::from(u16_at(ifd)?);
307 for i in 0..count {
308 let entry = ifd + 2 + i * 12;
309 if u16_at(entry)? == 0x0112 {
310 let value = u16_at(entry + 8)?;
311 return (1..=8).contains(&value).then_some(value as u8);
312 }
313 }
314 None
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 fn riff(chunks: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> {
322 let mut body = b"WEBP".to_vec();
323 for (tag, data) in chunks {
324 body.extend_from_slice(*tag);
325 body.extend_from_slice(&(data.len() as u32).to_le_bytes());
326 body.extend_from_slice(data);
327 if data.len() % 2 == 1 {
328 body.push(0);
329 }
330 }
331 let mut out = b"RIFF".to_vec();
332 out.extend_from_slice(&(body.len() as u32).to_le_bytes());
333 out.extend_from_slice(&body);
334 out
335 }
336
337 #[test]
338 fn odd_sized_chunks_are_padded_and_still_walked() {
339 let file = riff(&[(b"XXXX", vec![1, 2, 3]), (b"VP8L", vec![0x2f, 0, 0, 0, 0])]);
340 let found = chunks(&file).unwrap();
341 assert_eq!(found.len(), 2);
342 assert_eq!(&found[1].tag, b"VP8L");
343 assert_eq!(found[1].data.len(), 5);
344 }
345
346 #[test]
347 fn animation_is_refused_by_name() {
348 let mut vp8x = vec![0x02, 0, 0, 0];
349 vp8x.extend_from_slice(&[15, 0, 0, 15, 0, 0]);
350 let file = riff(&[(b"VP8X", vp8x), (b"ANMF", vec![0; 16])]);
351 let err = decode(&file, Limits::default()).unwrap_err();
352 assert!(format!("{err}").contains("animated"), "{err}");
353 }
354
355 #[test]
356 fn yuv_conversion_puts_studio_black_and_white_at_the_ends() {
357 assert_eq!(yuv_to_rgb(16, 128, 128), [0, 0, 0]);
358 assert_eq!(yuv_to_rgb(235, 128, 128), [255, 255, 255]);
359 let grey = yuv_to_rgb(126, 128, 128);
360 assert!(grey[0] == grey[1] && grey[1] == grey[2], "{grey:?}");
361 }
362
363 #[test]
364 fn the_alpha_gradient_filter_inverts_its_prediction() {
365 // Horizontal filter: each stored byte is a difference from the left.
366 let mut plane = vec![10u8, 5, 250, 1];
367 unfilter_alpha(&mut plane, 4, 1, 1);
368 assert_eq!(plane, vec![10, 15, 9, 10]);
369 }
370}