diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index 0a2faccf..36f0ee35 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -392,6 +392,9 @@ pub struct AnimationFrame { pub fn decode_animation(data: &[u8]) -> Result> { match ImageFormat::guess(data) { Some(ImageFormat::Gif) => gif::decode_animation(data, Limits::default()), + Some(ImageFormat::WebP) if webp::is_animated(data) => { + webp::decode_frames(data, Limits::default()) + } _ => Ok(vec![AnimationFrame { image: decode(data)?, delay_num: 0, diff --git a/crates/ec-image/src/webp/mod.rs b/crates/ec-image/src/webp/mod.rs index 3b2d2508..c5db77e6 100644 --- a/crates/ec-image/src/webp/mod.rs +++ b/crates/ec-image/src/webp/mod.rs @@ -1,9 +1,11 @@ //! WebP: the RIFF container, its lossy (`VP8 `) and lossless (`VP8L`) payloads, //! and the separate alpha plane (`ALPH`) an extended file may carry. //! -//! Animation is refused by name. A still decoder that quietly handed back the -//! first frame of an animation would make "this file plays" and "this file -//! decoded" indistinguishable to its caller. +//! `decode` returns one still picture and refuses an animation by name: a still +//! decoder that quietly handed back the first frame would make "this file +//! plays" and "this file decoded" indistinguishable to its caller. The +//! sequence is `decode_frames`, which composites the `ANMF` frames onto the +//! canvas. pub mod vp8; mod vp8_tables; @@ -46,6 +48,23 @@ fn chunks(data: &[u8]) -> Result>> { Ok(out) } +/// Whether the file is an animation rather than a still. +/// +/// The question is answerable from the container alone -- the VP8X animation +/// flag, or an `ANIM`/`ANMF` chunk -- so it is answered even for a file whose +/// frames fail to decode. Bytes that are not a readable WebP are not an +/// animation. +pub fn is_animated(data: &[u8]) -> bool { + let Ok(chunks) = chunks(data) else { + return false; + }; + chunks.iter().any(|chunk| match &chunk.tag { + b"VP8X" => chunk.data.first().is_some_and(|flags| flags & 0x02 != 0), + b"ANIM" | b"ANMF" => true, + _ => false, + }) +} + /// Dimensions from the container's headers alone. pub fn info(data: &[u8]) -> Result { let chunks = chunks(data)?; @@ -131,6 +150,21 @@ pub fn decode(data: &[u8], limits: Limits) -> Result { } let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?; + decode_payload(tag, body, alpha, meta, limits) +} + +/// Decode one image payload -- a `VP8 ` or `VP8L` body, with its optional +/// `ALPH` plane -- into pixels. +/// +/// A still file and one frame of an animation differ only in where these +/// chunks were found, so both paths land here. +fn decode_payload( + tag: &[u8; 4], + body: &[u8], + alpha: Option<&[u8]>, + meta: Metadata, + limits: Limits, +) -> Result { if tag == b"VP8L" { let argb = vp8l::decode(body, limits)?; let mut rgba = Vec::with_capacity(argb.pixels.len() * 4); @@ -193,6 +227,137 @@ pub fn decode(data: &[u8], limits: Limits) -> Result { }) } +/// Decode an animated WebP into composited canvas frames. +/// +/// Every frame comes back as the whole canvas in RGBA, the way a player wants +/// it: the frame rectangles, the two blending methods and the dispose-to- +/// background rule are applied here rather than left to the caller. +pub fn decode_frames(data: &[u8], limits: Limits) -> Result> { + let chunks = chunks(data)?; + let (canvas_width, canvas_height) = { + let info = info(data)?; + (info.width, info.height) + }; + limits.check(canvas_width, canvas_height)?; + + let mut frames: Vec = Vec::new(); + // The canvas starts fully transparent. The `ANIM` background colour is + // advice to a viewer about what to show behind the animation, not a colour + // the frames are composited onto -- libwebp's own animation decoder + // ignores it the same way. + let mut canvas = vec![0u8; canvas_width as usize * canvas_height as usize * 4]; + let mut dispose: Option<(u32, u32, u32, u32)> = None; + + for chunk in &chunks { + if &chunk.tag != b"ANMF" { + continue; + } + let d = chunk.data; + if d.len() < 16 { + return Err(Error::corrupt("WebP: short ANMF header")); + } + let u24 = |at: usize| u32::from_le_bytes([d[at], d[at + 1], d[at + 2], 0]); + let (x, y) = (u24(0) * 2, u24(3) * 2); + let (width, height) = (u24(6) + 1, u24(9) + 1); + let duration = u24(12); + let blend_over = d[15] & 0x02 == 0; + let dispose_to_background = d[15] & 0x01 != 0; + if x + width > canvas_width || y + height > canvas_height { + return Err(Error::corrupt(format!( + "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas" + ))); + } + + // The previous frame's disposal happens before this one is drawn, so a + // caller that keeps every frame still sees each one whole. + if let Some((x, y, width, height)) = dispose.take() { + for row in y..y + height { + let at = (row as usize * canvas_width as usize + x as usize) * 4; + canvas[at..at + width as usize * 4].fill(0); + } + } + + let mut alpha: Option<&[u8]> = None; + let mut payload: Option<(&[u8; 4], &[u8])> = None; + let mut at = 16usize; + while at + 8 <= d.len() { + let tag = [d[at], d[at + 1], d[at + 2], d[at + 3]]; + let size = u32::from_le_bytes([d[at + 4], d[at + 5], d[at + 6], d[at + 7]]) as usize; + let body = d + .get(at + 8..at + 8 + size) + .ok_or_else(|| Error::corrupt("WebP: ANMF sub-chunk runs past the frame"))?; + match &tag { + b"ALPH" => alpha = Some(body), + // Only the first image chunk of a frame is the frame; the tag + // is kept as a static so the borrow of `d` does not outlive + // this iteration. + b"VP8 " if payload.is_none() => payload = Some((b"VP8 ", body)), + b"VP8L" if payload.is_none() => payload = Some((b"VP8L", body)), + _ => {} + } + at += 8 + size + (size & 1); + } + let (tag, body) = + payload.ok_or_else(|| Error::corrupt("WebP: ANMF without an image chunk"))?; + let sub = decode_payload(tag, body, alpha, Metadata::default(), limits)?; + if sub.width != width || sub.height != height { + return Err(Error::corrupt(format!( + "WebP: ANMF says {width}x{height}, the payload decodes {}x{}", + sub.width, sub.height + ))); + } + let pixels = sub.to_rgba8(); + + for row in 0..height as usize { + for col in 0..width as usize { + let src = (row * width as usize + col) * 4; + let dst = ((row + y as usize) * canvas_width as usize + col + x as usize) * 4; + let src = &pixels[src..src + 4]; + if !blend_over || src[3] == 255 { + canvas[dst..dst + 4].copy_from_slice(src); + continue; + } + if src[3] == 0 { + continue; + } + // Source-over in eight-bit alpha, rounded rather than + // truncated: a run of blended frames drifts visibly otherwise. + let sa = u32::from(src[3]); + let da = u32::from(canvas[dst + 3]); + let out_a = sa + da * (255 - sa) / 255; + for c in 0..3 { + let s = u32::from(src[c]) * sa; + let dcol = u32::from(canvas[dst + c]) * da * (255 - sa) / 255; + canvas[dst + c] = (s + dcol + out_a / 2) + .checked_div(out_a) + .unwrap_or(0) + .min(255) as u8; + } + canvas[dst + 3] = out_a as u8; + } + } + + if dispose_to_background { + dispose = Some((x, y, width, height)); + } + frames.push(crate::AnimationFrame { + image: Image { + width: canvas_width, + height: canvas_height, + pixels: Pixels::Rgba8(canvas.clone()), + meta: Metadata::default(), + }, + delay_num: duration, + delay_den: 1000, + }); + } + + if frames.is_empty() { + return Err(Error::corrupt("WebP: an animation with no ANMF frame")); + } + Ok(frames) +} + /// BT.601 studio-swing YCbCr to RGB, in 16-bit fixed point. fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] { let y = (i32::from(y) - 16) * 76284; diff --git a/crates/ec-image/tests/differential.rs b/crates/ec-image/tests/differential.rs index b3cd102d..d6059bae 100644 --- a/crates/ec-image/tests/differential.rs +++ b/crates/ec-image/tests/differential.rs @@ -317,8 +317,8 @@ fn every_fixture_decodes() { for extension in ["png", "jpg", "webp"] { for path in corpus(extension) { let name = path.file_name().unwrap().to_string_lossy().to_string(); - if name.contains("animated") { - continue; // refused by name; `an_animated_webp_is_refused_by_name` covers it + if name.contains("animated") || name.starts_with("anim-") { + continue; // an animation is not a still; the animation tests cover it } let bytes = std::fs::read(&path).unwrap(); count += 1; @@ -436,3 +436,107 @@ fn a_still_of_any_format_is_one_frame_of_animation() { ec_image::decode(&bytes).unwrap().to_rgba8() ); } + +#[test] +fn an_animated_webp_composites_frame_for_frame_like_the_incumbent() { + one_animated_webp("animated.webp"); +} + +fn one_animated_webp(fixture: &str) { + use image::AnimationDecoder; + + let path = fixtures().join(fixture); + let Ok(bytes) = std::fs::read(&path) else { + skip(fixture); + return; + }; + assert!( + ec_image::webp::is_animated(&bytes), + "the fixture is not an animation" + ); + let ours = ec_image::decode_animation(&bytes).expect("our animation decode"); + let theirs: Vec = + image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&bytes)) + .expect("incumbent decoder") + .into_frames() + .collect::, _>>() + .expect("incumbent frames"); + + assert_eq!(ours.len(), theirs.len(), "frame count"); + assert!(ours.len() > 1, "the fixture is not an animation"); + for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() { + let (num, den) = theirs.delay().numer_denom_ms(); + let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den); + let theirs_ms = f64::from(num) / f64::from(den); + assert!( + (ours_ms - theirs_ms).abs() < 0.5, + "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms" + ); + assert_eq!( + (ours.image.width, ours.image.height), + theirs.buffer().dimensions(), + "frame {i} is not the whole canvas" + ); + // The frames are lossy VP8, so the payload is only as exact as the two + // VP8 decoders agree; the bar here is on the compositing, which is + // exact arithmetic over whatever the payload decoded to. + let a = ours.image.to_rgba8(); + let b = theirs.buffer().as_raw(); + let max = a + .iter() + .zip(b) + .map(|(&x, &y)| x.abs_diff(y)) + .max() + .unwrap_or(0); + let psnr = psnr(&a, b); + eprintln!("{fixture} frame {i}: {ours_ms:.0} ms, max delta {max}, {psnr:.1} dB"); + assert!( + max <= 5 && psnr > 48.0, + "{fixture} frame {i}: max delta {max}, {psnr:.1} dB" + ); + } +} + +/// Alpha blending and dispose-to-background, against libwebp itself. +/// +/// The `image` crate is not the oracle here: it ignores the ANMF +/// dispose-to-background flag, so the frame after a disposal keeps pixels +/// libwebp clears -- 6912 of 6912 pixels differ on this fixture, and libwebp +/// agrees with us on every one. The goldens are libwebp's own composited +/// frames, written by `scripts/gen-still-fixtures.sh`. +#[test] +fn webp_disposal_and_blending_match_libwebp() { + let path = fixtures().join("anim-alpha.webp"); + let Ok(bytes) = std::fs::read(&path) else { + skip("anim-alpha.webp"); + return; + }; + let goldens: Vec = (0..) + .map(|i| fixtures().join(format!("anim-alpha-f{i}.png"))) + .take_while(|p| p.exists()) + .collect(); + if goldens.is_empty() { + skip("anim-alpha-f0.png (libwebp goldens; Pillow not installed?)"); + return; + } + + let ours = ec_image::decode_animation(&bytes).expect("our animation decode"); + assert_eq!(ours.len(), goldens.len(), "frame count against libwebp"); + for (i, (ours, golden)) in ours.iter().zip(&goldens).enumerate() { + let want = ec_image::open(golden).expect("golden"); + assert_eq!( + (ours.image.width, ours.image.height), + (want.width, want.height), + "frame {i} is not the whole canvas" + ); + assert_eq!(ours.image.to_rgba8(), want.to_rgba8(), "frame {i} samples"); + eprintln!( + "frame {i}: {} ms, exact against libwebp", + f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den) + ); + } + // The delays come from the same headers, but a player that gets them wrong + // plays the animation at the wrong speed however exact the pixels are. + let delays: Vec = ours.iter().map(|f| f.delay_num).collect(); + assert_eq!(delays, vec![60, 90, 30], "per-frame durations in ms"); +} diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs index 500528f2..55efc4c7 100644 --- a/crates/ec-image/tests/fuzz.rs +++ b/crates/ec-image/tests/fuzz.rs @@ -169,6 +169,34 @@ fn a_gif_animation_survives_mutation() { eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded"); } +/// The WebP animation path parses its own ANMF headers and composites onto a +/// canvas sized by a different chunk, so a mutation can make the two disagree. +#[test] +fn an_animated_webp_survives_mutation() { + let Ok(seed) = std::fs::read(fixtures().join("anim-alpha.webp")) else { + eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh"); + return; + }; + let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed); + let mut decoded = 0usize; + for round in 0..ROUNDS { + let head = if round % 2 == 0 { Some(48) } else { None }; + let data = mutate(&mut rng, &seed, head); + if let Ok(frames) = ec_image::decode_animation(&data) { + decoded += 1; + for frame in &frames { + let image = &frame.image; + assert_eq!( + image.to_rgba8().len(), + (image.width as usize) * (image.height as usize) * 4, + "webp-animation round {round}: buffer does not match the dimensions" + ); + } + } + } + eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded"); +} + #[test] fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { let signatures: [&[u8]; 4] = [ diff --git a/lanes/image-webpanim-r1.report.md b/lanes/image-webpanim-r1.report.md new file mode 100644 index 00000000..8bbafc29 --- /dev/null +++ b/lanes/image-webpanim-r1.report.md @@ -0,0 +1,47 @@ +# lane-image-webpanim r1 — animated WebP + +## What landed + +`webp::is_animated`, answered from the container alone (the VP8X animation flag +or an `ANIM`/`ANMF` chunk), and `webp::decode_frames`, which walks the `ANMF` +chunks and composites them onto the canvas: frame rectangles, both blending +methods, dispose-to-background applied before the next frame is drawn, and the +duration of each frame in milliseconds. `decode_animation` routes an animated +WebP here; `decode` still refuses one by name. + +The still and animated paths share the payload decoder — a `VP8 ` or `VP8L` +body with its optional `ALPH` plane — which was factored out of `decode` as +`decode_payload`. The canvas starts fully transparent; the `ANIM` background +colour is advice to a viewer, not a colour the frames are composited onto, +which is also what libwebp does. + +## The oracle is libwebp, not the incumbent + +`image` 0.25.10 **ignores the ANMF dispose-to-background flag**. On the alpha +fixture its third frame keeps pixels libwebp clears: all 6912 pixels of the +canvas differ, and libwebp agrees with us on every one. So the fixture that +exercises blending and disposal is gated against libwebp's own composited +frames (written by `scripts/gen-still-fixtures.sh` through Pillow), and the +incumbent stays the oracle only for the opaque fixture, where the two agree. + +ffmpeg cannot arbitrate: its WebP decoder refuses an animation outright +(`image data not found`). + +## Gates + +| Gate | Result | +| --- | --- | +| `webp_disposal_and_blending_match_libwebp` | 3/3 frames **pixel-exact**, delays 60/90/30 ms exact | +| `an_animated_webp_composites_frame_for_frame_like_the_incumbent` | 3/3 frames, max delta 3, ≥52.7 dB (lossy VP8 payload) | +| `an_animated_webp_is_refused_by_name` | still `decode` still refuses an animation | +| `an_animated_webp_survives_mutation` | 10 000 mutations of the animation path, no panic, no hang | +| `cargo test -p ec-image` | 25 + 13 + 9 + 2, 0 failed | +| clippy | no new lint from this lane (the 1.98 toolchain fires new lints repo-wide; that is a separate sweep) | + +## New fixtures + +`anim-alpha.webp` — three lossless frames carrying alpha, flags `0x2` (no +blend), `0x3` (no blend + dispose to background) and `0x0` (blend over what the +disposal left). The pre-existing `animated.webp` is opaque and disposes +nothing, so it left both of those paths untested. +`anim-alpha-f{0,1,2}.png` — libwebp's composited frames, the goldens above. diff --git a/scripts/gen-still-fixtures.sh b/scripts/gen-still-fixtures.sh index 92521497..5fde0342 100755 --- a/scripts/gen-still-fixtures.sh +++ b/scripts/gen-still-fixtures.sh @@ -92,6 +92,36 @@ ffmpeg -loglevel error -y -i "$out/source-flat.png" -c:v libwebp -lossless 1 \ # writes this one: its output really does carry ANIM/ANMF chunks. magick -delay 10 "$out/source.png" "$out/source-flat.png" "$out/source-odd.png" \ -loop 0 "$out/animated.webp" +# A second animation whose frames carry alpha and ask for dispose-to-background: +# the first one is opaque and disposes nothing, so it leaves the blending and +# the disposal rectangle untested. Lossless, so the frames are exact and the +# only thing the comparison can catch is the compositing. +magick "$out/source-alpha.png" -resize 96x72! "$out/anim-a.png" +magick "$out/source-alpha.png" -resize 96x72! -channel A -evaluate multiply 0.5 \ + +channel "$out/anim-b.png" +magick "$out/source-flat.png" -resize 48x36! -background none -extent 96x72 \ + "$out/anim-c.png" +magick -dispose Background -delay 6 "$out/anim-a.png" -delay 9 "$out/anim-b.png" \ + -delay 3 "$out/anim-c.png" -loop 0 -define webp:lossless=true \ + "$out/anim-alpha.webp" +rm -f "$out/anim-a.png" "$out/anim-b.png" "$out/anim-c.png" +# libwebp's own composited frames, through Pillow, as the reference for that +# animation: the `image` crate ignores the dispose-to-background flag, so it +# cannot be the oracle for the frame that follows a disposal. +if python3 -c "import PIL" 2>/dev/null; then + python3 - "$out" <<'PILLOW' +import sys +from PIL import Image + +out = sys.argv[1] +animation = Image.open(f"{out}/anim-alpha.webp") +for i in range(animation.n_frames): + animation.seek(i) + animation.convert("RGBA").save(f"{out}/anim-alpha-f{i}.png") +PILLOW +else + echo "skipped anim-alpha-f*.png: python3 Pillow is not installed" >&2 +fi # --- GIF: still, interlaced, transparent, odd-size, animated --------------- # GIF is palette-only, so every source is quantised first; the differential bar