pub mod vp8l; use crate::{exif, Image, ImageFormat, Info, Limits, Metadata, Pixels}; use ec_core::{Error, Result}; use ec_vp8::decode::Decoder; struct Chunk<'a> { tag: [u8; 4], data: &'a [u8], } fn chunks(data: &[u8]) -> Result>> { let riff_size = data .get(4..8) .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize) .ok_or_else(|| Error::corrupt("WebP: truncated RIFF header"))?; let end = (riff_size + 8).min(data.len()); let mut out = Vec::new(); let mut at = 12usize; while at + 8 <= end { let tag = [data[at], data[at + 1], data[at + 2], data[at + 3]]; let size = u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]) as usize; let body = data .get(at + 8..at + 8 + size) .ok_or_else(|| Error::corrupt("WebP: chunk runs past the file"))?; out.push(Chunk { tag, data: body }); at += 8 + size + (size & 1); } if out.is_empty() { return Err(Error::corrupt("WebP: no chunks")); } Ok(out) } 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, }) } pub fn info(data: &[u8]) -> Result { let riff_size = data .get(4..8) .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize) .ok_or_else(|| Error::corrupt("WebP: truncated RIFF header"))?; let end = riff_size.saturating_add(8).min(data.len()); let mut dims: Option<(u32, u32)> = None; let mut orientation = 1; let mut at = 12usize; while at + 8 <= end { let tag = [data[at], data[at + 1], data[at + 2], data[at + 3]]; let size = u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]) as usize; let body = &data[at + 8..(at + 8).saturating_add(size).min(end)]; match &tag { b"VP8X" if dims.is_none() && body.len() >= 10 => { let width = 1 + (u32::from(body[4]) | u32::from(body[5]) << 8 | u32::from(body[6]) << 16); let height = 1 + (u32::from(body[7]) | u32::from(body[8]) << 8 | u32::from(body[9]) << 16); dims = Some((width, height)); } b"VP8 " if dims.is_none() => dims = Some(vp8_dimensions(body)?), b"VP8L" if dims.is_none() => { if body.len() < 5 || body[0] != 0x2f { return Err(Error::corrupt("WebP: short VP8L header")); } let packed = u32::from_le_bytes([body[1], body[2], body[3], body[4]]); dims = Some(((packed & 0x3fff) + 1, ((packed >> 14) & 0x3fff) + 1)); } b"EXIF" if orientation == 1 => { orientation = exif::tiff_orientation(body).unwrap_or(1); } _ => {} } at += 8 + size + (size & 1); } let (width, height) = dims.ok_or_else(|| Error::corrupt("WebP: no image chunk"))?; Ok(Info { format: ImageFormat::WebP, width, height, orientation, }) } pub fn decode(data: &[u8], limits: Limits) -> Result { let chunks = chunks(data)?; let mut meta = Metadata::default(); let mut alpha: Option<&[u8]> = None; let mut image: Option<(&[u8; 4], &[u8])> = None; for chunk in &chunks { match &chunk.tag { b"VP8X" => { let flags = chunk .data .first() .copied() .ok_or_else(|| Error::corrupt("WebP: empty VP8X"))?; if flags & 0x02 != 0 { return Err(Error::unsupported( "animated WebP", "this decoder returns one still picture, not a sequence of frames", )); } } b"ANIM" | b"ANMF" => { return Err(Error::unsupported( "animated WebP", "this decoder returns one still picture, not a sequence of frames", )); } b"ALPH" => alpha = Some(chunk.data), b"VP8 " | b"VP8L" => { if image.is_none() { image = Some((&chunk.tag, chunk.data)); } } b"EXIF" => meta.orientation = meta.orientation.or(exif::tiff_orientation(chunk.data)), _ => {} } } let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?; decode_payload(tag, body, alpha, meta, limits) } fn vp8_dimensions(body: &[u8]) -> Result<(u32, u32)> { let dims = ec_vp8::frame::parse_keyframe_dims(body)?; Ok((u32::from(dims.width), u32::from(dims.height))) } 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); for p in &argb.pixels { rgba.extend_from_slice(&[ ((p >> 16) & 0xff) as u8, ((p >> 8) & 0xff) as u8, (p & 0xff) as u8, ((p >> 24) & 0xff) as u8, ]); } return Ok(Image { width: argb.width, height: argb.height, pixels: Pixels::Rgba8(rgba), meta, }); } let (dw, dh) = vp8_dimensions(body)?; limits.check_output(dw, dh, if alpha.is_some() { 4 } else { 3 })?; let frame = Decoder::new() .decode(body)? .ok_or_else(|| Error::unsupported("hidden VP8 frame", "a still WebP must be shown"))?; let (w, h) = (usize::from(frame.width), usize::from(frame.height)); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let u_plane = crate::upsample::upsample(&frame.u, cw, ch, w, h); let v_plane = crate::upsample::upsample(&frame.v, cw, ch, w, h); let alpha_plane = match alpha { Some(chunk) => Some(decode_alpha( chunk, u32::from(frame.width), u32::from(frame.height), )?), None => None, }; let channels = if alpha_plane.is_some() { 4 } else { 3 }; let mut out = vec![0u8; w * h * channels]; for y in 0..h { for x in 0..w { let luma = frame.y[y * frame.stride + x]; let cb = u_plane[y * w + x]; let cr = v_plane[y * w + x]; let rgb = yuv_to_rgb(luma, cb, cr); let at = (y * w + x) * channels; out[at..at + 3].copy_from_slice(&rgb); if let Some(plane) = &alpha_plane { out[at + 3] = plane[y * w + x]; } } } Ok(Image { width: u32::from(frame.width), height: u32::from(frame.height), pixels: if channels == 4 { Pixels::Rgba8(out) } else { Pixels::Rgb8(out) }, meta, }) } 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_output(canvas_width, canvas_height, 4)?; let mut frames: Vec = Vec::new(); let canvas_bytes = canvas_width as usize * canvas_height as usize * 4; let mut canvas = vec![0u8; canvas_bytes]; let mut dispose: Option<(u32, u32, u32, u32)> = None; let mut budget = crate::AllocBudget::default(); budget.spend(&limits, "WebP canvas", canvas_bytes)?; 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" ))); } budget.spend(&limits, "WebP composited canvas", canvas_bytes)?; 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), 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; } 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) } fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] { let y = (i32::from(y) - 16) * 76284; let u = i32::from(u) - 128; let v = i32::from(v) - 128; let r = y + 104595 * v; let g = y - 25624 * u - 53281 * v; let b = y + 132251 * u; [ ((r + 32768) >> 16).clamp(0, 255) as u8, ((g + 32768) >> 16).clamp(0, 255) as u8, ((b + 32768) >> 16).clamp(0, 255) as u8, ] } fn decode_alpha(chunk: &[u8], width: u32, height: u32) -> Result> { let head = *chunk .first() .ok_or_else(|| Error::corrupt("WebP: empty ALPH chunk"))?; let method = head & 0x03; let filter = (head >> 2) & 0x03; let body = &chunk[1..]; let count = (width as usize) * (height as usize); let mut plane = match method { 0 => { if body.len() < count { return Err(Error::corrupt("WebP: ALPH shorter than the picture")); } body[..count].to_vec() } 1 => { let argb = vp8l::decode_implicit(body, width, height)?; argb.iter().map(|p| ((p >> 8) & 0xff) as u8).collect() } other => { return Err(Error::corrupt(format!( "WebP: ALPH compression method {other}" ))); } }; unfilter_alpha(&mut plane, width as usize, height as usize, filter); Ok(plane) } fn unfilter_alpha(plane: &mut [u8], width: usize, height: usize, filter: u8) { if filter == 0 { return; } for y in 0..height { for x in 0..width { let index = y * width + x; let left = if x > 0 { plane[index - 1] } else { 0 }; let above = if y > 0 { plane[index - width] } else { 0 }; let above_left = if x > 0 && y > 0 { plane[index - width - 1] } else { 0 }; let predictor = if x == 0 && y == 0 { 0 } else if y == 0 { left } else if x == 0 { above } else { match filter { 1 => left, 2 => above, _ => (i32::from(left) + i32::from(above) - i32::from(above_left)).clamp(0, 255) as u8, } }; plane[index] = predictor.wrapping_add(plane[index]); } } } #[cfg(test)] mod tests { use super::*; fn riff(chunks: &[(&[u8; 4], Vec)]) -> Vec { let mut body = b"WEBP".to_vec(); for (tag, data) in chunks { body.extend_from_slice(*tag); body.extend_from_slice(&(data.len() as u32).to_le_bytes()); body.extend_from_slice(data); if data.len() % 2 == 1 { body.push(0); } } let mut out = b"RIFF".to_vec(); out.extend_from_slice(&(body.len() as u32).to_le_bytes()); out.extend_from_slice(&body); out } #[test] fn odd_sized_chunks_are_padded_and_still_walked() { let file = riff(&[(b"XXXX", vec![1, 2, 3]), (b"VP8L", vec![0x2f, 0, 0, 0, 0])]); let found = chunks(&file).unwrap(); assert_eq!(found.len(), 2); assert_eq!(&found[1].tag, b"VP8L"); assert_eq!(found[1].data.len(), 5); } #[test] fn animation_is_refused_by_name() { let mut vp8x = vec![0x02, 0, 0, 0]; vp8x.extend_from_slice(&[15, 0, 0, 15, 0, 0]); let file = riff(&[(b"VP8X", vp8x), (b"ANMF", vec![0; 16])]); let err = decode(&file, Limits::default()).unwrap_err(); assert!(format!("{err}").contains("animated"), "{err}"); } #[test] fn yuv_conversion_puts_studio_black_and_white_at_the_ends() { assert_eq!(yuv_to_rgb(16, 128, 128), [0, 0, 0]); assert_eq!(yuv_to_rgb(235, 128, 128), [255, 255, 255]); let grey = yuv_to_rgb(126, 128, 128); assert!(grey[0] == grey[1] && grey[1] == grey[2], "{grey:?}"); } #[test] fn the_alpha_gradient_filter_inverts_its_prediction() { let mut plane = vec![10u8, 5, 250, 1]; unfilter_alpha(&mut plane, 4, 1, 1); assert_eq!(plane, vec![10, 15, 9, 10]); } }