| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | pub mod vp8; |
| 11 | mod vp8_tables; |
| 12 | pub mod vp8l; |
| 13 | |
| 14 | use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; |
| 15 | use ec_core::{Error, Result}; |
| 16 | |
| 17 | |
| 18 | struct Chunk<'a> { |
| 19 | tag: [u8; 4], |
| 20 | data: &'a [u8], |
| 21 | } |
| 22 | |
| 23 | |
| 24 | fn 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 | |
| 30 | |
| 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 | |
| 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 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | pub 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 | |
| 69 | pub fn info(data: &[u8]) -> Result<Info> { |
| 70 | let chunks = chunks(data)?; |
| 71 | for chunk in &chunks { |
| 72 | match &chunk.tag { |
| 73 | b"VP8X" if chunk.data.len() >= 10 => { |
| 74 | let d = chunk.data; |
| 75 | let width = 1 + (u32::from(d[4]) | u32::from(d[5]) << 8 | u32::from(d[6]) << 16); |
| 76 | let height = 1 + (u32::from(d[7]) | u32::from(d[8]) << 8 | u32::from(d[9]) << 16); |
| 77 | return Ok(Info { |
| 78 | format: ImageFormat::WebP, |
| 79 | width, |
| 80 | height, |
| 81 | }); |
| 82 | } |
| 83 | b"VP8 " => { |
| 84 | let (width, height) = vp8::dimensions(chunk.data)?; |
| 85 | return Ok(Info { |
| 86 | format: ImageFormat::WebP, |
| 87 | width, |
| 88 | height, |
| 89 | }); |
| 90 | } |
| 91 | b"VP8L" => { |
| 92 | let d = chunk.data; |
| 93 | if d.len() < 5 || d[0] != 0x2f { |
| 94 | return Err(Error::corrupt("WebP: short VP8L header")); |
| 95 | } |
| 96 | let packed = u32::from_le_bytes([d[1], d[2], d[3], d[4]]); |
| 97 | return Ok(Info { |
| 98 | format: ImageFormat::WebP, |
| 99 | width: (packed & 0x3fff) + 1, |
| 100 | height: ((packed >> 14) & 0x3fff) + 1, |
| 101 | }); |
| 102 | } |
| 103 | _ => {} |
| 104 | } |
| 105 | } |
| 106 | Err(Error::corrupt("WebP: no image chunk")) |
| 107 | } |
| 108 | |
| 109 | |
| 110 | pub fn decode(data: &[u8], limits: Limits) -> Result<Image> { |
| 111 | let chunks = chunks(data)?; |
| 112 | let mut meta = Metadata::default(); |
| 113 | let mut alpha: Option<&[u8]> = None; |
| 114 | let mut image: Option<(&[u8; 4], &[u8])> = None; |
| 115 | |
| 116 | for chunk in &chunks { |
| 117 | match &chunk.tag { |
| 118 | b"VP8X" => { |
| 119 | let flags = chunk |
| 120 | .data |
| 121 | .first() |
| 122 | .copied() |
| 123 | .ok_or_else(|| Error::corrupt("WebP: empty VP8X"))?; |
| 124 | if flags & 0x02 != 0 { |
| 125 | return Err(Error::unsupported( |
| 126 | "animated WebP", |
| 127 | "this decoder returns one still picture, not a sequence of frames", |
| 128 | )); |
| 129 | } |
| 130 | } |
| 131 | b"ANIM" | b"ANMF" => { |
| 132 | return Err(Error::unsupported( |
| 133 | "animated WebP", |
| 134 | "this decoder returns one still picture, not a sequence of frames", |
| 135 | )); |
| 136 | } |
| 137 | b"ALPH" => alpha = Some(chunk.data), |
| 138 | b"VP8 " | b"VP8L" => { |
| 139 | if image.is_none() { |
| 140 | image = Some((&chunk.tag, chunk.data)); |
| 141 | } |
| 142 | } |
| 143 | b"EXIF" => { |
| 144 | if let Some(o) = exif_orientation(chunk.data) { |
| 145 | meta.orientation = Some(o); |
| 146 | } |
| 147 | } |
| 148 | _ => {} |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?; |
| 153 | decode_payload(tag, body, alpha, meta, limits) |
| 154 | } |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | fn decode_payload( |
| 162 | tag: &[u8; 4], |
| 163 | body: &[u8], |
| 164 | alpha: Option<&[u8]>, |
| 165 | meta: Metadata, |
| 166 | limits: Limits, |
| 167 | ) -> Result<Image> { |
| 168 | if tag == b"VP8L" { |
| 169 | let argb = vp8l::decode(body, limits)?; |
| 170 | let mut rgba = Vec::with_capacity(argb.pixels.len() * 4); |
| 171 | for p in &argb.pixels { |
| 172 | rgba.extend_from_slice(&[ |
| 173 | ((p >> 16) & 0xff) as u8, |
| 174 | ((p >> 8) & 0xff) as u8, |
| 175 | (p & 0xff) as u8, |
| 176 | ((p >> 24) & 0xff) as u8, |
| 177 | ]); |
| 178 | } |
| 179 | return Ok(Image { |
| 180 | width: argb.width, |
| 181 | height: argb.height, |
| 182 | pixels: Pixels::Rgba8(rgba), |
| 183 | meta, |
| 184 | }); |
| 185 | } |
| 186 | |
| 187 | let frame = vp8::decode(body, limits)?; |
| 188 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 189 | |
| 190 | |
| 191 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 192 | let crop = |plane: &[u8]| -> Vec<u8> { |
| 193 | (0..ch) |
| 194 | .flat_map(|y| plane[y * frame.stride_uv..y * frame.stride_uv + cw].to_vec()) |
| 195 | .collect() |
| 196 | }; |
| 197 | let u_plane = crate::upsample::upsample(&crop(&frame.u), cw, ch, w, h); |
| 198 | let v_plane = crate::upsample::upsample(&crop(&frame.v), cw, ch, w, h); |
| 199 | let alpha_plane = match alpha { |
| 200 | Some(chunk) => Some(decode_alpha(chunk, frame.width, frame.height)?), |
| 201 | None => None, |
| 202 | }; |
| 203 | let channels = if alpha_plane.is_some() { 4 } else { 3 }; |
| 204 | let mut out = vec![0u8; w * h * channels]; |
| 205 | for y in 0..h { |
| 206 | for x in 0..w { |
| 207 | let luma = frame.y[y * frame.stride_y + x]; |
| 208 | let cb = u_plane[y * w + x]; |
| 209 | let cr = v_plane[y * w + x]; |
| 210 | let rgb = yuv_to_rgb(luma, cb, cr); |
| 211 | let at = (y * w + x) * channels; |
| 212 | out[at..at + 3].copy_from_slice(&rgb); |
| 213 | if let Some(plane) = &alpha_plane { |
| 214 | out[at + 3] = plane[y * w + x]; |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | Ok(Image { |
| 219 | width: frame.width, |
| 220 | height: frame.height, |
| 221 | pixels: if channels == 4 { |
| 222 | Pixels::Rgba8(out) |
| 223 | } else { |
| 224 | Pixels::Rgb8(out) |
| 225 | }, |
| 226 | meta, |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | pub fn decode_frames(data: &[u8], limits: Limits) -> Result<Vec<crate::AnimationFrame>> { |
| 236 | let chunks = chunks(data)?; |
| 237 | let (canvas_width, canvas_height) = { |
| 238 | let info = info(data)?; |
| 239 | (info.width, info.height) |
| 240 | }; |
| 241 | limits.check(canvas_width, canvas_height)?; |
| 242 | |
| 243 | let mut frames: Vec<crate::AnimationFrame> = Vec::new(); |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | let canvas_bytes = canvas_width as usize * canvas_height as usize * 4; |
| 249 | let mut canvas = vec![0u8; canvas_bytes]; |
| 250 | let mut dispose: Option<(u32, u32, u32, u32)> = None; |
| 251 | let mut budget = crate::AllocBudget::default(); |
| 252 | budget.spend(&limits, "WebP canvas", canvas_bytes)?; |
| 253 | |
| 254 | for chunk in &chunks { |
| 255 | if &chunk.tag != b"ANMF" { |
| 256 | continue; |
| 257 | } |
| 258 | let d = chunk.data; |
| 259 | if d.len() < 16 { |
| 260 | return Err(Error::corrupt("WebP: short ANMF header")); |
| 261 | } |
| 262 | let u24 = |at: usize| u32::from_le_bytes([d[at], d[at + 1], d[at + 2], 0]); |
| 263 | let (x, y) = (u24(0) * 2, u24(3) * 2); |
| 264 | let (width, height) = (u24(6) + 1, u24(9) + 1); |
| 265 | let duration = u24(12); |
| 266 | let blend_over = d[15] & 0x02 == 0; |
| 267 | let dispose_to_background = d[15] & 0x01 != 0; |
| 268 | if x + width > canvas_width || y + height > canvas_height { |
| 269 | return Err(Error::corrupt(format!( |
| 270 | "WebP: frame {width}x{height}+{x}+{y} runs off a {canvas_width}x{canvas_height} canvas" |
| 271 | ))); |
| 272 | } |
| 273 | |
| 274 | |
| 275 | |
| 276 | budget.spend(&limits, "WebP composited canvas", canvas_bytes)?; |
| 277 | |
| 278 | |
| 279 | |
| 280 | if let Some((x, y, width, height)) = dispose.take() { |
| 281 | for row in y..y + height { |
| 282 | let at = (row as usize * canvas_width as usize + x as usize) * 4; |
| 283 | canvas[at..at + width as usize * 4].fill(0); |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | let mut alpha: Option<&[u8]> = None; |
| 288 | let mut payload: Option<(&[u8; 4], &[u8])> = None; |
| 289 | let mut at = 16usize; |
| 290 | while at + 8 <= d.len() { |
| 291 | let tag = [d[at], d[at + 1], d[at + 2], d[at + 3]]; |
| 292 | let size = u32::from_le_bytes([d[at + 4], d[at + 5], d[at + 6], d[at + 7]]) as usize; |
| 293 | let body = d |
| 294 | .get(at + 8..at + 8 + size) |
| 295 | .ok_or_else(|| Error::corrupt("WebP: ANMF sub-chunk runs past the frame"))?; |
| 296 | match &tag { |
| 297 | b"ALPH" => alpha = Some(body), |
| 298 | |
| 299 | |
| 300 | |
| 301 | b"VP8 " if payload.is_none() => payload = Some((b"VP8 ", body)), |
| 302 | b"VP8L" if payload.is_none() => payload = Some((b"VP8L", body)), |
| 303 | _ => {} |
| 304 | } |
| 305 | at += 8 + size + (size & 1); |
| 306 | } |
| 307 | let (tag, body) = |
| 308 | payload.ok_or_else(|| Error::corrupt("WebP: ANMF without an image chunk"))?; |
| 309 | let sub = decode_payload(tag, body, alpha, Metadata::default(), limits)?; |
| 310 | if sub.width != width || sub.height != height { |
| 311 | return Err(Error::corrupt(format!( |
| 312 | "WebP: ANMF says {width}x{height}, the payload decodes {}x{}", |
| 313 | sub.width, sub.height |
| 314 | ))); |
| 315 | } |
| 316 | let pixels = sub.to_rgba8(); |
| 317 | |
| 318 | for row in 0..height as usize { |
| 319 | for col in 0..width as usize { |
| 320 | let src = (row * width as usize + col) * 4; |
| 321 | let dst = ((row + y as usize) * canvas_width as usize + col + x as usize) * 4; |
| 322 | let src = &pixels[src..src + 4]; |
| 323 | if !blend_over || src[3] == 255 { |
| 324 | canvas[dst..dst + 4].copy_from_slice(src); |
| 325 | continue; |
| 326 | } |
| 327 | if src[3] == 0 { |
| 328 | continue; |
| 329 | } |
| 330 | |
| 331 | |
| 332 | let sa = u32::from(src[3]); |
| 333 | let da = u32::from(canvas[dst + 3]); |
| 334 | let out_a = sa + da * (255 - sa) / 255; |
| 335 | for c in 0..3 { |
| 336 | let s = u32::from(src[c]) * sa; |
| 337 | let dcol = u32::from(canvas[dst + c]) * da * (255 - sa) / 255; |
| 338 | canvas[dst + c] = (s + dcol + out_a / 2) |
| 339 | .checked_div(out_a) |
| 340 | .unwrap_or(0) |
| 341 | .min(255) as u8; |
| 342 | } |
| 343 | canvas[dst + 3] = out_a as u8; |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | if dispose_to_background { |
| 348 | dispose = Some((x, y, width, height)); |
| 349 | } |
| 350 | frames.push(crate::AnimationFrame { |
| 351 | image: Image { |
| 352 | width: canvas_width, |
| 353 | height: canvas_height, |
| 354 | pixels: Pixels::Rgba8(canvas.clone()), |
| 355 | meta: Metadata::default(), |
| 356 | }, |
| 357 | delay_num: duration, |
| 358 | delay_den: 1000, |
| 359 | }); |
| 360 | } |
| 361 | |
| 362 | if frames.is_empty() { |
| 363 | return Err(Error::corrupt("WebP: an animation with no ANMF frame")); |
| 364 | } |
| 365 | Ok(frames) |
| 366 | } |
| 367 | |
| 368 | |
| 369 | fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] { |
| 370 | let y = (i32::from(y) - 16) * 76284; |
| 371 | let u = i32::from(u) - 128; |
| 372 | let v = i32::from(v) - 128; |
| 373 | let r = y + 104595 * v; |
| 374 | let g = y - 25624 * u - 53281 * v; |
| 375 | let b = y + 132251 * u; |
| 376 | [ |
| 377 | ((r + 32768) >> 16).clamp(0, 255) as u8, |
| 378 | ((g + 32768) >> 16).clamp(0, 255) as u8, |
| 379 | ((b + 32768) >> 16).clamp(0, 255) as u8, |
| 380 | ] |
| 381 | } |
| 382 | |
| 383 | |
| 384 | fn decode_alpha(chunk: &[u8], width: u32, height: u32) -> Result<Vec<u8>> { |
| 385 | let head = *chunk |
| 386 | .first() |
| 387 | .ok_or_else(|| Error::corrupt("WebP: empty ALPH chunk"))?; |
| 388 | let method = head & 0x03; |
| 389 | let filter = (head >> 2) & 0x03; |
| 390 | let body = &chunk[1..]; |
| 391 | let count = (width as usize) * (height as usize); |
| 392 | let mut plane = match method { |
| 393 | 0 => { |
| 394 | if body.len() < count { |
| 395 | return Err(Error::corrupt("WebP: ALPH shorter than the picture")); |
| 396 | } |
| 397 | body[..count].to_vec() |
| 398 | } |
| 399 | 1 => { |
| 400 | |
| 401 | let argb = vp8l::decode_implicit(body, width, height)?; |
| 402 | argb.iter().map(|p| ((p >> 8) & 0xff) as u8).collect() |
| 403 | } |
| 404 | other => { |
| 405 | return Err(Error::corrupt(format!( |
| 406 | "WebP: ALPH compression method {other}" |
| 407 | ))); |
| 408 | } |
| 409 | }; |
| 410 | unfilter_alpha(&mut plane, width as usize, height as usize, filter); |
| 411 | Ok(plane) |
| 412 | } |
| 413 | |
| 414 | |
| 415 | |
| 416 | fn unfilter_alpha(plane: &mut [u8], width: usize, height: usize, filter: u8) { |
| 417 | if filter == 0 { |
| 418 | return; |
| 419 | } |
| 420 | for y in 0..height { |
| 421 | for x in 0..width { |
| 422 | let index = y * width + x; |
| 423 | let left = if x > 0 { plane[index - 1] } else { 0 }; |
| 424 | let above = if y > 0 { plane[index - width] } else { 0 }; |
| 425 | let above_left = if x > 0 && y > 0 { |
| 426 | plane[index - width - 1] |
| 427 | } else { |
| 428 | 0 |
| 429 | }; |
| 430 | let predictor = if x == 0 && y == 0 { |
| 431 | 0 |
| 432 | } else if y == 0 { |
| 433 | |
| 434 | |
| 435 | left |
| 436 | } else if x == 0 { |
| 437 | above |
| 438 | } else { |
| 439 | match filter { |
| 440 | 1 => left, |
| 441 | 2 => above, |
| 442 | _ => (i32::from(left) + i32::from(above) - i32::from(above_left)).clamp(0, 255) |
| 443 | as u8, |
| 444 | } |
| 445 | }; |
| 446 | plane[index] = predictor.wrapping_add(plane[index]); |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | |
| 452 | fn exif_orientation(data: &[u8]) -> Option<u8> { |
| 453 | let little = match data.get(..2)? { |
| 454 | b"II" => true, |
| 455 | b"MM" => false, |
| 456 | _ => return None, |
| 457 | }; |
| 458 | let u16_at = |at: usize| -> Option<u16> { |
| 459 | let b = data.get(at..at + 2)?; |
| 460 | Some(if little { |
| 461 | u16::from_le_bytes([b[0], b[1]]) |
| 462 | } else { |
| 463 | u16::from_be_bytes([b[0], b[1]]) |
| 464 | }) |
| 465 | }; |
| 466 | let u32_at = |at: usize| -> Option<u32> { |
| 467 | let b = data.get(at..at + 4)?; |
| 468 | Some(if little { |
| 469 | u32::from_le_bytes([b[0], b[1], b[2], b[3]]) |
| 470 | } else { |
| 471 | u32::from_be_bytes([b[0], b[1], b[2], b[3]]) |
| 472 | }) |
| 473 | }; |
| 474 | if u16_at(2)? != 42 { |
| 475 | return None; |
| 476 | } |
| 477 | let ifd = u32_at(4)? as usize; |
| 478 | let count = usize::from(u16_at(ifd)?); |
| 479 | for i in 0..count { |
| 480 | let entry = ifd + 2 + i * 12; |
| 481 | if u16_at(entry)? == 0x0112 { |
| 482 | let value = u16_at(entry + 8)?; |
| 483 | return (1..=8).contains(&value).then_some(value as u8); |
| 484 | } |
| 485 | } |
| 486 | None |
| 487 | } |
| 488 | |
| 489 | #[cfg(test)] |
| 490 | mod tests { |
| 491 | use super::*; |
| 492 | |
| 493 | fn riff(chunks: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> { |
| 494 | let mut body = b"WEBP".to_vec(); |
| 495 | for (tag, data) in chunks { |
| 496 | body.extend_from_slice(*tag); |
| 497 | body.extend_from_slice(&(data.len() as u32).to_le_bytes()); |
| 498 | body.extend_from_slice(data); |
| 499 | if data.len() % 2 == 1 { |
| 500 | body.push(0); |
| 501 | } |
| 502 | } |
| 503 | let mut out = b"RIFF".to_vec(); |
| 504 | out.extend_from_slice(&(body.len() as u32).to_le_bytes()); |
| 505 | out.extend_from_slice(&body); |
| 506 | out |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn odd_sized_chunks_are_padded_and_still_walked() { |
| 511 | let file = riff(&[(b"XXXX", vec![1, 2, 3]), (b"VP8L", vec![0x2f, 0, 0, 0, 0])]); |
| 512 | let found = chunks(&file).unwrap(); |
| 513 | assert_eq!(found.len(), 2); |
| 514 | assert_eq!(&found[1].tag, b"VP8L"); |
| 515 | assert_eq!(found[1].data.len(), 5); |
| 516 | } |
| 517 | |
| 518 | #[test] |
| 519 | fn animation_is_refused_by_name() { |
| 520 | let mut vp8x = vec![0x02, 0, 0, 0]; |
| 521 | vp8x.extend_from_slice(&[15, 0, 0, 15, 0, 0]); |
| 522 | let file = riff(&[(b"VP8X", vp8x), (b"ANMF", vec![0; 16])]); |
| 523 | let err = decode(&file, Limits::default()).unwrap_err(); |
| 524 | assert!(format!("{err}").contains("animated"), "{err}"); |
| 525 | } |
| 526 | |
| 527 | #[test] |
| 528 | fn yuv_conversion_puts_studio_black_and_white_at_the_ends() { |
| 529 | assert_eq!(yuv_to_rgb(16, 128, 128), [0, 0, 0]); |
| 530 | assert_eq!(yuv_to_rgb(235, 128, 128), [255, 255, 255]); |
| 531 | let grey = yuv_to_rgb(126, 128, 128); |
| 532 | assert!(grey[0] == grey[1] && grey[1] == grey[2], "{grey:?}"); |
| 533 | } |
| 534 | |
| 535 | #[test] |
| 536 | fn the_alpha_gradient_filter_inverts_its_prediction() { |
| 537 | |
| 538 | let mut plane = vec![10u8, 5, 250, 1]; |
| 539 | unfilter_alpha(&mut plane, 4, 1, 1); |
| 540 | assert_eq!(plane, vec![10, 15, 9, 10]); |
| 541 | } |
| 542 | } |