forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs514 lines, 19.3 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//! `decode` returns one still picture and refuses an animation by name: a still
5//! decoder that quietly handed back the first frame would make "this file
6//! plays" and "this file decoded" indistinguishable to its caller. The
7//! sequence is `decode_frames`, which composites the `ANMF` frames onto the
8//! canvas.
9
10pub mod vp8;
11mod vp8_tables;
12pub mod vp8l;
13
14use crate::{exif, Image, ImageFormat, Info, Limits, Metadata, Pixels};
15use ec_core::{Error, Result};
16
17/// One RIFF chunk.
18struct Chunk<'a> {
19 tag: [u8; 4],
20 data: &'a [u8],
21}
22
23/// Walk the chunks inside a `WEBP` RIFF file.
24fn chunks(data: &[u8]) -> Result<Vec<Chunk<'_>>> {
25 let riff_size = data
26 .get(4..8)
27 .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
28 .ok_or_else(|| Error::corrupt("WebP: truncated RIFF header"))?;
29 // The declared size may exceed what is present in a truncated file; take
30 // whichever ends sooner rather than trusting the header.
31 let end = (riff_size + 8).min(data.len());
32 let mut out = Vec::new();
33 let mut at = 12usize;
34 while at + 8 <= end {
35 let tag = [data[at], data[at + 1], data[at + 2], data[at + 3]];
36 let size =
37 u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]) as usize;
38 let body = data
39 .get(at + 8..at + 8 + size)
40 .ok_or_else(|| Error::corrupt("WebP: chunk runs past the file"))?;
41 out.push(Chunk { tag, data: body });
42 // Chunks are padded to an even length.
43 at += 8 + size + (size & 1);
44 }
45 if out.is_empty() {
46 return Err(Error::corrupt("WebP: no chunks"));
47 }
48 Ok(out)
49}
50
51/// Whether the file is an animation rather than a still.
52///
53/// The question is answerable from the container alone -- the VP8X animation
54/// flag, or an `ANIM`/`ANMF` chunk -- so it is answered even for a file whose
55/// frames fail to decode. Bytes that are not a readable WebP are not an
56/// animation.
57pub fn is_animated(data: &[u8]) -> bool {
58 let Ok(chunks) = chunks(data) else {
59 return false;
60 };
61 chunks.iter().any(|chunk| match &chunk.tag {
62 b"VP8X" => chunk.data.first().is_some_and(|flags| flags & 0x02 != 0),
63 b"ANIM" | b"ANMF" => true,
64 _ => false,
65 })
66}
67
68/// Dimensions and EXIF orientation from the container's headers alone.
69///
70/// Walks the chunk headers without requiring the whole file: a chunk whose body
71/// runs past the end is read up to the end. A prefix of a file therefore reports
72/// the same answer as the whole file, as long as the image header and the `EXIF`
73/// chunk lie inside the prefix.
74pub fn info(data: &[u8]) -> Result<Info> {
75 let riff_size = data
76 .get(4..8)
77 .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize)
78 .ok_or_else(|| Error::corrupt("WebP: truncated RIFF header"))?;
79 let end = riff_size.saturating_add(8).min(data.len());
80 let mut dims: Option<(u32, u32)> = None;
81 let mut orientation = 1;
82 let mut at = 12usize;
83 while at + 8 <= end {
84 let tag = [data[at], data[at + 1], data[at + 2], data[at + 3]];
85 let size =
86 u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]) as usize;
87 let body = &data[at + 8..(at + 8).saturating_add(size).min(end)];
88 match &tag {
89 b"VP8X" if dims.is_none() && body.len() >= 10 => {
90 let width = 1 + (u32::from(body[4]) | u32::from(body[5]) << 8 | u32::from(body[6]) << 16);
91 let height = 1 + (u32::from(body[7]) | u32::from(body[8]) << 8 | u32::from(body[9]) << 16);
92 dims = Some((width, height));
93 }
94 b"VP8 " if dims.is_none() => dims = Some(vp8::dimensions(body)?),
95 b"VP8L" if dims.is_none() => {
96 if body.len() < 5 || body[0] != 0x2f {
97 return Err(Error::corrupt("WebP: short VP8L header"));
98 }
99 let packed = u32::from_le_bytes([body[1], body[2], body[3], body[4]]);
100 dims = Some(((packed & 0x3fff) + 1, ((packed >> 14) & 0x3fff) + 1));
101 }
102 b"EXIF" if orientation == 1 => {
103 orientation = exif::tiff_orientation(body).unwrap_or(1);
104 }
105 _ => {}
106 }
107 // Chunks are padded to an even length.
108 at += 8 + size + (size & 1);
109 }
110 let (width, height) = dims.ok_or_else(|| Error::corrupt("WebP: no image chunk"))?;
111 Ok(Info {
112 format: ImageFormat::WebP,
113 width,
114 height,
115 orientation,
116 })
117}
118
119/// Decode a WebP file.
120pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
121 let chunks = chunks(data)?;
122 let mut meta = Metadata::default();
123 let mut alpha: Option<&[u8]> = None;
124 let mut image: Option<(&[u8; 4], &[u8])> = None;
125
126 for chunk in &chunks {
127 match &chunk.tag {
128 b"VP8X" => {
129 let flags = chunk
130 .data
131 .first()
132 .copied()
133 .ok_or_else(|| Error::corrupt("WebP: empty VP8X"))?;
134 if flags & 0x02 != 0 {
135 return Err(Error::unsupported(
136 "animated WebP",
137 "this decoder returns one still picture, not a sequence of frames",
138 ));
139 }
140 }
141 b"ANIM" | b"ANMF" => {
142 return Err(Error::unsupported(
143 "animated WebP",
144 "this decoder returns one still picture, not a sequence of frames",
145 ));
146 }
147 b"ALPH" => alpha = Some(chunk.data),
148 b"VP8 " | b"VP8L" => {
149 if image.is_none() {
150 image = Some((&chunk.tag, chunk.data));
151 }
152 }
153 b"EXIF" => meta.orientation = meta.orientation.or(exif::tiff_orientation(chunk.data)),
154 _ => {}
155 }
156 }
157
158 let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?;
159 decode_payload(tag, body, alpha, meta, limits)
160}
161
162/// Decode one image payload -- a `VP8 ` or `VP8L` body, with its optional
163/// `ALPH` plane -- into pixels.
164///
165/// A still file and one frame of an animation differ only in where these
166/// chunks were found, so both paths land here.
167fn decode_payload(
168 tag: &[u8; 4],
169 body: &[u8],
170 alpha: Option<&[u8]>,
171 meta: Metadata,
172 limits: Limits,
173) -> Result<Image> {
174 if tag == b"VP8L" {
175 let argb = vp8l::decode(body, limits)?;
176 let mut rgba = Vec::with_capacity(argb.pixels.len() * 4);
177 for p in &argb.pixels {
178 rgba.extend_from_slice(&[
179 ((p >> 16) & 0xff) as u8,
180 ((p >> 8) & 0xff) as u8,
181 (p & 0xff) as u8,
182 ((p >> 24) & 0xff) as u8,
183 ]);
184 }
185 return Ok(Image {
186 width: argb.width,
187 height: argb.height,
188 pixels: Pixels::Rgba8(rgba),
189 meta,
190 });
191 }
192
193 // The RGB or RGBA picture is refused by name before the VP8 planes are formed.
194 let (dw, dh) = vp8::dimensions(body)?;
195 limits.check_output(dw, dh, if alpha.is_some() { 4 } else { 3 })?;
196 let frame = vp8::decode(body, limits)?;
197 let (w, h) = (frame.width as usize, frame.height as usize);
198 // Chroma is stored at half resolution and upsampled with the same triangle
199 // filter libwebp uses; nearest-neighbour here costs about a decibel.
200 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
201 let crop = |plane: &[u8]| -> Vec<u8> {
202 (0..ch)
203 .flat_map(|y| plane[y * frame.stride_uv..y * frame.stride_uv + cw].to_vec())
204 .collect()
205 };
206 let u_plane = crate::upsample::upsample(&crop(&frame.u), cw, ch, w, h);
207 let v_plane = crate::upsample::upsample(&crop(&frame.v), cw, ch, w, h);
208 let alpha_plane = match alpha {
209 Some(chunk) => Some(decode_alpha(chunk, frame.width, frame.height)?),
210 None => None,
211 };
212 let channels = if alpha_plane.is_some() { 4 } else { 3 };
213 let mut out = vec![0u8; w * h * channels];
214 for y in 0..h {
215 for x in 0..w {
216 let luma = frame.y[y * frame.stride_y + x];
217 let cb = u_plane[y * w + x];
218 let cr = v_plane[y * w + x];
219 let rgb = yuv_to_rgb(luma, cb, cr);
220 let at = (y * w + x) * channels;
221 out[at..at + 3].copy_from_slice(&rgb);
222 if let Some(plane) = &alpha_plane {
223 out[at + 3] = plane[y * w + x];
224 }
225 }
226 }
227 Ok(Image {
228 width: frame.width,
229 height: frame.height,
230 pixels: if channels == 4 {
231 Pixels::Rgba8(out)
232 } else {
233 Pixels::Rgb8(out)
234 },
235 meta,
236 })
237}
238
239/// Decode an animated WebP into composited canvas frames.
240///
241/// Every frame comes back as the whole canvas in RGBA, the way a player wants
242/// it: the frame rectangles, the two blending methods and the dispose-to-
243/// background rule are applied here rather than left to the caller.
244pub fn decode_frames(data: &[u8], limits: Limits) -> Result<Vec<crate::AnimationFrame>> {
245 let chunks = chunks(data)?;
246 let (canvas_width, canvas_height) = {
247 let info = info(data)?;
248 (info.width, info.height)
249 };
250 limits.check_output(canvas_width, canvas_height, 4)?;
251
252 let mut frames: Vec<crate::AnimationFrame> = Vec::new();
253 // The canvas starts fully transparent. The `ANIM` background colour is
254 // advice to a viewer about what to show behind the animation, not a colour
255 // the frames are composited onto -- libwebp's own animation decoder
256 // ignores it the same way.
257 let canvas_bytes = canvas_width as usize * canvas_height as usize * 4;
258 let mut canvas = vec![0u8; canvas_bytes];
259 let mut dispose: Option<(u32, u32, u32, u32)> = None;
260 let mut budget = crate::AllocBudget::default();
261 budget.spend(&limits, "WebP canvas", canvas_bytes)?;
262
263 for chunk in &chunks {
264 if &chunk.tag != b"ANMF" {
265 continue;
266 }
267 let d = chunk.data;
268 if d.len() < 16 {
269 return Err(Error::corrupt("WebP: short ANMF header"));
270 }
271 let u24 = |at: usize| u32::from_le_bytes([d[at], d[at + 1], d[at + 2], 0]);
272 let (x, y) = (u24(0) * 2, u24(3) * 2);
273 let (width, height) = (u24(6) + 1, u24(9) + 1);
274 let duration = u24(12);
275 let blend_over = d[15] & 0x02 == 0;
276 let dispose_to_background = d[15] & 0x01 != 0;
277 if x + width > canvas_width || y + height > canvas_height {
278 return Err(Error::corrupt(format!(
279 "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas"
280 )));
281 }
282 // Every ANMF frame clones the whole composited canvas below -- the
283 // real multiplier a single buffer's own bound never catches -- so
284 // it is spent from the decode-wide budget before that clone runs.
285 budget.spend(&limits, "WebP composited canvas", canvas_bytes)?;
286
287 // The previous frame's disposal happens before this one is drawn, so a
288 // caller that keeps every frame still sees each one whole.
289 if let Some((x, y, width, height)) = dispose.take() {
290 for row in y..y + height {
291 let at = (row as usize * canvas_width as usize + x as usize) * 4;
292 canvas[at..at + width as usize * 4].fill(0);
293 }
294 }
295
296 let mut alpha: Option<&[u8]> = None;
297 let mut payload: Option<(&[u8; 4], &[u8])> = None;
298 let mut at = 16usize;
299 while at + 8 <= d.len() {
300 let tag = [d[at], d[at + 1], d[at + 2], d[at + 3]];
301 let size = u32::from_le_bytes([d[at + 4], d[at + 5], d[at + 6], d[at + 7]]) as usize;
302 let body = d
303 .get(at + 8..at + 8 + size)
304 .ok_or_else(|| Error::corrupt("WebP: ANMF sub-chunk runs past the frame"))?;
305 match &tag {
306 b"ALPH" => alpha = Some(body),
307 // Only the first image chunk of a frame is the frame; the tag
308 // is kept as a static so the borrow of `d` does not outlive
309 // this iteration.
310 b"VP8 " if payload.is_none() => payload = Some((b"VP8 ", body)),
311 b"VP8L" if payload.is_none() => payload = Some((b"VP8L", body)),
312 _ => {}
313 }
314 at += 8 + size + (size & 1);
315 }
316 let (tag, body) =
317 payload.ok_or_else(|| Error::corrupt("WebP: ANMF without an image chunk"))?;
318 let sub = decode_payload(tag, body, alpha, Metadata::default(), limits)?;
319 if sub.width != width || sub.height != height {
320 return Err(Error::corrupt(format!(
321 "WebP: ANMF says {width}x{height}, the payload decodes {}x{}",
322 sub.width, sub.height
323 )));
324 }
325 let pixels = sub.to_rgba8();
326
327 for row in 0..height as usize {
328 for col in 0..width as usize {
329 let src = (row * width as usize + col) * 4;
330 let dst = ((row + y as usize) * canvas_width as usize + col + x as usize) * 4;
331 let src = &pixels[src..src + 4];
332 if !blend_over || src[3] == 255 {
333 canvas[dst..dst + 4].copy_from_slice(src);
334 continue;
335 }
336 if src[3] == 0 {
337 continue;
338 }
339 // Source-over in eight-bit alpha, rounded rather than
340 // truncated: a run of blended frames drifts visibly otherwise.
341 let sa = u32::from(src[3]);
342 let da = u32::from(canvas[dst + 3]);
343 let out_a = sa + da * (255 - sa) / 255;
344 for c in 0..3 {
345 let s = u32::from(src[c]) * sa;
346 let dcol = u32::from(canvas[dst + c]) * da * (255 - sa) / 255;
347 canvas[dst + c] = (s + dcol + out_a / 2)
348 .checked_div(out_a)
349 .unwrap_or(0)
350 .min(255) as u8;
351 }
352 canvas[dst + 3] = out_a as u8;
353 }
354 }
355
356 if dispose_to_background {
357 dispose = Some((x, y, width, height));
358 }
359 frames.push(crate::AnimationFrame {
360 image: Image {
361 width: canvas_width,
362 height: canvas_height,
363 pixels: Pixels::Rgba8(canvas.clone()),
364 meta: Metadata::default(),
365 },
366 delay_num: duration,
367 delay_den: 1000,
368 });
369 }
370
371 if frames.is_empty() {
372 return Err(Error::corrupt("WebP: an animation with no ANMF frame"));
373 }
374 Ok(frames)
375}
376
377/// BT.601 studio-swing YCbCr to RGB, in 16-bit fixed point.
378fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] {
379 let y = (i32::from(y) - 16) * 76284;
380 let u = i32::from(u) - 128;
381 let v = i32::from(v) - 128;
382 let r = y + 104595 * v;
383 let g = y - 25624 * u - 53281 * v;
384 let b = y + 132251 * u;
385 [
386 ((r + 32768) >> 16).clamp(0, 255) as u8,
387 ((g + 32768) >> 16).clamp(0, 255) as u8,
388 ((b + 32768) >> 16).clamp(0, 255) as u8,
389 ]
390}
391
392/// Decode an `ALPH` chunk into one byte of alpha per pixel.
393fn decode_alpha(chunk: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
394 let head = *chunk
395 .first()
396 .ok_or_else(|| Error::corrupt("WebP: empty ALPH chunk"))?;
397 let method = head & 0x03;
398 let filter = (head >> 2) & 0x03;
399 let body = &chunk[1..];
400 let count = (width as usize) * (height as usize);
401 let mut plane = match method {
402 0 => {
403 if body.len() < count {
404 return Err(Error::corrupt("WebP: ALPH shorter than the picture"));
405 }
406 body[..count].to_vec()
407 }
408 1 => {
409 // Lossless-coded, dimensions implied; the alpha lives in green.
410 let argb = vp8l::decode_implicit(body, width, height)?;
411 argb.iter().map(|p| ((p >> 8) & 0xff) as u8).collect()
412 }
413 other => {
414 return Err(Error::corrupt(format!(
415 "WebP: ALPH compression method {other}"
416 )));
417 }
418 };
419 unfilter_alpha(&mut plane, width as usize, height as usize, filter);
420 Ok(plane)
421}
422
423/// Undo the alpha plane's spatial filter (none / horizontal / vertical /
424/// gradient), in place.
425fn unfilter_alpha(plane: &mut [u8], width: usize, height: usize, filter: u8) {
426 if filter == 0 {
427 return;
428 }
429 for y in 0..height {
430 for x in 0..width {
431 let index = y * width + x;
432 let left = if x > 0 { plane[index - 1] } else { 0 };
433 let above = if y > 0 { plane[index - width] } else { 0 };
434 let above_left = if x > 0 && y > 0 {
435 plane[index - width - 1]
436 } else {
437 0
438 };
439 let predictor = if x == 0 && y == 0 {
440 0
441 } else if y == 0 {
442 // The top row has no pixel above, so it predicts from the left
443 // whatever the filter says, and the left column from above.
444 left
445 } else if x == 0 {
446 above
447 } else {
448 match filter {
449 1 => left,
450 2 => above,
451 _ => (i32::from(left) + i32::from(above) - i32::from(above_left)).clamp(0, 255)
452 as u8,
453 }
454 };
455 plane[index] = predictor.wrapping_add(plane[index]);
456 }
457 }
458}
459
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464
465 fn riff(chunks: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> {
466 let mut body = b"WEBP".to_vec();
467 for (tag, data) in chunks {
468 body.extend_from_slice(*tag);
469 body.extend_from_slice(&(data.len() as u32).to_le_bytes());
470 body.extend_from_slice(data);
471 if data.len() % 2 == 1 {
472 body.push(0);
473 }
474 }
475 let mut out = b"RIFF".to_vec();
476 out.extend_from_slice(&(body.len() as u32).to_le_bytes());
477 out.extend_from_slice(&body);
478 out
479 }
480
481 #[test]
482 fn odd_sized_chunks_are_padded_and_still_walked() {
483 let file = riff(&[(b"XXXX", vec![1, 2, 3]), (b"VP8L", vec![0x2f, 0, 0, 0, 0])]);
484 let found = chunks(&file).unwrap();
485 assert_eq!(found.len(), 2);
486 assert_eq!(&found[1].tag, b"VP8L");
487 assert_eq!(found[1].data.len(), 5);
488 }
489
490 #[test]
491 fn animation_is_refused_by_name() {
492 let mut vp8x = vec![0x02, 0, 0, 0];
493 vp8x.extend_from_slice(&[15, 0, 0, 15, 0, 0]);
494 let file = riff(&[(b"VP8X", vp8x), (b"ANMF", vec![0; 16])]);
495 let err = decode(&file, Limits::default()).unwrap_err();
496 assert!(format!("{err}").contains("animated"), "{err}");
497 }
498
499 #[test]
500 fn yuv_conversion_puts_studio_black_and_white_at_the_ends() {
501 assert_eq!(yuv_to_rgb(16, 128, 128), [0, 0, 0]);
502 assert_eq!(yuv_to_rgb(235, 128, 128), [255, 255, 255]);
503 let grey = yuv_to_rgb(126, 128, 128);
504 assert!(grey[0] == grey[1] && grey[1] == grey[2], "{grey:?}");
505 }
506
507 #[test]
508 fn the_alpha_gradient_filter_inverts_its_prediction() {
509 // Horizontal filter: each stored byte is a difference from the left.
510 let mut plane = vec![10u8, 5, 250, 1];
511 unfilter_alpha(&mut plane, 4, 1, 1);
512 assert_eq!(plane, vec![10, 15, 9, 10]);
513 }
514}