diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index a07526d9..0da48893 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -34,6 +34,7 @@ pub mod jpeg; pub mod png; mod upsample; +pub mod webp; use ec_core::{PixelFormat, Plane, VideoFrame}; @@ -340,10 +341,7 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { match ImageFormat::guess(data) { Some(ImageFormat::Png) => png::decode(data, limits), Some(ImageFormat::Jpeg) => jpeg::decode(data, limits), - Some(ImageFormat::WebP) => Err(Error::unsupported( - "WebP", - "the WebP decoder is a later stage of this crate", - )), + Some(ImageFormat::WebP) => webp::decode(data, limits), None => Err(Error::unsupported( "image", "no PNG, JPEG or WebP signature at the start of the data", @@ -356,10 +354,7 @@ pub fn info(data: &[u8]) -> Result { match ImageFormat::guess(data) { Some(ImageFormat::Png) => png::info(data), Some(ImageFormat::Jpeg) => jpeg::info(data), - Some(ImageFormat::WebP) => Err(Error::unsupported( - "WebP", - "the WebP decoder is a later stage of this crate", - )), + Some(ImageFormat::WebP) => webp::info(data), None => Err(Error::unsupported( "image", "no PNG, JPEG or WebP signature at the start of the data", diff --git a/crates/ec-image/src/webp/mod.rs b/crates/ec-image/src/webp/mod.rs new file mode 100644 index 00000000..3b2d2508 --- /dev/null +++ b/crates/ec-image/src/webp/mod.rs @@ -0,0 +1,370 @@ +//! 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. + +pub mod vp8; +mod vp8_tables; +pub mod vp8l; + +use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use ec_core::{Error, Result}; + +/// One RIFF chunk. +struct Chunk<'a> { + tag: [u8; 4], + data: &'a [u8], +} + +/// Walk the chunks inside a `WEBP` RIFF file. +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"))?; + // The declared size may exceed what is present in a truncated file; take + // whichever ends sooner rather than trusting the 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 }); + // Chunks are padded to an even length. + at += 8 + size + (size & 1); + } + if out.is_empty() { + return Err(Error::corrupt("WebP: no chunks")); + } + Ok(out) +} + +/// Dimensions from the container's headers alone. +pub fn info(data: &[u8]) -> Result { + let chunks = chunks(data)?; + for chunk in &chunks { + match &chunk.tag { + b"VP8X" if chunk.data.len() >= 10 => { + let d = chunk.data; + let width = 1 + (u32::from(d[4]) | u32::from(d[5]) << 8 | u32::from(d[6]) << 16); + let height = 1 + (u32::from(d[7]) | u32::from(d[8]) << 8 | u32::from(d[9]) << 16); + return Ok(Info { + format: ImageFormat::WebP, + width, + height, + }); + } + b"VP8 " => { + let (width, height) = vp8::dimensions(chunk.data)?; + return Ok(Info { + format: ImageFormat::WebP, + width, + height, + }); + } + b"VP8L" => { + let d = chunk.data; + if d.len() < 5 || d[0] != 0x2f { + return Err(Error::corrupt("WebP: short VP8L header")); + } + let packed = u32::from_le_bytes([d[1], d[2], d[3], d[4]]); + return Ok(Info { + format: ImageFormat::WebP, + width: (packed & 0x3fff) + 1, + height: ((packed >> 14) & 0x3fff) + 1, + }); + } + _ => {} + } + } + Err(Error::corrupt("WebP: no image chunk")) +} + +/// Decode a WebP file. +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" => { + if let Some(o) = exif_orientation(chunk.data) { + meta.orientation = Some(o); + } + } + _ => {} + } + } + + let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?; + 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 frame = vp8::decode(body, limits)?; + let (w, h) = (frame.width as usize, frame.height as usize); + // Chroma is stored at half resolution and upsampled with the same triangle + // filter libwebp uses; nearest-neighbour here costs about a decibel. + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let crop = |plane: &[u8]| -> Vec { + (0..ch) + .flat_map(|y| plane[y * frame.stride_uv..y * frame.stride_uv + cw].to_vec()) + .collect() + }; + let u_plane = crate::upsample::upsample(&crop(&frame.u), cw, ch, w, h); + let v_plane = crate::upsample::upsample(&crop(&frame.v), cw, ch, w, h); + let alpha_plane = match alpha { + Some(chunk) => Some(decode_alpha(chunk, frame.width, 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_y + 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: frame.width, + height: frame.height, + pixels: if channels == 4 { + Pixels::Rgba8(out) + } else { + Pixels::Rgb8(out) + }, + meta, + }) +} + +/// 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; + 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, + ] +} + +/// Decode an `ALPH` chunk into one byte of alpha per pixel. +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 => { + // Lossless-coded, dimensions implied; the alpha lives in green. + 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) +} + +/// Undo the alpha plane's spatial filter (none / horizontal / vertical / +/// gradient), in place. +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 { + // The top row has no pixel above, so it predicts from the left + // whatever the filter says, and the left column from above. + 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]); + } + } +} + +/// EXIF orientation out of a bare TIFF block (no `Exif\0\0` prefix here). +fn exif_orientation(data: &[u8]) -> Option { + let little = match data.get(..2)? { + b"II" => true, + b"MM" => false, + _ => return None, + }; + let u16_at = |at: usize| -> Option { + let b = data.get(at..at + 2)?; + Some(if little { + u16::from_le_bytes([b[0], b[1]]) + } else { + u16::from_be_bytes([b[0], b[1]]) + }) + }; + let u32_at = |at: usize| -> Option { + let b = data.get(at..at + 4)?; + Some(if little { + u32::from_le_bytes([b[0], b[1], b[2], b[3]]) + } else { + u32::from_be_bytes([b[0], b[1], b[2], b[3]]) + }) + }; + if u16_at(2)? != 42 { + return None; + } + let ifd = u32_at(4)? as usize; + let count = usize::from(u16_at(ifd)?); + for i in 0..count { + let entry = ifd + 2 + i * 12; + if u16_at(entry)? == 0x0112 { + let value = u16_at(entry + 8)?; + return (1..=8).contains(&value).then_some(value as u8); + } + } + None +} + +#[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() { + // Horizontal filter: each stored byte is a difference from the left. + let mut plane = vec![10u8, 5, 250, 1]; + unfilter_alpha(&mut plane, 4, 1, 1); + assert_eq!(plane, vec![10, 15, 9, 10]); + } +} diff --git a/crates/ec-image/src/webp/vp8.rs b/crates/ec-image/src/webp/vp8.rs new file mode 100644 index 00000000..922eb2d7 --- /dev/null +++ b/crates/ec-image/src/webp/vp8.rs @@ -0,0 +1,1612 @@ +//! VP8 key frame decoding (RFC 6386), which is all a still WebP contains. +//! +//! A `VP8 ` chunk in a still image is one key frame: intra prediction only, no +//! reference buffers and no motion vectors. Everything else the frame format +//! carries is here — the boolean entropy decoder, segmentation, per-partition +//! token decoding, the WHT/DCT inversions, all sixteen prediction modes and +//! both loop filters — because a key frame uses all of it. +//! +//! Inter-frame syntax (motion vectors, reference selection, sub-pixel +//! interpolation) is deliberately absent: this crate decodes stills, and a +//! decoder that pretends to accept an inter frame it cannot reconstruct is +//! worse than one that names the refusal. + +use super::vp8_tables::{ + AC_QLOOKUP, COEFF_BANDS, COEFF_UPDATE_PROBS, DC_QLOOKUP, DEFAULT_COEFF_PROBS, KF_BMODE_PROBS, + ZIGZAG, +}; +use crate::Limits; +use ec_core::{Error, Result}; + +/// 16x16 luma / 8x8 chroma prediction modes. +const DC_PRED: usize = 0; +const V_PRED: usize = 1; +const H_PRED: usize = 2; +const TM_PRED: usize = 3; +const B_PRED: usize = 4; + +/// Trees are flat arrays: a positive entry is the next node, anything else is +/// the leaf value negated (so leaf 0 encodes as 0, which is never a node). +const KF_YMODE_TREE: [i8; 8] = [-(B_PRED as i8), 2, 4, 6, 0, -1, -2, -3]; +const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128]; +const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; +const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183]; +const BMODE_TREE: [i8; 18] = [ + 0, 2, -1, 4, -2, 6, 8, 12, -3, 10, -5, -6, -4, 14, -7, 16, -8, -9, +]; +const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3]; +const COEFF_TREE: [i8; 22] = [ + -11, 2, 0, 4, -1, 6, 8, 12, -2, 10, -3, -4, 14, 16, -5, -6, 18, 20, -7, -8, -9, -10, +]; + +/// Extra-bit probabilities for the six "category" tokens. +const PCAT: [&[u8]; 6] = [ + &[159], + &[165, 145], + &[173, 148, 140], + &[176, 155, 140, 135], + &[180, 157, 141, 134, 130], + &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129], +]; +/// Smallest value each category token stands for. +const CAT_BASE: [i32; 6] = [5, 7, 11, 19, 35, 67]; + +/// Subblock modes, in the enumeration order the trees and tables use. +const B_DC_PRED: usize = 0; +const B_TM_PRED: usize = 1; +const B_VE_PRED: usize = 2; +const B_HE_PRED: usize = 3; + +/// The boolean entropy decoder of RFC 6386 section 7.3. +pub struct BoolDecoder<'a> { + data: &'a [u8], + at: usize, + range: u32, + value: u32, + bit_count: i32, +} + +impl<'a> BoolDecoder<'a> { + /// Start decoding at the beginning of `data`. + pub fn new(data: &'a [u8]) -> BoolDecoder<'a> { + let mut value = 0u32; + for i in 0..2 { + value = (value << 8) | u32::from(data.get(i).copied().unwrap_or(0)); + } + BoolDecoder { + data, + at: 2, + range: 255, + value, + bit_count: 0, + } + } + + /// One bool with probability `prob / 256` of being zero. + pub fn bool(&mut self, prob: u8) -> u32 { + let split = 1 + (((self.range - 1) * u32::from(prob)) >> 8); + let big_split = split << 8; + let bit = if self.value >= big_split { + self.range -= split; + self.value -= big_split; + 1 + } else { + self.range = split; + 0 + }; + while self.range < 128 { + self.value <<= 1; + self.range <<= 1; + self.bit_count += 1; + if self.bit_count == 8 { + self.bit_count = 0; + // Past the end the decoder reads zeros; a truncated partition + // then produces a wrong picture, never a panic. + self.value |= u32::from(self.data.get(self.at).copied().unwrap_or(0)); + self.at += 1; + } + } + bit + } + + /// `n`-bit literal, high bit first, each bit at probability 128. + pub fn literal(&mut self, n: u32) -> u32 { + let mut v = 0; + for _ in 0..n { + v = (v << 1) + self.bool(128); + } + v + } + + /// A magnitude-and-sign field: `flag ? +/- L(n) : 0`. + fn signed(&mut self, n: u32) -> i32 { + let magnitude = self.literal(n) as i32; + if self.bool(128) == 1 { + -magnitude + } else { + magnitude + } + } + + /// Optional magnitude-and-sign field. + fn maybe_signed(&mut self, n: u32) -> i32 { + if self.bool(128) == 1 { + self.signed(n) + } else { + 0 + } + } + + /// Walk a tree, reading one bool per node. + fn tree(&mut self, tree: &[i8], probs: &[u8], start: usize) -> usize { + let mut i = start; + loop { + let bit = self.bool(probs[i >> 1]) as usize; + let next = tree[i + bit]; + if next > 0 { + i = next as usize; + } else { + return (-next) as usize; + } + } + } + + /// True once the decoder has read past the end of its partition. + fn exhausted(&self) -> bool { + self.at > self.data.len() + 2 + } +} + +/// Per-segment quantizer factors: `[dc, ac]` for Y, Y2 and chroma. +#[derive(Clone, Copy, Default)] +struct Dequant { + y: [i32; 2], + y2: [i32; 2], + uv: [i32; 2], +} + +/// Everything the frame header set up. +struct Header { + segmentation: bool, + update_map: bool, + segment_probs: [u8; 3], + filter_simple: bool, + filter_level: i32, + sharpness: i32, + delta_enabled: bool, + ref_delta: [i32; 4], + mode_delta: [i32; 4], + segment_lf: [i32; 4], + segment_lf_absolute: bool, + dequant: [Dequant; 4], + coeff_probs: [[[[u8; 11]; 3]; 8]; 4], + skip_enabled: bool, + skip_prob: u8, +} + +/// What one macroblock decided, kept for the loop filter pass. +#[derive(Clone, Copy)] +struct MbInfo { + y_mode: usize, + segment: usize, + has_coeffs: bool, +} + +/// A decoded key frame's planes, cropped to the visible picture. +pub struct Frame { + /// Visible width. + pub width: u32, + /// Visible height. + pub height: u32, + /// Luma plane, `stride_y` bytes per row. + pub y: Vec, + /// U plane, `stride_uv` bytes per row. + pub u: Vec, + /// V plane, `stride_uv` bytes per row. + pub v: Vec, + /// Bytes per luma row. + pub stride_y: usize, + /// Bytes per chroma row. + pub stride_uv: usize, +} + +/// Width, height and scale codes from the uncompressed chunk. +pub fn dimensions(data: &[u8]) -> Result<(u32, u32)> { + let head = data + .get(..10) + .ok_or_else(|| Error::corrupt("VP8: frame shorter than its header"))?; + let tag = u32::from(head[0]) | (u32::from(head[1]) << 8) | (u32::from(head[2]) << 16); + if tag & 1 != 0 { + return Err(Error::unsupported( + "VP8 inter frame in a still image", + "a still WebP carries one key frame; there is no reference to predict from", + )); + } + if head[3..6] != [0x9d, 0x01, 0x2a] { + return Err(Error::corrupt("VP8: bad key frame start code")); + } + let width = u32::from(u16::from_le_bytes([head[6], head[7]])) & 0x3fff; + let height = u32::from(u16::from_le_bytes([head[8], head[9]])) & 0x3fff; + Ok((width, height)) +} + +/// Decode one VP8 key frame. +pub fn decode(data: &[u8], limits: Limits) -> Result { + let (width, height) = dimensions(data)?; + limits.check(width, height)?; + let tag = u32::from(data[0]) | (u32::from(data[1]) << 8) | (u32::from(data[2]) << 16); + let first_part_size = ((tag >> 5) & 0x7ffff) as usize; + let body = data + .get(10..) + .ok_or_else(|| Error::corrupt("VP8: no frame body"))?; + let first = body + .get(..first_part_size) + .ok_or_else(|| Error::corrupt("VP8: first partition runs past the chunk"))?; + let mut bd = BoolDecoder::new(first); + + let _color_space = bd.literal(1); + let _clamping = bd.literal(1); + let (header, partition_count) = read_header(&mut bd)?; + + // Token partitions follow the first one, preceded by their sizes. + let rest = &body[first_part_size..]; + let partitions = split_partitions(rest, partition_count)?; + + let mb_cols = (width as usize).div_ceil(16); + let mb_rows = (height as usize).div_ceil(16); + let stride_y = mb_cols * 16; + let stride_uv = mb_cols * 8; + let mut frame = Frame { + width, + height, + y: vec![0; stride_y * mb_rows * 16], + u: vec![0; stride_uv * mb_rows * 8], + v: vec![0; stride_uv * mb_rows * 8], + stride_y, + stride_uv, + }; + + let mut token_decoders: Vec> = + partitions.iter().map(|p| BoolDecoder::new(p)).collect(); + let mut above_bmodes = vec![B_DC_PRED; mb_cols * 4]; + let mut above_nz = vec![[0u8; 9]; mb_cols]; + let mut infos = Vec::with_capacity(mb_cols * mb_rows); + let mut coeffs = [[0i16; 16]; 25]; + let mut bmodes = [B_DC_PRED; 16]; + + for mb_y in 0..mb_rows { + let mut left_bmodes = [B_DC_PRED; 4]; + let mut left_nz = [0u8; 9]; + for mb_x in 0..mb_cols { + // Prediction record: segment, skip flag, then the modes. + let segment = if header.segmentation && header.update_map { + bd.tree(&SEGMENT_TREE, &header.segment_probs, 0) + } else { + 0 + }; + let skip = header.skip_enabled && bd.bool(header.skip_prob) == 1; + let y_mode = bd.tree(&KF_YMODE_TREE, &KF_YMODE_PROBS, 0); + if y_mode == B_PRED { + for by in 0..4 { + for bx in 0..4 { + let above = if by == 0 { + above_bmodes[mb_x * 4 + bx] + } else { + bmodes[(by - 1) * 4 + bx] + }; + let left = if bx == 0 { + left_bmodes[by] + } else { + bmodes[by * 4 + bx - 1] + }; + bmodes[by * 4 + bx] = bd.tree(&BMODE_TREE, &KF_BMODE_PROBS[above][left], 0); + } + } + } else { + // A whole-macroblock mode still predicts the *next* + // macroblock's subblock modes, through this equivalence. + let implied = match y_mode { + V_PRED => B_VE_PRED, + H_PRED => B_HE_PRED, + TM_PRED => B_TM_PRED, + _ => B_DC_PRED, + }; + bmodes = [implied; 16]; + } + let uv_mode = bd.tree(&UV_MODE_TREE, &KF_UV_MODE_PROBS, 0); + above_bmodes[mb_x * 4..mb_x * 4 + 4].copy_from_slice(&bmodes[12..16]); + left_bmodes = [bmodes[3], bmodes[7], bmodes[11], bmodes[15]]; + + // Residual record, from this row's token partition. + let tokens = &mut token_decoders[mb_y % partitions.len()]; + let has_y2 = y_mode != B_PRED; + let mut has_coeffs = false; + for block in coeffs.iter_mut() { + block.fill(0); + } + if skip { + left_nz[..8].fill(0); + above_nz[mb_x][..8].fill(0); + if has_y2 { + left_nz[8] = 0; + above_nz[mb_x][8] = 0; + } + } else { + has_coeffs = decode_residual( + tokens, + &header, + header.dequant[segment], + has_y2, + &mut coeffs, + &mut left_nz, + &mut above_nz[mb_x], + )?; + } + + reconstruct( + &mut frame, + mb_x, + mb_y, + mb_cols, + mb_rows, + y_mode, + uv_mode, + &bmodes, + &mut coeffs, + has_y2, + ); + infos.push(MbInfo { + y_mode, + segment, + has_coeffs, + }); + if bd.exhausted() { + return Err(Error::corrupt("VP8: first partition ran out of data")); + } + } + } + + if header.filter_level > 0 { + loop_filter(&mut frame, &header, &infos, mb_cols, mb_rows); + } + Ok(frame) +} + +/// Read the frame header; returns it with the token partition count. +fn read_header(bd: &mut BoolDecoder<'_>) -> Result<(Header, usize)> { + let mut header = Header { + segmentation: false, + update_map: false, + segment_probs: [255; 3], + filter_simple: false, + filter_level: 0, + sharpness: 0, + delta_enabled: false, + ref_delta: [0; 4], + mode_delta: [0; 4], + segment_lf: [0; 4], + segment_lf_absolute: false, + dequant: [Dequant::default(); 4], + coeff_probs: DEFAULT_COEFF_PROBS, + skip_enabled: false, + skip_prob: 0, + }; + let mut segment_quant = [0i32; 4]; + + header.segmentation = bd.literal(1) == 1; + if header.segmentation { + header.update_map = bd.literal(1) == 1; + let update_data = bd.literal(1) == 1; + if update_data { + header.segment_lf_absolute = bd.literal(1) == 1; + for q in &mut segment_quant { + *q = bd.maybe_signed(7); + } + for lf in &mut header.segment_lf { + *lf = bd.maybe_signed(6); + } + } + if header.update_map { + for p in &mut header.segment_probs { + *p = if bd.literal(1) == 1 { + bd.literal(8) as u8 + } else { + 255 + }; + } + } + } + + header.filter_simple = bd.literal(1) == 1; + header.filter_level = bd.literal(6) as i32; + header.sharpness = bd.literal(3) as i32; + header.delta_enabled = bd.literal(1) == 1; + if header.delta_enabled && bd.literal(1) == 1 { + for d in &mut header.ref_delta { + if bd.literal(1) == 1 { + *d = bd.signed(6); + } + } + for d in &mut header.mode_delta { + if bd.literal(1) == 1 { + *d = bd.signed(6); + } + } + } + + let partition_count = 1usize << bd.literal(2); + + // Quantizer indices, then the six factors per segment. + let base = bd.literal(7) as i32; + let y_dc = bd.maybe_signed(4); + let y2_dc = bd.maybe_signed(4); + let y2_ac = bd.maybe_signed(4); + let uv_dc = bd.maybe_signed(4); + let uv_ac = bd.maybe_signed(4); + for segment in 0..4 { + let q = if header.segmentation { + if header.segment_lf_absolute { + segment_quant[segment] + } else { + base + segment_quant[segment] + } + } else { + base + }; + header.dequant[segment] = Dequant { + y: [dc_q(q + y_dc), ac_q(q)], + y2: [dc_q(q + y2_dc) * 2, (ac_q(q + y2_ac) * 155 / 100).max(8)], + uv: [dc_q(q + uv_dc).min(132), ac_q(q + uv_ac)], + }; + } + + let _refresh_entropy = bd.literal(1); + for i in 0..4 { + for j in 0..8 { + for k in 0..3 { + for t in 0..11 { + if bd.bool(COEFF_UPDATE_PROBS[i][j][k][t]) == 1 { + header.coeff_probs[i][j][k][t] = bd.literal(8) as u8; + } + } + } + } + } + header.skip_enabled = bd.literal(1) == 1; + if header.skip_enabled { + header.skip_prob = bd.literal(8) as u8; + } + Ok((header, partition_count)) +} + +fn clamp_q(q: i32) -> usize { + q.clamp(0, 127) as usize +} + +fn dc_q(q: i32) -> i32 { + DC_QLOOKUP[clamp_q(q)] +} + +fn ac_q(q: i32) -> i32 { + AC_QLOOKUP[clamp_q(q)] +} + +/// Split the token partitions, whose sizes precede them three bytes each. +fn split_partitions(data: &[u8], count: usize) -> Result> { + let table = (count - 1) * 3; + let body = data + .get(table..) + .ok_or_else(|| Error::corrupt("VP8: partition size table runs past the chunk"))?; + let mut parts = Vec::with_capacity(count); + let mut at = 0usize; + for i in 0..count - 1 { + let size = usize::from(data[i * 3]) + | (usize::from(data[i * 3 + 1]) << 8) + | (usize::from(data[i * 3 + 2]) << 16); + let part = body + .get(at..at + size) + .ok_or_else(|| Error::corrupt("VP8: token partition runs past the chunk"))?; + parts.push(part); + at += size; + } + parts.push(&body[at..]); + Ok(parts) +} + +/// Decode one macroblock's 25 blocks of coefficients, dequantizing as it goes. +#[allow(clippy::too_many_arguments)] +fn decode_residual( + bd: &mut BoolDecoder<'_>, + header: &Header, + dequant: Dequant, + has_y2: bool, + coeffs: &mut [[i16; 16]; 25], + left_nz: &mut [u8; 9], + above_nz: &mut [u8; 9], +) -> Result { + let mut any = false; + if has_y2 { + let ctx = usize::from(left_nz[8]) + usize::from(above_nz[8]); + let nonzero = decode_block(bd, header, 1, ctx, 0, dequant.y2, &mut coeffs[24])?; + left_nz[8] = u8::from(nonzero); + above_nz[8] = u8::from(nonzero); + any |= nonzero; + } + let (plane, first) = if has_y2 { + (0usize, 1usize) + } else { + (3usize, 0usize) + }; + for by in 0..4 { + for bx in 0..4 { + let ctx = usize::from(left_nz[by]) + usize::from(above_nz[bx]); + let nonzero = decode_block( + bd, + header, + plane, + ctx, + first, + dequant.y, + &mut coeffs[by * 4 + bx], + )?; + left_nz[by] = u8::from(nonzero); + above_nz[bx] = u8::from(nonzero); + any |= nonzero; + } + } + for (chroma, base) in [(0usize, 16usize), (1, 20)] { + for by in 0..2 { + for bx in 0..2 { + let li = 4 + chroma * 2 + by; + let ai = 4 + chroma * 2 + bx; + let ctx = usize::from(left_nz[li]) + usize::from(above_nz[ai]); + let nonzero = decode_block( + bd, + header, + 2, + ctx, + 0, + dequant.uv, + &mut coeffs[base + by * 2 + bx], + )?; + left_nz[li] = u8::from(nonzero); + above_nz[ai] = u8::from(nonzero); + any |= nonzero; + } + } + } + if bd.exhausted() { + return Err(Error::corrupt("VP8: token partition ran out of data")); + } + Ok(any) +} + +/// One 4x4 block of tokens, written out dequantized in raster order. +fn decode_block( + bd: &mut BoolDecoder<'_>, + header: &Header, + plane: usize, + ctx: usize, + first: usize, + factors: [i32; 2], + out: &mut [i16; 16], +) -> Result { + let mut ctx = ctx; + let mut nonzero = false; + let mut index = first; + let mut skip_eob = false; + while index < 16 { + let probs = &header.coeff_probs[plane][COEFF_BANDS[index]][ctx]; + let token = bd.tree(&COEFF_TREE, probs, if skip_eob { 2 } else { 0 }); + if token == 11 { + break; + } + let value = match token { + 0 => 0, + 1..=4 => token as i32, + _ => { + let cat = token - 5; + let mut extra = 0i32; + for &p in PCAT[cat] { + extra = 2 * extra + bd.bool(p) as i32; + } + CAT_BASE[cat] + extra + } + }; + ctx = match value { + 0 => 0, + 1 => 1, + _ => 2, + }; + skip_eob = value == 0; + if value != 0 { + nonzero = true; + let signed = if bd.bool(128) == 1 { -value } else { value }; + let factor = if index == 0 { factors[0] } else { factors[1] }; + out[ZIGZAG[index]] = (signed * factor).clamp(-32768, 32767) as i16; + } + index += 1; + } + Ok(nonzero) +} + +/// Inverse Walsh-Hadamard: the Y2 block's values become the Y blocks' DCs. +fn inverse_wht(input: &[i16; 16], coeffs: &mut [[i16; 16]; 25]) { + let mut tmp = [0i32; 16]; + for i in 0..4 { + let a1 = i32::from(input[i]) + i32::from(input[12 + i]); + let b1 = i32::from(input[4 + i]) + i32::from(input[8 + i]); + let c1 = i32::from(input[4 + i]) - i32::from(input[8 + i]); + let d1 = i32::from(input[i]) - i32::from(input[12 + i]); + tmp[i] = a1 + b1; + tmp[4 + i] = c1 + d1; + tmp[8 + i] = a1 - b1; + tmp[12 + i] = d1 - c1; + } + for i in 0..4 { + let a1 = tmp[i * 4] + tmp[i * 4 + 3]; + let b1 = tmp[i * 4 + 1] + tmp[i * 4 + 2]; + let c1 = tmp[i * 4 + 1] - tmp[i * 4 + 2]; + let d1 = tmp[i * 4] - tmp[i * 4 + 3]; + coeffs[i * 4][0] = ((a1 + b1 + 3) >> 3) as i16; + coeffs[i * 4 + 1][0] = ((c1 + d1 + 3) >> 3) as i16; + coeffs[i * 4 + 2][0] = ((a1 - b1 + 3) >> 3) as i16; + coeffs[i * 4 + 3][0] = ((d1 - c1 + 3) >> 3) as i16; + } +} + +const COS_PI8_SQRT2_MINUS1: i32 = 20091; +const SIN_PI8_SQRT2: i32 = 35468; + +/// The 4x4 inverse DCT of RFC 6386 section 14.4, bit-exact as specified. +fn inverse_dct(block: &[i16; 16]) -> [i32; 16] { + let mut tmp = [0i32; 16]; + for i in 0..4 { + let ip = |k: usize| i32::from(block[k * 4 + i]); + let a1 = ip(0) + ip(2); + let b1 = ip(0) - ip(2); + let t1 = (ip(1) * SIN_PI8_SQRT2) >> 16; + let t2 = ip(3) + ((ip(3) * COS_PI8_SQRT2_MINUS1) >> 16); + let c1 = t1 - t2; + let t1 = ip(1) + ((ip(1) * COS_PI8_SQRT2_MINUS1) >> 16); + let t2 = (ip(3) * SIN_PI8_SQRT2) >> 16; + let d1 = t1 + t2; + tmp[i] = a1 + d1; + tmp[12 + i] = a1 - d1; + tmp[4 + i] = b1 + c1; + tmp[8 + i] = b1 - c1; + } + let mut out = [0i32; 16]; + for i in 0..4 { + let ip = |k: usize| tmp[i * 4 + k]; + let a1 = ip(0) + ip(2); + let b1 = ip(0) - ip(2); + let t1 = (ip(1) * SIN_PI8_SQRT2) >> 16; + let t2 = ip(3) + ((ip(3) * COS_PI8_SQRT2_MINUS1) >> 16); + let c1 = t1 - t2; + let t1 = ip(1) + ((ip(1) * COS_PI8_SQRT2_MINUS1) >> 16); + let t2 = (ip(3) * SIN_PI8_SQRT2) >> 16; + let d1 = t1 + t2; + out[i * 4] = (a1 + d1 + 4) >> 3; + out[i * 4 + 3] = (a1 - d1 + 4) >> 3; + out[i * 4 + 1] = (b1 + c1 + 4) >> 3; + out[i * 4 + 2] = (b1 - c1 + 4) >> 3; + } + out +} + +/// The macroblock's working buffer: one row of "above" pixels (with the four +/// above-right ones a subblock may reach for) and one column of "left" ones, +/// surrounding the 16x16 luma and 8x8 chroma blocks being built. +struct Work { + y: [[u8; 21]; 17], + u: [[u8; 9]; 9], + v: [[u8; 9]; 9], +} + +#[allow(clippy::too_many_arguments)] +fn reconstruct( + frame: &mut Frame, + mb_x: usize, + mb_y: usize, + mb_cols: usize, + _mb_rows: usize, + y_mode: usize, + uv_mode: usize, + bmodes: &[usize; 16], + coeffs: &mut [[i16; 16]; 25], + has_y2: bool, +) { + if has_y2 { + let y2 = coeffs[24]; + inverse_wht(&y2, coeffs); + } + let mut work = Work { + y: [[0; 21]; 17], + u: [[0; 9]; 9], + v: [[0; 9]; 9], + }; + load_edges(frame, &mut work, mb_x, mb_y, mb_cols); + + if y_mode == B_PRED { + for by in 0..4 { + for bx in 0..4 { + predict_subblock(&mut work, bx, by, bmodes[by * 4 + bx]); + add_residual_4x4(&mut work.y, by * 4 + 1, bx * 4 + 1, &coeffs[by * 4 + bx]); + } + } + } else { + predict_luma_16x16(&mut work, y_mode, mb_x, mb_y); + for by in 0..4 { + for bx in 0..4 { + add_residual_4x4(&mut work.y, by * 4 + 1, bx * 4 + 1, &coeffs[by * 4 + bx]); + } + } + } + predict_chroma(&mut work, uv_mode, mb_x, mb_y); + for by in 0..2 { + for bx in 0..2 { + add_residual_4x4_c( + &mut work.u, + by * 4 + 1, + bx * 4 + 1, + &coeffs[16 + by * 2 + bx], + ); + add_residual_4x4_c( + &mut work.v, + by * 4 + 1, + bx * 4 + 1, + &coeffs[20 + by * 2 + bx], + ); + } + } + store_macroblock(frame, &work, mb_x, mb_y); +} + +/// Fill the working buffer's borders from the already-reconstructed frame, +/// using 127 above the picture and 129 to its left as the format requires. +fn load_edges(frame: &Frame, work: &mut Work, mb_x: usize, mb_y: usize, mb_cols: usize) { + let sy = frame.stride_y; + let suv = frame.stride_uv; + // Luma above row plus four above-right pixels. + if mb_y == 0 { + work.y[0] = [127; 21]; + } else { + let row = (mb_y * 16 - 1) * sy; + work.y[0][0] = if mb_x == 0 { + 129 + } else { + frame.y[row + mb_x * 16 - 1] + }; + for i in 0..16 { + work.y[0][1 + i] = frame.y[row + mb_x * 16 + i]; + } + for i in 0..4 { + work.y[0][17 + i] = if mb_x + 1 < mb_cols { + frame.y[row + mb_x * 16 + 16 + i] + } else { + // The rightmost macroblock reuses the last visible pixel of + // the row above, per section 12.3. + frame.y[row + mb_x * 16 + 15] + }; + } + } + for r in 0..16 { + work.y[r + 1][0] = if mb_x == 0 { + 129 + } else { + frame.y[(mb_y * 16 + r) * sy + mb_x * 16 - 1] + }; + } + // Chroma above rows and left columns. + for (plane, buf) in [(&frame.u, &mut work.u), (&frame.v, &mut work.v)] { + if mb_y == 0 { + buf[0] = [127; 9]; + } else { + let row = (mb_y * 8 - 1) * suv; + buf[0][0] = if mb_x == 0 { + 129 + } else { + plane[row + mb_x * 8 - 1] + }; + for i in 0..8 { + buf[0][1 + i] = plane[row + mb_x * 8 + i]; + } + } + for r in 0..8 { + buf[r + 1][0] = if mb_x == 0 { + 129 + } else { + plane[(mb_y * 8 + r) * suv + mb_x * 8 - 1] + }; + } + } +} + +fn store_macroblock(frame: &mut Frame, work: &Work, mb_x: usize, mb_y: usize) { + let sy = frame.stride_y; + let suv = frame.stride_uv; + for r in 0..16 { + let dst = (mb_y * 16 + r) * sy + mb_x * 16; + frame.y[dst..dst + 16].copy_from_slice(&work.y[r + 1][1..17]); + } + for r in 0..8 { + let dst = (mb_y * 8 + r) * suv + mb_x * 8; + frame.u[dst..dst + 8].copy_from_slice(&work.u[r + 1][1..9]); + frame.v[dst..dst + 8].copy_from_slice(&work.v[r + 1][1..9]); + } +} + +fn add_residual_4x4(buf: &mut [[u8; 21]; 17], row: usize, col: usize, block: &[i16; 16]) { + if block.iter().all(|&c| c == 0) { + return; + } + let residue = inverse_dct(block); + for r in 0..4 { + for c in 0..4 { + let v = i32::from(buf[row + r][col + c]) + residue[r * 4 + c]; + buf[row + r][col + c] = v.clamp(0, 255) as u8; + } + } +} + +fn add_residual_4x4_c(buf: &mut [[u8; 9]; 9], row: usize, col: usize, block: &[i16; 16]) { + if block.iter().all(|&c| c == 0) { + return; + } + let residue = inverse_dct(block); + for r in 0..4 { + for c in 0..4 { + let v = i32::from(buf[row + r][col + c]) + residue[r * 4 + c]; + buf[row + r][col + c] = v.clamp(0, 255) as u8; + } + } +} + +/// DC prediction's rounded average, over whichever edges exist. +fn dc_value(above: &[u8], left: &[u8], have_above: bool, have_left: bool) -> u8 { + let mut sum = 0u32; + let mut count = 0u32; + if have_above { + sum += above.iter().map(|&p| u32::from(p)).sum::(); + count += above.len() as u32; + } + if have_left { + sum += left.iter().map(|&p| u32::from(p)).sum::(); + count += left.len() as u32; + } + if count == 0 { + return 128; + } + let shift = count.trailing_zeros(); + ((sum + (1 << (shift - 1))) >> shift) as u8 +} + +fn predict_luma_16x16(work: &mut Work, mode: usize, mb_x: usize, mb_y: usize) { + let above: Vec = work.y[0][1..17].to_vec(); + let left: Vec = (0..16).map(|r| work.y[r + 1][0]).collect(); + let corner = work.y[0][0]; + let dc = dc_value(&above, &left, mb_y > 0, mb_x > 0); + for r in 0..16 { + for c in 0..16 { + work.y[r + 1][c + 1] = match mode { + V_PRED => above[c], + H_PRED => left[r], + TM_PRED => (i32::from(left[r]) + i32::from(above[c]) - i32::from(corner)) + .clamp(0, 255) as u8, + DC_PRED => dc, + _ => dc, + }; + } + } +} + +fn predict_chroma(work: &mut Work, mode: usize, mb_x: usize, mb_y: usize) { + for buf in [&mut work.u, &mut work.v] { + let above: Vec = buf[0][1..9].to_vec(); + let left: Vec = (0..8).map(|r| buf[r + 1][0]).collect(); + let corner = buf[0][0]; + let dc = dc_value(&above, &left, mb_y > 0, mb_x > 0); + for r in 0..8 { + for c in 0..8 { + buf[r + 1][c + 1] = match mode { + V_PRED => above[c], + H_PRED => left[r], + TM_PRED => (i32::from(left[r]) + i32::from(above[c]) - i32::from(corner)) + .clamp(0, 255) as u8, + DC_PRED => dc, + _ => dc, + }; + } + } + } +} + +fn avg3(x: u8, y: u8, z: u8) -> u8 { + ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8 +} + +fn avg2(x: u8, y: u8) -> u8 { + ((u32::from(x) + u32::from(y) + 1) >> 1) as u8 +} + +/// The ten 4x4 subblock predictions of section 12.3. +fn predict_subblock(work: &mut Work, bx: usize, by: usize, mode: usize) { + let row = by * 4; + let col = bx * 4; + // A[-1] is P; A[0..8] the above row and its four right-hand neighbours. + let mut a = [0u8; 9]; + a[0] = work.y[row][col]; + for i in 0..8 { + // Subblocks on the macroblock's right edge take their above-right from + // row -1 whatever their own row is: the pixels to their upper right + // have not been reconstructed yet. + a[1 + i] = if bx == 3 && i >= 4 { + work.y[0][17 + (i - 4)] + } else { + work.y[row][col + 1 + i] + }; + } + let l = [ + work.y[row + 1][col], + work.y[row + 2][col], + work.y[row + 3][col], + work.y[row + 4][col], + ]; + let p = a[0]; + let above = &a[1..9]; + // E[0..9]: the left column reversed, then P, then the above row. + let e = [ + l[3], l[2], l[1], l[0], p, above[0], above[1], above[2], above[3], + ]; + let mut b = [[0u8; 4]; 4]; + match mode { + B_DC_PRED => { + let mut v = 4u32; + for i in 0..4 { + v += u32::from(above[i]) + u32::from(l[i]); + } + let v = (v >> 3) as u8; + b = [[v; 4]; 4]; + } + B_TM_PRED => { + for r in 0..4 { + for c in 0..4 { + b[r][c] = + (i32::from(l[r]) + i32::from(above[c]) - i32::from(p)).clamp(0, 255) as u8; + } + } + } + B_VE_PRED => { + for c in 0..4 { + let v = avg3( + if c == 0 { p } else { above[c - 1] }, + above[c], + above[c + 1], + ); + for r in 0..4 { + b[r][c] = v; + } + } + } + B_HE_PRED => { + let values = [ + avg3(p, l[0], l[1]), + avg3(l[0], l[1], l[2]), + avg3(l[1], l[2], l[3]), + avg3(l[2], l[3], l[3]), + ]; + for r in 0..4 { + b[r] = [values[r]; 4]; + } + } + 4 => { + // B_LD_PRED: 45 degrees down-left. + let d = |i: usize| avg3(above[i - 1], above[i], above[i + 1]); + b[0][0] = d(1); + b[0][1] = d(2); + b[1][0] = d(2); + b[0][2] = d(3); + b[1][1] = d(3); + b[2][0] = d(3); + b[0][3] = d(4); + b[1][2] = d(4); + b[2][1] = d(4); + b[3][0] = d(4); + b[1][3] = d(5); + b[2][2] = d(5); + b[3][1] = d(5); + b[2][3] = d(6); + b[3][2] = d(6); + b[3][3] = avg3(above[6], above[7], above[7]); + } + 5 => { + // B_RD_PRED: 45 degrees down-right. + let d = |i: usize| avg3(e[i - 1], e[i], e[i + 1]); + b[3][0] = d(1); + b[3][1] = d(2); + b[2][0] = d(2); + b[3][2] = d(3); + b[2][1] = d(3); + b[1][0] = d(3); + b[3][3] = d(4); + b[2][2] = d(4); + b[1][1] = d(4); + b[0][0] = d(4); + b[2][3] = d(5); + b[1][2] = d(5); + b[0][1] = d(5); + b[1][3] = d(6); + b[0][2] = d(6); + b[0][3] = d(7); + } + 6 => { + // B_VR_PRED. + let d3 = |i: usize| avg3(e[i - 1], e[i], e[i + 1]); + let d2 = |i: usize| avg2(e[i], e[i + 1]); + b[3][0] = d3(2); + b[2][0] = d3(3); + b[3][1] = d3(4); + b[1][0] = d3(4); + b[2][1] = d2(4); + b[0][0] = d2(4); + b[3][2] = d3(5); + b[1][1] = d3(5); + b[2][2] = d2(5); + b[0][1] = d2(5); + b[3][3] = d3(6); + b[1][2] = d3(6); + b[2][3] = d2(6); + b[0][2] = d2(6); + b[1][3] = d3(7); + b[0][3] = d2(7); + } + 7 => { + // B_VL_PRED. + let d3 = |i: usize| avg3(above[i - 1], above[i], above[i + 1]); + let d2 = |i: usize| avg2(above[i], above[i + 1]); + b[0][0] = d2(0); + b[1][0] = d3(1); + b[2][0] = d2(1); + b[0][1] = d2(1); + b[1][1] = d3(2); + b[3][0] = d3(2); + b[2][1] = d2(2); + b[0][2] = d2(2); + b[3][1] = d3(3); + b[1][2] = d3(3); + b[2][2] = d2(3); + b[0][3] = d2(3); + b[3][2] = d3(4); + b[1][3] = d3(4); + b[2][3] = d3(5); + b[3][3] = d3(6); + } + 8 => { + // B_HD_PRED. + let d3 = |i: usize| avg3(e[i - 1], e[i], e[i + 1]); + let d2 = |i: usize| avg2(e[i], e[i + 1]); + b[3][0] = d2(0); + b[3][1] = d3(1); + b[2][0] = d2(1); + b[3][2] = d2(1); + b[2][1] = d3(2); + b[3][3] = d3(2); + b[2][2] = d2(2); + b[1][0] = d2(2); + b[2][3] = d3(3); + b[1][1] = d3(3); + b[1][2] = d2(3); + b[0][0] = d2(3); + b[1][3] = d3(4); + b[0][1] = d3(4); + b[0][2] = d3(5); + b[0][3] = d3(6); + } + _ => { + // B_HU_PRED. + b[0][0] = avg2(l[0], l[1]); + b[0][1] = avg3(l[0], l[1], l[2]); + b[0][2] = avg2(l[1], l[2]); + b[1][0] = avg2(l[1], l[2]); + b[0][3] = avg3(l[1], l[2], l[3]); + b[1][1] = avg3(l[1], l[2], l[3]); + b[1][2] = avg2(l[2], l[3]); + b[2][0] = avg2(l[2], l[3]); + b[1][3] = avg3(l[2], l[3], l[3]); + b[2][1] = avg3(l[2], l[3], l[3]); + b[2][2] = l[3]; + b[2][3] = l[3]; + b[3][0] = l[3]; + b[3][1] = l[3]; + b[3][2] = l[3]; + b[3][3] = l[3]; + } + } + for r in 0..4 { + for c in 0..4 { + work.y[row + 1 + r][col + 1 + c] = b[r][c]; + } + } +} + +// ---- Loop filter (section 15) -------------------------------------------- + +fn c8(v: i32) -> i32 { + v.clamp(-128, 127) +} + +fn u2s(v: u8) -> i32 { + i32::from(v) - 128 +} + +fn s2u(v: i32) -> u8 { + (c8(v) + 128) as u8 +} + +/// The shared 2-or-4-tap adjustment; returns the value the wider filters need. +fn common_adjust(use_outer: bool, plane: &mut [u8], q0: usize, step: usize) -> i32 { + let p1 = u2s(plane[q0 - 2 * step]); + let p0 = u2s(plane[q0 - step]); + let q0v = u2s(plane[q0]); + let q1 = u2s(plane[q0 + step]); + let a = c8((if use_outer { c8(p1 - q1) } else { 0 }) + 3 * (q0v - p0)); + let b = c8(a + 3) >> 3; + let a = c8(a + 4) >> 3; + plane[q0] = s2u(q0v - a); + plane[q0 - step] = s2u(p0 + b); + a +} + +fn simple_segment(edge_limit: i32, plane: &mut [u8], q0: usize, step: usize) { + let p1 = i32::from(plane[q0 - 2 * step]); + let p0 = i32::from(plane[q0 - step]); + let q0v = i32::from(plane[q0]); + let q1 = i32::from(plane[q0 + step]); + if (p0 - q0v).abs() * 2 + (p1 - q1).abs() / 2 <= edge_limit { + common_adjust(true, plane, q0, step); + } +} + +fn filter_yes(interior: i32, edge: i32, plane: &[u8], q0: usize, step: usize) -> bool { + let at = |k: i32| i32::from(plane[(q0 as i32 + k * step as i32) as usize]); + let (p3, p2, p1, p0) = (at(-4), at(-3), at(-2), at(-1)); + let (q0v, q1, q2, q3) = (at(0), at(1), at(2), at(3)); + (p0 - q0v).abs() * 2 + (p1 - q1).abs() / 2 <= edge + && (p3 - p2).abs() <= interior + && (p2 - p1).abs() <= interior + && (p1 - p0).abs() <= interior + && (q3 - q2).abs() <= interior + && (q2 - q1).abs() <= interior + && (q1 - q0v).abs() <= interior +} + +fn hev(threshold: i32, plane: &[u8], q0: usize, step: usize) -> bool { + let at = |k: i32| i32::from(plane[(q0 as i32 + k * step as i32) as usize]); + (at(-2) - at(-1)).abs() > threshold || (at(1) - at(0)).abs() > threshold +} + +fn subblock_filter( + hev_threshold: i32, + interior: i32, + edge: i32, + plane: &mut [u8], + q0: usize, + step: usize, +) { + if !filter_yes(interior, edge, plane, q0, step) { + return; + } + let high = hev(hev_threshold, plane, q0, step); + let a = (common_adjust(high, plane, q0, step) + 1) >> 1; + if !high { + let q1 = u2s(plane[q0 + step]); + let p1 = u2s(plane[q0 - 2 * step]); + plane[q0 + step] = s2u(q1 - a); + plane[q0 - 2 * step] = s2u(p1 + a); + } +} + +fn mb_filter( + hev_threshold: i32, + interior: i32, + edge: i32, + plane: &mut [u8], + q0: usize, + step: usize, +) { + if !filter_yes(interior, edge, plane, q0, step) { + return; + } + if hev(hev_threshold, plane, q0, step) { + common_adjust(true, plane, q0, step); + return; + } + let p2 = u2s(plane[q0 - 3 * step]); + let p1 = u2s(plane[q0 - 2 * step]); + let p0 = u2s(plane[q0 - step]); + let q0v = u2s(plane[q0]); + let q1 = u2s(plane[q0 + step]); + let q2 = u2s(plane[q0 + 2 * step]); + let w = c8(c8(p1 - q1) + 3 * (q0v - p0)); + let a = c8((27 * w + 63) >> 7); + plane[q0] = s2u(q0v - a); + plane[q0 - step] = s2u(p0 + a); + let a = c8((18 * w + 63) >> 7); + plane[q0 + step] = s2u(q1 - a); + plane[q0 - 2 * step] = s2u(p1 + a); + let a = c8((9 * w + 63) >> 7); + plane[q0 + 2 * step] = s2u(q2 - a); + plane[q0 - 3 * step] = s2u(p2 + a); +} + +/// Per-macroblock filter strength, exactly as section 15.4 derives it. +fn filter_parameters(header: &Header, info: &MbInfo) -> (i32, i32, i32) { + let mut level = header.filter_level; + if header.segmentation { + level = if header.segment_lf_absolute { + header.segment_lf[info.segment] + } else { + level + header.segment_lf[info.segment] + }; + } + level = level.clamp(0, 63); + if header.delta_enabled { + // A key frame's every macroblock references the current frame, so the + // reference delta is always index 0 and the mode delta only applies to + // B_PRED. + level += header.ref_delta[0]; + if info.y_mode == B_PRED { + level += header.mode_delta[0]; + } + } + let level = level.clamp(0, 63); + let mut interior = level; + if header.sharpness > 0 { + interior >>= if header.sharpness > 4 { 2 } else { 1 }; + interior = interior.min(9 - header.sharpness); + } + interior = interior.max(1); + let mut hev_threshold = i32::from(level >= 15); + if level >= 40 { + hev_threshold += 1; + } + (level, interior, hev_threshold) +} + +fn loop_filter( + frame: &mut Frame, + header: &Header, + infos: &[MbInfo], + mb_cols: usize, + mb_rows: usize, +) { + let sy = frame.stride_y; + let suv = frame.stride_uv; + for mb_y in 0..mb_rows { + for mb_x in 0..mb_cols { + let info = infos[mb_y * mb_cols + mb_x]; + let (level, interior, hev_threshold) = filter_parameters(header, &info); + if level == 0 { + continue; + } + let mb_edge = (level + 2) * 2 + interior; + let sub_edge = level * 2 + interior; + // Interior edges are skipped where the macroblock has no residue + // and predicts as a whole; nothing there can have a block edge. + let skip_interior = !info.has_coeffs && info.y_mode != B_PRED; + let (yx, yy) = (mb_x * 16, mb_y * 16); + let (cx, cy) = (mb_x * 8, mb_y * 8); + + if header.filter_simple { + if mb_x > 0 { + for r in 0..16 { + simple_segment(mb_edge, &mut frame.y, (yy + r) * sy + yx, 1); + } + } + if !skip_interior { + for c in [4, 8, 12] { + for r in 0..16 { + simple_segment(sub_edge, &mut frame.y, (yy + r) * sy + yx + c, 1); + } + } + } + if mb_y > 0 { + for c in 0..16 { + simple_segment(mb_edge, &mut frame.y, yy * sy + yx + c, sy); + } + } + if !skip_interior { + for r in [4, 8, 12] { + for c in 0..16 { + simple_segment(sub_edge, &mut frame.y, (yy + r) * sy + yx + c, sy); + } + } + } + continue; + } + + if mb_x > 0 { + for r in 0..16 { + mb_filter( + hev_threshold, + interior, + mb_edge, + &mut frame.y, + (yy + r) * sy + yx, + 1, + ); + } + for r in 0..8 { + mb_filter( + hev_threshold, + interior, + mb_edge, + &mut frame.u, + (cy + r) * suv + cx, + 1, + ); + mb_filter( + hev_threshold, + interior, + mb_edge, + &mut frame.v, + (cy + r) * suv + cx, + 1, + ); + } + } + if !skip_interior { + for c in [4, 8, 12] { + for r in 0..16 { + subblock_filter( + hev_threshold, + interior, + sub_edge, + &mut frame.y, + (yy + r) * sy + yx + c, + 1, + ); + } + } + for r in 0..8 { + subblock_filter( + hev_threshold, + interior, + sub_edge, + &mut frame.u, + (cy + r) * suv + cx + 4, + 1, + ); + subblock_filter( + hev_threshold, + interior, + sub_edge, + &mut frame.v, + (cy + r) * suv + cx + 4, + 1, + ); + } + } + if mb_y > 0 { + for c in 0..16 { + mb_filter( + hev_threshold, + interior, + mb_edge, + &mut frame.y, + yy * sy + yx + c, + sy, + ); + } + for c in 0..8 { + mb_filter( + hev_threshold, + interior, + mb_edge, + &mut frame.u, + cy * suv + cx + c, + suv, + ); + mb_filter( + hev_threshold, + interior, + mb_edge, + &mut frame.v, + cy * suv + cx + c, + suv, + ); + } + } + if !skip_interior { + for r in [4, 8, 12] { + for c in 0..16 { + subblock_filter( + hev_threshold, + interior, + sub_edge, + &mut frame.y, + (yy + r) * sy + yx + c, + sy, + ); + } + } + for c in 0..8 { + subblock_filter( + hev_threshold, + interior, + sub_edge, + &mut frame.u, + (cy + 4) * suv + cx + c, + suv, + ); + subblock_filter( + hev_threshold, + interior, + sub_edge, + &mut frame.v, + (cy + 4) * suv + cx + c, + suv, + ); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The encoder of RFC 6386 section 7.3, so the decoder can be checked + /// against the thing it has to invert rather than against an assumption + /// about what the bits look like. + struct BoolEncoder { + out: Vec, + range: u32, + bottom: u32, + bit_count: i32, + } + + impl BoolEncoder { + fn new() -> BoolEncoder { + BoolEncoder { + out: Vec::new(), + range: 255, + bottom: 0, + bit_count: 24, + } + } + + fn carry(&mut self) { + let mut i = self.out.len(); + while i > 0 { + i -= 1; + if self.out[i] == 255 { + self.out[i] = 0; + } else { + self.out[i] += 1; + return; + } + } + } + + fn write(&mut self, prob: u8, value: u32) { + let split = 1 + (((self.range - 1) * u32::from(prob)) >> 8); + if value != 0 { + self.bottom += split; + self.range -= split; + } else { + self.range = split; + } + while self.range < 128 { + self.range <<= 1; + if self.bottom & (1 << 31) != 0 { + self.carry(); + } + self.bottom <<= 1; + self.bit_count -= 1; + if self.bit_count == 0 { + self.out.push((self.bottom >> 24) as u8); + self.bottom &= (1 << 24) - 1; + self.bit_count = 8; + } + } + } + + fn literal(&mut self, n: u32, value: u32) { + for i in (0..n).rev() { + self.write(128, (value >> i) & 1); + } + } + + fn finish(mut self) -> Vec { + let mut c = self.bit_count; + let mut v = self.bottom; + if v & (1u32 << (32 - c)) != 0 { + self.carry(); + } + v <<= c & 7; + c >>= 3; + while c > 0 { + v <<= 8; + c -= 1; + } + for _ in 0..4 { + self.out.push((v >> 24) as u8); + v <<= 8; + } + self.out + } + } + + #[test] + fn the_bool_decoder_inverts_the_specification_encoder() { + let probs = [128u8, 1, 255, 200, 32, 145]; + let bits: Vec = (0..600) + .map(|i: u32| (i.wrapping_mul(2_654_435_761)) >> 31) + .collect(); + let mut encoder = BoolEncoder::new(); + for (i, &bit) in bits.iter().enumerate() { + encoder.write(probs[i % probs.len()], bit); + } + encoder.literal(8, 0xb2); + encoder.literal(12, 0x4d3); + let data = encoder.finish(); + + let mut bd = BoolDecoder::new(&data); + for (i, &bit) in bits.iter().enumerate() { + assert_eq!(bd.bool(probs[i % probs.len()]), bit, "bool {i}"); + } + assert_eq!(bd.literal(8), 0xb2); + assert_eq!(bd.literal(12), 0x4d3); + } + + #[test] + fn trees_decode_their_leaves() { + // A stream of zero bits walks the leftmost branch of each tree. + let data = [0u8; 8]; + let mut bd = BoolDecoder::new(&data); + assert_eq!(bd.tree(&KF_YMODE_TREE, &KF_YMODE_PROBS, 0), B_PRED); + let mut bd = BoolDecoder::new(&data); + assert_eq!(bd.tree(&UV_MODE_TREE, &KF_UV_MODE_PROBS, 0), DC_PRED); + let mut bd = BoolDecoder::new(&data); + assert_eq!(bd.tree(&BMODE_TREE, &KF_BMODE_PROBS[0][0], 0), B_DC_PRED); + let mut bd = BoolDecoder::new(&data); + assert_eq!( + bd.tree(&COEFF_TREE, &[128; 11], 0), + 11, + "eob is the 0 branch" + ); + } + + #[test] + fn the_inverse_dct_of_a_dc_only_block_is_flat() { + let mut block = [0i16; 16]; + block[0] = 80; + let out = inverse_dct(&block); + for v in out { + assert_eq!(v, 10, "DC 80 spreads to (80 + 4) >> 3 everywhere"); + } + } + + #[test] + fn the_inverse_wht_matches_its_specification() { + let mut input = [0i16; 16]; + input[0] = 64; + let mut coeffs = [[0i16; 16]; 25]; + inverse_wht(&input, &mut coeffs); + for block in coeffs.iter().take(16) { + assert_eq!(block[0], 8, "a flat WHT spreads its DC over the 16 blocks"); + } + } + + #[test] + fn dequant_factors_follow_the_scaling_rules() { + assert_eq!(dc_q(0), 4); + assert_eq!(ac_q(127), 284); + // Y2 AC is scaled by 155/100 with a floor of 8, chroma DC caps at 132. + assert_eq!((ac_q(0) * 155 / 100).max(8), 8); + assert_eq!(dc_q(127).min(132), 132); + } +} diff --git a/crates/ec-image/src/webp/vp8_tables.rs b/crates/ec-image/src/webp/vp8_tables.rs new file mode 100644 index 00000000..be2e90fd --- /dev/null +++ b/crates/ec-image/src/webp/vp8_tables.rs @@ -0,0 +1,500 @@ +//! VP8 constant tables, generated from the RFC 6386 text by +//! `scratchpad/s40/gen_vp8_tables.py` — every value is the spec's own. +//! +//! Regenerating beats retyping: a single transposed probability shows up as a +//! plausible-looking decode that drifts from the reference several +//! macroblocks later. + +/// Keyframe subblock mode probabilities, indexed [above][left][node]. +pub const KF_BMODE_PROBS: [[[u8; 9]; 10]; 10] = [ + [ + [231, 120, 48, 89, 115, 113, 120, 152, 112], + [152, 179, 64, 126, 170, 118, 46, 70, 95], + [175, 69, 143, 80, 85, 82, 72, 155, 103], + [56, 58, 10, 171, 218, 189, 17, 13, 152], + [144, 71, 10, 38, 171, 213, 144, 34, 26], + [114, 26, 17, 163, 44, 195, 21, 10, 173], + [121, 24, 80, 195, 26, 62, 44, 64, 85], + [170, 46, 55, 19, 136, 160, 33, 206, 71], + [63, 20, 8, 114, 114, 208, 12, 9, 226], + [81, 40, 11, 96, 182, 84, 29, 16, 36], + ], + [ + [134, 183, 89, 137, 98, 101, 106, 165, 148], + [72, 187, 100, 130, 157, 111, 32, 75, 80], + [66, 102, 167, 99, 74, 62, 40, 234, 128], + [41, 53, 9, 178, 241, 141, 26, 8, 107], + [104, 79, 12, 27, 217, 255, 87, 17, 7], + [74, 43, 26, 146, 73, 166, 49, 23, 157], + [65, 38, 105, 160, 51, 52, 31, 115, 128], + [87, 68, 71, 44, 114, 51, 15, 186, 23], + [47, 41, 14, 110, 182, 183, 21, 17, 194], + [66, 45, 25, 102, 197, 189, 23, 18, 22], + ], + [ + [88, 88, 147, 150, 42, 46, 45, 196, 205], + [43, 97, 183, 117, 85, 38, 35, 179, 61], + [39, 53, 200, 87, 26, 21, 43, 232, 171], + [56, 34, 51, 104, 114, 102, 29, 93, 77], + [107, 54, 32, 26, 51, 1, 81, 43, 31], + [39, 28, 85, 171, 58, 165, 90, 98, 64], + [34, 22, 116, 206, 23, 34, 43, 166, 73], + [68, 25, 106, 22, 64, 171, 36, 225, 114], + [34, 19, 21, 102, 132, 188, 16, 76, 124], + [62, 18, 78, 95, 85, 57, 50, 48, 51], + ], + [ + [193, 101, 35, 159, 215, 111, 89, 46, 111], + [60, 148, 31, 172, 219, 228, 21, 18, 111], + [112, 113, 77, 85, 179, 255, 38, 120, 114], + [40, 42, 1, 196, 245, 209, 10, 25, 109], + [100, 80, 8, 43, 154, 1, 51, 26, 71], + [88, 43, 29, 140, 166, 213, 37, 43, 154], + [61, 63, 30, 155, 67, 45, 68, 1, 209], + [142, 78, 78, 16, 255, 128, 34, 197, 171], + [41, 40, 5, 102, 211, 183, 4, 1, 221], + [51, 50, 17, 168, 209, 192, 23, 25, 82], + ], + [ + [125, 98, 42, 88, 104, 85, 117, 175, 82], + [95, 84, 53, 89, 128, 100, 113, 101, 45], + [75, 79, 123, 47, 51, 128, 81, 171, 1], + [57, 17, 5, 71, 102, 57, 53, 41, 49], + [115, 21, 2, 10, 102, 255, 166, 23, 6], + [38, 33, 13, 121, 57, 73, 26, 1, 85], + [41, 10, 67, 138, 77, 110, 90, 47, 114], + [101, 29, 16, 10, 85, 128, 101, 196, 26], + [57, 18, 10, 102, 102, 213, 34, 20, 43], + [117, 20, 15, 36, 163, 128, 68, 1, 26], + ], + [ + [138, 31, 36, 171, 27, 166, 38, 44, 229], + [67, 87, 58, 169, 82, 115, 26, 59, 179], + [63, 59, 90, 180, 59, 166, 93, 73, 154], + [40, 40, 21, 116, 143, 209, 34, 39, 175], + [57, 46, 22, 24, 128, 1, 54, 17, 37], + [47, 15, 16, 183, 34, 223, 49, 45, 183], + [46, 17, 33, 183, 6, 98, 15, 32, 183], + [65, 32, 73, 115, 28, 128, 23, 128, 205], + [40, 3, 9, 115, 51, 192, 18, 6, 223], + [87, 37, 9, 115, 59, 77, 64, 21, 47], + ], + [ + [104, 55, 44, 218, 9, 54, 53, 130, 226], + [64, 90, 70, 205, 40, 41, 23, 26, 57], + [54, 57, 112, 184, 5, 41, 38, 166, 213], + [30, 34, 26, 133, 152, 116, 10, 32, 134], + [75, 32, 12, 51, 192, 255, 160, 43, 51], + [39, 19, 53, 221, 26, 114, 32, 73, 255], + [31, 9, 65, 234, 2, 15, 1, 118, 73], + [88, 31, 35, 67, 102, 85, 55, 186, 85], + [56, 21, 23, 111, 59, 205, 45, 37, 192], + [55, 38, 70, 124, 73, 102, 1, 34, 98], + ], + [ + [102, 61, 71, 37, 34, 53, 31, 243, 192], + [69, 60, 71, 38, 73, 119, 28, 222, 37], + [68, 45, 128, 34, 1, 47, 11, 245, 171], + [62, 17, 19, 70, 146, 85, 55, 62, 70], + [75, 15, 9, 9, 64, 255, 184, 119, 16], + [37, 43, 37, 154, 100, 163, 85, 160, 1], + [63, 9, 92, 136, 28, 64, 32, 201, 85], + [86, 6, 28, 5, 64, 255, 25, 248, 1], + [56, 8, 17, 132, 137, 255, 55, 116, 128], + [58, 15, 20, 82, 135, 57, 26, 121, 40], + ], + [ + [164, 50, 31, 137, 154, 133, 25, 35, 218], + [51, 103, 44, 131, 131, 123, 31, 6, 158], + [86, 40, 64, 135, 148, 224, 45, 183, 128], + [22, 26, 17, 131, 240, 154, 14, 1, 209], + [83, 12, 13, 54, 192, 255, 68, 47, 28], + [45, 16, 21, 91, 64, 222, 7, 1, 197], + [56, 21, 39, 155, 60, 138, 23, 102, 213], + [85, 26, 85, 85, 128, 128, 32, 146, 171], + [18, 11, 7, 63, 144, 171, 4, 4, 246], + [35, 27, 10, 146, 174, 171, 12, 26, 128], + ], + [ + [190, 80, 35, 99, 180, 80, 126, 54, 45], + [85, 126, 47, 87, 176, 51, 41, 20, 32], + [101, 75, 128, 139, 118, 146, 116, 128, 85], + [56, 41, 15, 176, 236, 85, 37, 9, 62], + [146, 36, 19, 30, 171, 255, 97, 27, 20], + [71, 30, 17, 119, 118, 255, 17, 18, 138], + [101, 38, 60, 138, 55, 70, 43, 26, 142], + [138, 45, 61, 62, 219, 1, 81, 188, 64], + [32, 41, 20, 117, 151, 142, 20, 21, 163], + [112, 19, 12, 61, 195, 128, 48, 4, 24], + ], +]; + +/// Probability that a given token probability is updated in the header. +pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255], + [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255], + [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255], + [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], +]; + +/// Token probabilities a keyframe starts from, [type][band][context][node]. +pub const DEFAULT_COEFF_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128], + [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128], + [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128], + ], + [ + [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128], + [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128], + [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128], + ], + [ + [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128], + [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128], + [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128], + ], + [ + [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128], + [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128], + [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128], + ], + [ + [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128], + [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128], + [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128], + ], + [ + [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128], + [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128], + [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62], + [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1], + [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128], + ], + [ + [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128], + [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128], + [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128], + ], + [ + [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128], + [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128], + [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128], + ], + [ + [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128], + [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128], + [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128], + ], + [ + [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128], + [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128], + [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128], + ], + [ + [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128], + [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128], + [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128], + ], + [ + [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128], + [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128], + [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128], + ], + [ + [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128], + [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128], + [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128], + [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128], + ], + [ + [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128], + [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128], + [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128], + ], + [ + [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128], + [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128], + [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128], + ], + [ + [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128], + [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128], + [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128], + [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128], + [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128], + [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255], + [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128], + [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128], + ], + [ + [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128], + [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128], + [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128], + ], + [ + [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128], + [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128], + [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128], + ], + [ + [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128], + [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128], + [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128], + ], + [ + [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128], + [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128], + [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128], + ], + [ + [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128], + [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128], + [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128], + ], + [ + [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128], + [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128], + [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], +]; + +/// DC dequantization factor per quantizer index. +pub const DC_QLOOKUP: [i32; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +]; + +/// AC dequantization factor per quantizer index. +pub const AC_QLOOKUP: [i32; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +]; + +/// Which probability band each coefficient position uses. +pub const COEFF_BANDS: [usize; 16] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7]; + +/// Coefficient scan order within a 4x4 block. +pub const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; diff --git a/crates/ec-image/src/webp/vp8l.rs b/crates/ec-image/src/webp/vp8l.rs new file mode 100644 index 00000000..5899d06b --- /dev/null +++ b/crates/ec-image/src/webp/vp8l.rs @@ -0,0 +1,896 @@ +//! VP8L: the WebP lossless bitstream. +//! +//! Prefix-coded ARGB literals, LZ77 backward references over a +//! two-dimensionally mapped distance space, a hash-addressed colour cache, and +//! four reversible transforms (predictor, colour, subtract-green, colour +//! indexing) applied in the reverse of the order they were read. +//! +//! Decoding is pixel-exact by construction: every step is integer and the +//! format is lossless, so a differential test against any other implementation +//! either matches every sample or has found a bug. + +use ec_core::{Error, Result}; + +/// Distance codes 1..=120 name a pixel in the neighbourhood above/left of the +/// current one, as `(x, y)` offsets, straight from the specification's table. +const DISTANCE_MAP: [(i32, i32); 120] = [ + (0, 1), + (1, 0), + (1, 1), + (-1, 1), + (0, 2), + (2, 0), + (1, 2), + (-1, 2), + (2, 1), + (-2, 1), + (2, 2), + (-2, 2), + (0, 3), + (3, 0), + (1, 3), + (-1, 3), + (3, 1), + (-3, 1), + (2, 3), + (-2, 3), + (3, 2), + (-3, 2), + (0, 4), + (4, 0), + (1, 4), + (-1, 4), + (4, 1), + (-4, 1), + (3, 3), + (-3, 3), + (2, 4), + (-2, 4), + (4, 2), + (-4, 2), + (0, 5), + (3, 4), + (-3, 4), + (4, 3), + (-4, 3), + (5, 0), + (1, 5), + (-1, 5), + (5, 1), + (-5, 1), + (2, 5), + (-2, 5), + (5, 2), + (-5, 2), + (4, 4), + (-4, 4), + (3, 5), + (-3, 5), + (5, 3), + (-5, 3), + (0, 6), + (6, 0), + (1, 6), + (-1, 6), + (6, 1), + (-6, 1), + (2, 6), + (-2, 6), + (6, 2), + (-6, 2), + (4, 5), + (-4, 5), + (5, 4), + (-5, 4), + (3, 6), + (-3, 6), + (6, 3), + (-6, 3), + (0, 7), + (7, 0), + (1, 7), + (-1, 7), + (5, 5), + (-5, 5), + (7, 1), + (-7, 1), + (4, 6), + (-4, 6), + (6, 4), + (-6, 4), + (2, 7), + (-2, 7), + (7, 2), + (-7, 2), + (3, 7), + (-3, 7), + (7, 3), + (-7, 3), + (5, 6), + (-5, 6), + (6, 5), + (-6, 5), + (8, 0), + (4, 7), + (-4, 7), + (7, 4), + (-7, 4), + (8, 1), + (8, 2), + (6, 6), + (-6, 6), + (8, 3), + (5, 7), + (-5, 7), + (7, 5), + (-7, 5), + (8, 4), + (6, 7), + (-6, 7), + (7, 6), + (-7, 6), + (8, 5), + (7, 7), + (-7, 7), + (8, 6), + (8, 7), +]; + +/// The order code-length code lengths arrive in. +const CODE_LENGTH_ORDER: [usize; 19] = [ + 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +]; + +const GREEN_EXTRA: usize = 24; +const MAX_ALLOWED_CODE_LENGTH: usize = 15; + +/// Least-significant-bit-first bit reader, as VP8L reads its stream. +pub struct BitReader<'a> { + data: &'a [u8], + /// Bit position from the start of `data`. + pos: usize, +} + +impl<'a> BitReader<'a> { + /// A reader over `data`, starting at its first bit. + pub fn new(data: &'a [u8]) -> BitReader<'a> { + BitReader { data, pos: 0 } + } + + /// Read `n` bits (`n <= 24`), low bit first. + /// + /// Past the end of the data the reader yields zeros and records that it + /// ran out; the decode loop reports the truncation rather than panicking + /// on a short buffer. + pub fn read(&mut self, n: u32) -> u32 { + let mut value = 0u32; + for i in 0..n { + let byte = self.data.get(self.pos >> 3).copied().unwrap_or(0); + let bit = (byte >> (self.pos & 7)) & 1; + value |= u32::from(bit) << i; + self.pos += 1; + } + value + } + + /// True once more bits have been read than the buffer holds. + pub fn exhausted(&self) -> bool { + self.pos > self.data.len() * 8 + } +} + +/// A canonical prefix code, decoded bit by bit. +struct Huffman { + /// Number of codes of each length, 1..=15. + counts: [u16; MAX_ALLOWED_CODE_LENGTH + 1], + /// Symbols ordered by (length, symbol). + symbols: Vec, + /// The one symbol, when the code is a single leaf that consumes no bits. + single: Option, +} + +impl Huffman { + fn from_lengths(lengths: &[u8]) -> Result { + let mut counts = [0u16; MAX_ALLOWED_CODE_LENGTH + 1]; + let mut used = 0; + let mut last = 0u16; + for (symbol, &len) in lengths.iter().enumerate() { + if len as usize > MAX_ALLOWED_CODE_LENGTH { + return Err(Error::corrupt(format!("VP8L: code length {len}"))); + } + if len > 0 { + counts[len as usize] += 1; + used += 1; + last = symbol as u16; + } + } + if used == 0 { + return Err(Error::corrupt("VP8L: prefix code with no symbols")); + } + if used == 1 { + return Ok(Huffman { + counts, + symbols: vec![last], + single: Some(last), + }); + } + // Kraft check: an over- or under-subscribed code is a corrupt stream, + // and an under-subscribed one would otherwise decode into a hole. + let mut left = 1i32; + for len in 1..=MAX_ALLOWED_CODE_LENGTH { + left <<= 1; + left -= i32::from(counts[len]); + if left < 0 { + return Err(Error::corrupt("VP8L: over-subscribed prefix code")); + } + } + if left != 0 { + return Err(Error::corrupt("VP8L: incomplete prefix code")); + } + // Symbols ordered by code length, then by symbol: exactly the order + // `decode` walks them in. + let mut offsets = [0usize; MAX_ALLOWED_CODE_LENGTH + 1]; + let mut total = 0usize; + for len in 1..=MAX_ALLOWED_CODE_LENGTH { + offsets[len] = total; + total += usize::from(counts[len]); + } + let mut symbols = vec![0u16; used]; + for (symbol, &len) in lengths.iter().enumerate() { + if len > 0 { + symbols[offsets[len as usize]] = symbol as u16; + offsets[len as usize] += 1; + } + } + Ok(Huffman { + counts, + symbols, + single: None, + }) + } + + fn decode(&self, bits: &mut BitReader<'_>) -> Result { + if let Some(symbol) = self.single { + return Ok(symbol); + } + let mut code = 0i32; + let mut first = 0i32; + let mut index = 0i32; + for len in 1..=MAX_ALLOWED_CODE_LENGTH { + code |= bits.read(1) as i32; + let count = i32::from(self.counts[len]); + if code - first < count { + let at = (index + code - first) as usize; + return self + .symbols + .get(at) + .copied() + .ok_or_else(|| Error::corrupt("VP8L: symbol outside its code")); + } + index += count; + first = (first + count) << 1; + code <<= 1; + } + Err(Error::corrupt("VP8L: no prefix code matches the bits")) + } +} + +/// One prefix code group: green+length+cache, red, blue, alpha, distance. +struct Group { + green: Huffman, + red: Huffman, + blue: Huffman, + alpha: Huffman, + distance: Huffman, +} + +/// A decoded lossless image: packed ARGB, one `u32` per pixel. +pub struct Argb { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// `a << 24 | r << 16 | g << 8 | b`, scan-line order. + pub pixels: Vec, +} + +/// Decode a complete VP8L chunk, header and all. +pub fn decode(data: &[u8], limits: crate::Limits) -> Result { + let mut bits = BitReader::new(data); + if bits.read(8) != 0x2f { + return Err(Error::corrupt("VP8L: missing 0x2f signature")); + } + let width = bits.read(14) + 1; + let height = bits.read(14) + 1; + let _alpha_is_used = bits.read(1); + let version = bits.read(3); + if version != 0 { + return Err(Error::corrupt(format!("VP8L: version {version}"))); + } + limits.check(width, height)?; + let pixels = decode_stream(&mut bits, width, height, true)?; + Ok(Argb { + width, + height, + pixels, + }) +} + +/// Decode a headerless VP8L stream of known dimensions — how an `ALPH` chunk +/// carries a lossless alpha plane, and how a colour table is stored. +pub fn decode_implicit(data: &[u8], width: u32, height: u32) -> Result> { + let mut bits = BitReader::new(data); + decode_stream(&mut bits, width, height, true) +} + +/// The image stream proper: transforms (when allowed), then entropy-coded data. +fn decode_stream( + bits: &mut BitReader<'_>, + width: u32, + height: u32, + transforms_allowed: bool, +) -> Result> { + let mut transforms: Vec = Vec::new(); + let mut work_width = width; + if transforms_allowed { + let mut seen = [false; 4]; + while bits.read(1) == 1 { + let kind = bits.read(2) as usize; + if seen[kind] { + return Err(Error::corrupt("VP8L: transform used twice")); + } + seen[kind] = true; + let transform = read_transform(bits, kind, work_width, height)?; + if let Transform::ColorIndexing { width_bits, .. } = &transform { + work_width = work_width.div_ceil(1 << width_bits); + } + transforms.push(transform); + } + } + + let mut pixels = decode_entropy_coded(bits, work_width, height, true)?; + // Applied last-read-first, which is the inverse of the encoder's order. + for transform in transforms.iter().rev() { + pixels = apply_transform(transform, pixels, &mut work_width, height)?; + } + if work_width != width { + return Err(Error::corrupt("VP8L: transforms left the wrong width")); + } + Ok(pixels) +} + +/// A transform, with the data needed to invert it. +enum Transform { + Predictor { bits: u32, image: Vec, tw: u32 }, + Color { bits: u32, image: Vec, tw: u32 }, + SubtractGreen, + ColorIndexing { width_bits: u32, table: Vec }, +} + +fn read_transform( + bits: &mut BitReader<'_>, + kind: usize, + width: u32, + height: u32, +) -> Result { + match kind { + 0 | 1 => { + let size_bits = bits.read(3) + 2; + let tw = width.div_ceil(1 << size_bits); + let th = height.div_ceil(1 << size_bits); + let image = decode_entropy_coded(bits, tw, th, false)?; + Ok(if kind == 0 { + Transform::Predictor { + bits: size_bits, + image, + tw, + } + } else { + Transform::Color { + bits: size_bits, + image, + tw, + } + }) + } + 2 => Ok(Transform::SubtractGreen), + _ => { + let size = bits.read(8) + 1; + let mut table = decode_entropy_coded(bits, size, 1, false)?; + // The table is stored as deltas between successive colours. + for i in 1..table.len() { + table[i] = add_argb(table[i], table[i - 1]); + } + let width_bits = match size { + 0..=2 => 3, + 3..=4 => 2, + 5..=16 => 1, + _ => 0, + }; + Ok(Transform::ColorIndexing { width_bits, table }) + } + } +} + +fn apply_transform( + transform: &Transform, + pixels: Vec, + width: &mut u32, + height: u32, +) -> Result> { + Ok(match transform { + Transform::SubtractGreen => pixels + .into_iter() + .map(|p| { + let g = (p >> 8) & 0xff; + let r = ((p >> 16) + g) & 0xff; + let b = (p + g) & 0xff; + (p & 0xff00_ff00) | (r << 16) | b + }) + .collect(), + Transform::Color { bits, image, tw } => { + let mut out = pixels; + for y in 0..height { + for x in 0..*width { + let block = (y >> bits) * tw + (x >> bits); + let element = image.get(block as usize).copied().unwrap_or(0); + let index = (y * *width + x) as usize; + out[index] = inverse_color(out[index], element); + } + } + out + } + Transform::Predictor { bits, image, tw } => { + inverse_predictor(pixels, *width, height, *bits, image, *tw) + } + Transform::ColorIndexing { width_bits, table } => { + let out_width = *width << width_bits; + let mut out = vec![0u32; (out_width as usize) * (height as usize)]; + let per_pixel = 1u32 << width_bits; + let bits_each = 8 >> width_bits; + let mask = (1u32 << bits_each) - 1; + for y in 0..height { + for x in 0..*width { + let packed = (pixels[(y * *width + x) as usize] >> 8) & 0xff; + for sub in 0..per_pixel { + let ox = x * per_pixel + sub; + if ox >= out_width { + break; + } + let index = if *width_bits == 0 { + packed + } else { + (packed >> (bits_each * sub)) & mask + }; + out[(y * out_width + ox) as usize] = + table.get(index as usize).copied().unwrap_or(0); + } + } + } + *width = out_width; + out + } + }) +} + +fn add_argb(a: u32, b: u32) -> u32 { + let mut out = 0u32; + for shift in [0, 8, 16, 24] { + let sum = (((a >> shift) & 0xff) + ((b >> shift) & 0xff)) & 0xff; + out |= sum << shift; + } + out +} + +fn inverse_color(pixel: u32, element: u32) -> u32 { + // The element carries green_to_red in blue, green_to_blue in green and + // red_to_blue in red, as the specification lays it out. + let green_to_red = (element & 0xff) as i8; + let green_to_blue = ((element >> 8) & 0xff) as i8; + let red_to_blue = ((element >> 16) & 0xff) as i8; + let green = ((pixel >> 8) & 0xff) as u8 as i8; + let mut red = ((pixel >> 16) & 0xff) as i32; + let mut blue = (pixel & 0xff) as i32; + red += delta(green_to_red, green); + blue += delta(green_to_blue, green); + blue += delta(red_to_blue, (red & 0xff) as u8 as i8); + (pixel & 0xff00_ff00) | (((red & 0xff) as u32) << 16) | ((blue & 0xff) as u32) +} + +/// `(t * c) >> 5` in the specification's 3.5 fixed point. +fn delta(t: i8, c: i8) -> i32 { + (i32::from(t) * i32::from(c)) >> 5 +} + +fn inverse_predictor( + mut pixels: Vec, + width: u32, + height: u32, + size_bits: u32, + image: &[u32], + tw: u32, +) -> Vec { + let w = width as usize; + for y in 0..height as usize { + for x in 0..w { + let index = y * w + x; + let pred = if x == 0 && y == 0 { + 0xff00_0000 + } else if y == 0 { + pixels[index - 1] + } else if x == 0 { + pixels[index - w] + } else { + let block = ((y as u32) >> size_bits) * tw + ((x as u32) >> size_bits); + let mode = image.get(block as usize).map_or(0, |p| (p >> 8) & 0xff); + let left = pixels[index - 1]; + let top = pixels[index - w]; + let top_left = pixels[index - w - 1]; + // The rightmost column has no top-right; the leftmost pixel of + // the same row stands in, as the specification requires. + let top_right = if x + 1 == w { + pixels[y * w] + } else { + pixels[index - w + 1] + }; + predict(mode, left, top, top_left, top_right) + }; + pixels[index] = add_argb(pixels[index], pred); + } + } + pixels +} + +fn predict(mode: u32, l: u32, t: u32, tl: u32, tr: u32) -> u32 { + match mode { + 0 => 0xff00_0000, + 1 => l, + 2 => t, + 3 => tr, + 4 => tl, + 5 => average2(average2(l, tr), t), + 6 => average2(l, tl), + 7 => average2(l, t), + 8 => average2(tl, t), + 9 => average2(t, tr), + 10 => average2(average2(l, tl), average2(t, tr)), + 11 => select(l, t, tl), + 12 => clamp_add_subtract_full(l, t, tl), + 13 => clamp_add_subtract_half(average2(l, t), tl), + // Modes past 13 do not exist; a corrupt predictor image gets black + // rather than an out-of-range panic. + _ => 0xff00_0000, + } +} + +fn average2(a: u32, b: u32) -> u32 { + let mut out = 0u32; + for shift in [0, 8, 16, 24] { + let v = (((a >> shift) & 0xff) + ((b >> shift) & 0xff)) / 2; + out |= v << shift; + } + out +} + +fn select(l: u32, t: u32, tl: u32) -> u32 { + let mut pl = 0i32; + let mut pt = 0i32; + for shift in [0, 8, 16, 24] { + let (a, b, c) = ( + ((l >> shift) & 0xff) as i32, + ((t >> shift) & 0xff) as i32, + ((tl >> shift) & 0xff) as i32, + ); + let p = a + b - c; + pl += (p - a).abs(); + pt += (p - b).abs(); + } + if pl < pt { l } else { t } +} + +fn clamp_add_subtract_full(a: u32, b: u32, c: u32) -> u32 { + let mut out = 0u32; + for shift in [0, 8, 16, 24] { + let v = (((a >> shift) & 0xff) as i32 + ((b >> shift) & 0xff) as i32 + - ((c >> shift) & 0xff) as i32) + .clamp(0, 255) as u32; + out |= v << shift; + } + out +} + +fn clamp_add_subtract_half(a: u32, b: u32) -> u32 { + let mut out = 0u32; + for shift in [0, 8, 16, 24] { + let (x, y) = (((a >> shift) & 0xff) as i32, ((b >> shift) & 0xff) as i32); + let v = (x + (x - y) / 2).clamp(0, 255) as u32; + out |= v << shift; + } + out +} + +/// Read a prefix code: either the two-symbol shorthand or full code lengths. +fn read_code(bits: &mut BitReader<'_>, alphabet: usize) -> Result { + let mut lengths = vec![0u8; alphabet]; + if bits.read(1) == 1 { + // Simple code: one or two symbols, each one bit long. + let count = bits.read(1) + 1; + let first_is_byte = bits.read(1) == 1; + let symbol0 = bits.read(if first_is_byte { 8 } else { 1 }) as usize; + if symbol0 >= alphabet { + return Err(Error::corrupt("VP8L: simple code symbol past the alphabet")); + } + lengths[symbol0] = 1; + if count == 2 { + let symbol1 = bits.read(8) as usize; + if symbol1 >= alphabet { + return Err(Error::corrupt("VP8L: simple code symbol past the alphabet")); + } + lengths[symbol1] = 1; + } + // One symbol of length 1 is a legal single-leaf code, so build from + // the lengths rather than insisting the Kraft sum be exactly one. + return Huffman::from_lengths(&lengths); + } + + let num_lengths = 4 + bits.read(4) as usize; + let mut code_length_lengths = [0u8; 19]; + for i in 0..num_lengths { + code_length_lengths[CODE_LENGTH_ORDER[i]] = bits.read(3) as u8; + } + let code_length_code = Huffman::from_lengths(&code_length_lengths)?; + + let mut max_symbol = if bits.read(1) == 1 { + let length_bits = 2 + 2 * bits.read(3); + let max = 2 + bits.read(length_bits) as usize; + if max > alphabet { + return Err(Error::corrupt("VP8L: max_symbol past the alphabet")); + } + max + } else { + alphabet + }; + + let mut previous = 8u8; + let mut index = 0usize; + while index < alphabet { + if max_symbol == 0 { + break; + } + max_symbol -= 1; + if bits.exhausted() { + return Err(Error::corrupt("VP8L: truncated code lengths")); + } + let symbol = code_length_code.decode(bits)?; + match symbol { + 0..=15 => { + lengths[index] = symbol as u8; + index += 1; + if symbol != 0 { + previous = symbol as u8; + } + } + 16 => { + let repeat = 3 + bits.read(2) as usize; + for _ in 0..repeat.min(alphabet - index) { + lengths[index] = previous; + index += 1; + } + } + 17 => index += (3 + bits.read(3) as usize).min(alphabet - index), + 18 => index += (11 + bits.read(7) as usize).min(alphabet - index), + other => return Err(Error::corrupt(format!("VP8L: code length symbol {other}"))), + } + } + Huffman::from_lengths(&lengths) +} + +/// Read the five prefix codes of one group. +fn read_group(bits: &mut BitReader<'_>, cache_bits: u32) -> Result { + let green_alphabet = 256 + GREEN_EXTRA + if cache_bits > 0 { 1 << cache_bits } else { 0 }; + Ok(Group { + green: read_code(bits, green_alphabet)?, + red: read_code(bits, 256)?, + blue: read_code(bits, 256)?, + alpha: read_code(bits, 256)?, + distance: read_code(bits, 40)?, + }) +} + +/// Length or distance from a prefix code plus its extra bits. +fn prefix_value(bits: &mut BitReader<'_>, code: u32) -> u32 { + if code < 4 { + return code + 1; + } + let extra = (code - 2) >> 1; + let offset = (2 + (code & 1)) << extra; + offset + bits.read(extra) + 1 +} + +/// Decode an entropy-coded image: the ARGB image itself, or one of the +/// sub-resolution images a transform or the meta prefix uses. +fn decode_entropy_coded( + bits: &mut BitReader<'_>, + width: u32, + height: u32, + meta_allowed: bool, +) -> Result> { + let count = (width as usize) + .checked_mul(height as usize) + .ok_or_else(|| Error::corrupt("VP8L: image geometry overflows"))?; + + // Order matters and is easy to get backwards: the colour cache size comes + // first, then the meta prefix codes, then the prefix codes themselves. + let cache_bits = if bits.read(1) == 1 { + let n = bits.read(4); + if !(1..=11).contains(&n) { + return Err(Error::corrupt(format!("VP8L: colour cache bits {n}"))); + } + n + } else { + 0 + }; + + let mut entropy_image: Vec = Vec::new(); + let mut prefix_bits = 0u32; + let mut prefix_width = 0u32; + let mut groups = 1usize; + if meta_allowed && bits.read(1) == 1 { + prefix_bits = bits.read(3) + 2; + prefix_width = width.div_ceil(1 << prefix_bits); + let prefix_height = height.div_ceil(1 << prefix_bits); + entropy_image = decode_entropy_coded(bits, prefix_width, prefix_height, false)?; + groups = entropy_image + .iter() + .map(|p| (((p >> 8) & 0xffff) as usize) + 1) + .max() + .unwrap_or(1); + if groups > 1 << 16 { + return Err(Error::corrupt("VP8L: too many prefix code groups")); + } + } + + let mut code_groups = Vec::with_capacity(groups); + for _ in 0..groups { + code_groups.push(read_group(bits, cache_bits)?); + if bits.exhausted() { + return Err(Error::corrupt("VP8L: truncated prefix codes")); + } + } + + let mut cache = vec![0u32; if cache_bits > 0 { 1 << cache_bits } else { 0 }]; + let mut pixels = vec![0u32; count]; + let mut at = 0usize; + while at < count { + if bits.exhausted() { + return Err(Error::corrupt("VP8L: truncated image data")); + } + let group = if entropy_image.is_empty() { + &code_groups[0] + } else { + let x = (at % width as usize) as u32; + let y = (at / width as usize) as u32; + let block = (y >> prefix_bits) * prefix_width + (x >> prefix_bits); + let meta = entropy_image + .get(block as usize) + .map_or(0, |p| ((p >> 8) & 0xffff) as usize); + code_groups + .get(meta) + .ok_or_else(|| Error::corrupt("VP8L: meta prefix code past its group list"))? + }; + let symbol = u32::from(group.green.decode(bits)?); + if symbol < 256 { + let red = u32::from(group.red.decode(bits)?); + let blue = u32::from(group.blue.decode(bits)?); + let alpha = u32::from(group.alpha.decode(bits)?); + let pixel = (alpha << 24) | (red << 16) | (symbol << 8) | blue; + pixels[at] = pixel; + if cache_bits > 0 { + cache[cache_index(pixel, cache_bits)] = pixel; + } + at += 1; + } else if symbol < 256 + GREEN_EXTRA as u32 { + let length = prefix_value(bits, symbol - 256) as usize; + let distance_code = u32::from(group.distance.decode(bits)?); + let distance = prefix_value(bits, distance_code) as usize; + let distance = map_distance(distance, width); + if distance > at || length > count - at { + return Err(Error::corrupt("VP8L: backward reference outside the image")); + } + for i in 0..length { + let pixel = pixels[at - distance + i]; + pixels[at + i] = pixel; + if cache_bits > 0 { + cache[cache_index(pixel, cache_bits)] = pixel; + } + } + at += length; + } else { + let index = (symbol - 256 - GREEN_EXTRA as u32) as usize; + let pixel = *cache + .get(index) + .ok_or_else(|| Error::corrupt("VP8L: colour cache index out of range"))?; + pixels[at] = pixel; + at += 1; + } + } + Ok(pixels) +} + +fn cache_index(pixel: u32, cache_bits: u32) -> usize { + ((0x1e35_a7bd_u32.wrapping_mul(pixel)) >> (32 - cache_bits)) as usize +} + +/// Distance codes 1..=120 name a nearby pixel; anything larger is a plain +/// scan-line distance offset by 120. +fn map_distance(code: usize, width: u32) -> usize { + if code > 120 { + return code - 120; + } + let (xi, yi) = DISTANCE_MAP[code - 1]; + let distance = yi * width as i32 + xi; + distance.max(1) as usize +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bits_come_out_low_bit_first() { + let mut bits = BitReader::new(&[0b1010_0110, 0xff]); + assert_eq!(bits.read(1), 0); + assert_eq!(bits.read(2), 0b11); + assert_eq!(bits.read(5), 0b1_0100); + assert_eq!(bits.read(8), 0xff); + assert!(!bits.exhausted()); + bits.read(1); + assert!(bits.exhausted()); + } + + #[test] + fn a_canonical_code_decodes_its_own_symbols() { + // Lengths 1,2,3,3 -> codes 0, 10, 110, 111. + let code = Huffman::from_lengths(&[1, 2, 3, 3]).unwrap(); + let mut bits = BitReader::new(&[0b1101_1100, 0b0000_0001]); + // Bits low-first: 0,0,1,1,1,0,1,1 -> symbol 0, then 110 -> 2 ... + assert_eq!(code.decode(&mut bits).unwrap(), 0); + assert_eq!(code.decode(&mut bits).unwrap(), 0); + assert_eq!(code.decode(&mut bits).unwrap(), 3); + } + + #[test] + fn an_incomplete_code_is_refused() { + assert!(Huffman::from_lengths(&[1, 2, 3]).is_err()); + assert!(Huffman::from_lengths(&[1, 1, 1, 1]).is_err()); + assert!(Huffman::from_lengths(&[0, 0]).is_err()); + // A single leaf is legal and consumes no bits. + let single = Huffman::from_lengths(&[0, 1, 0]).unwrap(); + let mut bits = BitReader::new(&[]); + assert_eq!(single.decode(&mut bits).unwrap(), 1); + } + + #[test] + fn distance_codes_map_into_the_neighbourhood() { + // Code 1 is the pixel directly above; code 2 the one to the left. + assert_eq!(map_distance(1, 16), 16); + assert_eq!(map_distance(2, 16), 1); + assert_eq!(map_distance(121, 16), 1); + // Every mapped distance must be at least one pixel back. + for code in 1..=120 { + assert!(map_distance(code, 4) >= 1, "code {code}"); + } + } + + #[test] + fn the_predictors_agree_with_their_definitions() { + let l = 0xff20_4060; + let t = 0xff40_6080; + let tl = 0xff10_2030; + assert_eq!(predict(1, l, t, tl, 0), l); + assert_eq!(predict(2, l, t, tl, 0), t); + assert_eq!(predict(7, l, t, tl, 0), 0xff30_5070); + assert_eq!(predict(12, l, t, tl, 0), clamp_add_subtract_full(l, t, tl)); + assert_eq!(predict(99, l, t, tl, 0), 0xff00_0000); + } +} diff --git a/crates/ec-pgs/src/lib.rs b/crates/ec-pgs/src/lib.rs index 4093cfb5..286e3486 100644 --- a/crates/ec-pgs/src/lib.rs +++ b/crates/ec-pgs/src/lib.rs @@ -386,17 +386,24 @@ pub fn make_decoder(_params: &CodecParameters) -> Result> { Ok(Box::new(PgsDecoder::new())) } -/// One palette entry: BT.601 limited-range Y'CbCr with straight alpha, the way -/// a disc writes it, into RGBA. +/// One palette entry: BT.601 Y'CbCr with straight alpha, the way a disc writes +/// it, into RGBA. +/// +/// The luma is taken at its own scale — `Y' = 235` comes out 235, not the 255 +/// an expansion of the 16..235 video range would give. That is not a reading of +/// the Blu-ray spec but a measurement of what every player draws: ffmpeg's own +/// `pgssub` decoder, burning `fixtures/subs/pgs-1080p.sup` over black, tops out +/// at 235 (`scripts/pgs-white-level.sh`), and a subtitle that is brighter than +/// the one the disc is mastered against is our bug, not the world's. fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] { - let y = 298 * (i32::from(y) - 16); + let y = i32::from(y) << 8; let cb = i32::from(cb) - 128; let cr = i32::from(cr) - 128; let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8; [ - clamp(y + 409 * cr), - clamp(y - 100 * cb - 208 * cr), - clamp(y + 516 * cb), + clamp(y + 359 * cr), + clamp(y - 88 * cb - 183 * cr), + clamp(y + 454 * cb), alpha, ] } @@ -515,10 +522,11 @@ mod tests { // Outside the object: nothing painted at all. assert_eq!(pixel(0, 0), [0, 0, 0, 0]); assert_eq!(pixel(1, 1), [0, 0, 0, 0]); - // Row 1 of the object is white, row 2 is black, both opaque. - assert_eq!(pixel(2, 1), [255, 255, 255, 255]); - assert_eq!(pixel(9, 1), [255, 255, 255, 255]); - assert_eq!(pixel(2, 2), [0, 0, 0, 255]); + // Row 1 of the object is white, row 2 is black, both opaque. White is + // the palette's own `Y' = 235`, black its `Y' = 16` — see [`rgba`]. + assert_eq!(pixel(2, 1), [235, 235, 235, 255]); + assert_eq!(pixel(9, 1), [235, 235, 235, 255]); + assert_eq!(pixel(2, 2), [16, 16, 16, 255]); // Past the object's width again. assert_eq!(pixel(10, 1), [0, 0, 0, 0]); assert!(decoder.take_frame().is_none()); @@ -567,10 +575,12 @@ mod tests { } #[test] - fn palette_entries_are_bt601_limited_range() { - // Y=235 is white, Y=16 is black, and alpha rides through untouched. - assert_eq!(rgba(235, 128, 128, 255), [255, 255, 255, 255]); - assert_eq!(rgba(16, 128, 128, 128), [0, 0, 0, 128]); + fn palette_entries_convert_at_their_own_luma_scale() { + // A disc's white and black land where ffmpeg's PGS decoder puts them — + // 235 and 16, not an expansion to 255 and 0 — and alpha rides through + // untouched. + assert_eq!(rgba(235, 128, 128, 255), [235, 235, 235, 255]); + assert_eq!(rgba(16, 128, 128, 128), [16, 16, 16, 128]); // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601. let red = rgba(81, 240, 90, 255); assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}"); diff --git a/scripts/pgs-white-level.sh b/scripts/pgs-white-level.sh new file mode 100755 index 00000000..43557568 --- /dev/null +++ b/scripts/pgs-white-level.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# What a player draws a PGS subtitle's white as, measured rather than reasoned: +# ffmpeg burns fixtures/subs/pgs-1080p.sup over black and the brightest red +# channel in the first painted frame is printed. It is 235 -- the palette's own +# Y', not an expansion of the 16..235 video range to 255 -- which is what +# `ec_pgs::rgba` matches. +# +# scripts/pgs-white-level.sh [file.sup] +set -euo pipefail + +sup="${1:-$(dirname "$0")/../fixtures/subs/pgs-1080p.sup}" +[ -r "$sup" ] || { echo "no such .sup: $sup (fixtures are gitignored)" >&2; exit 1; } + +size=$(ffprobe -v error -select_streams s:0 -show_entries stream=width,height \ + -of csv=p=0:s=x "$sup") +raw=$(mktemp -t pgs-white.XXXXXX) +trap 'rm -f "$raw"' EXIT + +ffmpeg -v error -f lavfi -i "color=c=black:s=$size:r=1:d=60,format=rgba" -i "$sup" \ + -filter_complex "[0:v][1:s]overlay=format=rgb" -frames:v 60 \ + -pix_fmt rgba -f rawvideo -y "$raw" + +python3 - "$raw" "$size" <<'PY' +import sys +data = open(sys.argv[1], 'rb').read() +w, h = (int(v) for v in sys.argv[2].split('x')) +frame = w * h * 4 +for i in range(len(data) // frame): + reds = data[i * frame:(i + 1) * frame:4] + peak = max(reds) + if peak: + print(f"frame {i}: brightest red {peak}, " + f"{sum(1 for v in reds if v)} pixels drawn on") + break +else: + print("nothing painted in any frame", file=sys.stderr) + sys.exit(1) +PY diff --git a/shims/oxideav-ac3/src/lib.rs b/shims/oxideav-ac3/src/lib.rs new file mode 100644 index 00000000..3dc0e667 --- /dev/null +++ b/shims/oxideav-ac3/src/lib.rs @@ -0,0 +1,129 @@ +//! `oxideav-ac3` as edith consumes it, over [`ec_ac3`]. +//! +//! A shim, not a port: it carries the incumbent's package name and version so +//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the +//! replica names — the header surface it reads a track's rate and layout out of +//! ([`syncinfo::parse`], [`bsi::parse`], [`eac3::bsi::parse`], `audio.rs:1954`, +//! `2063`) and [`register_codecs`], which is how it gets a decoder at all +//! (`audio.rs:2132`). The header modules are `ec_ac3`'s own: their signatures, +//! their entry offsets (`bsi` after the five `syncinfo()` bytes, `eac3::bsi` +//! after the 16-bit sync word) and their fields already match what the replica +//! writes, so a re-export is the whole adapter. +//! +//! Two differences are owned here rather than at the call site: +//! +//! * **Sample format.** The incumbent hands out S16 little-endian and the +//! replica reads it as such (`audio.rs:2160`, `chunks_exact(2)` over +//! `/32768.0`); `ec_ac3` decodes to `f32`. The conversion is +//! [`Ac3Decoder::receive_frame`], once, for every caller — which is why this +//! shim writes its own [`oxideav_core::Decoder`] instead of wrapping +//! `oxideav_core::EcDecoder`, whose job is the frames that need no +//! conversion. +//! * **Downmix request.** The incumbent takes the wanted channel count on +//! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the +//! factory translates. `Some(2)` is the A/52 §7.8 stereo fold the replica +//! asks for on anything wider than mono, `None` the stream's own layout. + +#![forbid(unsafe_code)] + +pub use ec_ac3::{bsi, eac3, syncinfo}; + +use ec_ac3::{Downmix, Options}; +use oxideav_core::{ + AudioFrame, CodecId, CodecInfo, CodecParameters, CodecRegistry, Decoder, Frame, Packet, Result, +}; + +/// Register this crate's codecs — `ac3` and `eac3` — into `registry`. +/// +/// Both ids reach the same decoder: it dispatches per packet on `bsid`, so the +/// id picks the capability set and not the syntax. +pub fn register_codecs(registry: &mut CodecRegistry) { + for id in ["ac3", "eac3"] { + registry.register(CodecInfo::new(CodecId::new(id)).decoder(open)); + } +} + +/// A decoder for `params`, folded down to `params.channels`. +fn open(params: &CodecParameters) -> Result> { + let options = Options { + downmix: match params.channels { + Some(1) => Downmix::Mono, + Some(2) => Downmix::Stereo, + _ => Downmix::Native, + }, + ..Options::default() + }; + Ok(Box::new(Ac3Decoder { + id: params.codec_id.clone(), + inner: ec_ac3::Ac3Decoder::with_options(options), + })) +} + +/// The family's AC-3 decoder: one syncframe in, one S16 little-endian frame +/// out. +struct Ac3Decoder { + id: CodecId, + inner: ec_ac3::Ac3Decoder, +} + +impl Decoder for Ac3Decoder { + fn codec_id(&self) -> &CodecId { + &self.id + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + Ok(ec_core::Decoder::send_packet(&mut self.inner, packet)?) + } + + fn receive_frame(&mut self) -> Result { + match ec_core::Decoder::receive_frame(&mut self.inner)? { + ec_core::Frame::Audio(audio) => Ok(Frame::Audio(AudioFrame { + samples: audio.samples as u32, + pts: audio.pts.map(|ts| ts.ticks), + data: audio.data.iter().map(|plane| s16le(plane)).collect(), + })), + other => Ok(other.into()), + } + } +} + +/// Interleaved `f32` bytes as S16 little-endian, which is what the incumbent +/// speaks. Full scale is 32768 in both directions, saturating: the replica's +/// inverse is `/32768.0`, and a sample at or past `+1.0` has to land on +/// `i16::MAX` rather than wrap to silence. +fn s16le(samples: &[u8]) -> Vec { + let mut out = Vec::with_capacity(samples.len() / 2); + for chunk in samples.chunks_exact(4) { + let v = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + let scaled = (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16; + out.extend_from_slice(&scaled.to_le_bytes()); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_scale_saturates_instead_of_wrapping() { + let pcm: Vec = [-1.5f32, -1.0, 0.0, 0.5, 1.0, 1.5] + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let got: Vec = s16le(&pcm) + .chunks_exact(2) + .map(|s| i16::from_le_bytes([s[0], s[1]])) + .collect(); + assert_eq!(got, [-32768, -32768, 0, 16384, 32767, 32767]); + } + + #[test] + fn both_ids_are_registered_and_a_third_is_not() { + let mut registry = CodecRegistry::new(); + register_codecs(&mut registry); + assert!(registry.has_decoder(&CodecId::new("ac3"))); + assert!(registry.has_decoder(&CodecId::new("eac3"))); + assert!(!registry.has_decoder(&CodecId::new("truehd"))); + } +} diff --git a/shims/oxideav-ac3/tests/edith_surface.rs b/shims/oxideav-ac3/tests/edith_surface.rs new file mode 100644 index 00000000..f327e9eb --- /dev/null +++ b/shims/oxideav-ac3/tests/edith_surface.rs @@ -0,0 +1,105 @@ +//! The AC-3 path exactly as the replica drives it: read the rate and the +//! layout out of the first syncframe's headers, ask the registry for a decoder +//! folded to that layout, decode, and read the frame back as S16 little-endian +//! (`engine/src/audio.rs:1954-2170`). +//! +//! Missing fixtures skip rather than fail, as the `ec-ac3` matrix does; +//! `scripts/gen-fixtures.sh` writes them. + +use std::path::{Path, PathBuf}; + +use oxideav_ac3::{bsi, eac3, register_codecs, syncinfo}; +use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Error, Frame, Packet, TimeBase}; + +fn fixture(name: &str) -> Option> { + let path: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/audio") + .join(name); + std::fs::read(path).ok() +} + +/// `engine/src/audio.rs:2130` — a fresh decoder out of a fresh registry. +fn ac3_decoder(codec: &str, channels: Option) -> Box { + let mut registry = CodecRegistry::new(); + register_codecs(&mut registry); + let mut params = CodecParameters::audio(CodecId::new(codec)); + params.channels = channels; + registry.first_decoder(¶ms).expect("no AC-3 decoder") +} + +/// `engine/src/audio.rs:2150` — one syncframe in, interleaved `f32` and the +/// frames per channel out; `None` when the decoder wants more input. +fn decode_ac3(decoder: &mut Box, bytes: &[u8]) -> Option<(Vec, u64)> { + let packet = Packet::new(0, TimeBase::new(1, 48_000), bytes.to_vec()); + decoder.send_packet(&packet).expect("AC-3 decode failed"); + match decoder.receive_frame() { + Ok(Frame::Audio(audio)) => Some(( + audio.data[0] + .chunks_exact(2) + .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) + .collect(), + u64::from(audio.samples), + )), + Ok(other) => panic!("AC-3 decoder handed back {other:?}"), + Err(Error::NeedMore) => None, + Err(e) => panic!("AC-3 decode failed: {e:?}"), + } +} + +/// `engine/src/audio.rs:2061` — rate and `nfchans` out of the bit stream, +/// whichever syntax it is. +fn header(codec: &str, frame: &[u8]) -> (u32, usize) { + if codec == "eac3" { + let bsi = eac3::bsi::parse(frame.get(2..).unwrap_or_default()).expect("E-AC-3 bsi"); + (bsi.sample_rate, bsi.nfchans) + } else { + let sync = syncinfo::parse(frame).expect("AC-3 syncinfo"); + let bsi = bsi::parse(frame.get(5..).unwrap_or_default()).expect("AC-3 bsi"); + (sync.sample_rate, bsi.nfchans) + } +} + +fn rms(pcm: &[f32]) -> f64 { + (pcm.iter().map(|&v| f64::from(v) * f64::from(v)).sum::() / pcm.len().max(1) as f64).sqrt() +} + +/// Every generated layout, opened the way a timeline source is opened: wider +/// than mono folds to stereo, mono stays mono, and neither decodes to silence +/// (the replica's mono `corner-cut` exists because the incumbent did). +#[test] +fn the_replicas_open_path_lands_on_audible_pcm() { + let cases = [ + ("ac3-5.1-48000.ac3", "ac3", 48_000, 5, 2), + ("ac3-stereo-48000.ac3", "ac3", 48_000, 2, 2), + ("ac3-mono-44100.ac3", "ac3", 44_100, 1, 1), + ("eac3-5.1-48000.eac3", "eac3", 48_000, 5, 2), + ("eac3-mono-48000.eac3", "eac3", 48_000, 1, 1), + ]; + let mut ran = 0; + for (name, codec, rate, nfchans_want, channels_want) in cases { + let Some(data) = fixture(name) else { continue }; + ran += 1; + + let (sample_rate, nfchans) = header(codec, &data); + assert_eq!(sample_rate, rate, "{name}: sample rate"); + assert_eq!(nfchans, nfchans_want, "{name}: nfchans"); + + let requested = (nfchans > 1).then_some(2); + let mut decoder = ac3_decoder(codec, requested); + let (pcm, samples) = decode_ac3(&mut decoder, &data).expect("the first syncframe decoded"); + let channels = (pcm.len() as u64 / samples.max(1)) as u16; + assert_eq!(channels, channels_want, "{name}: decoded channels"); + assert!(samples > 0, "{name}: no samples"); + assert!(rms(&pcm) > 1e-3, "{name}: decoded to silence, rms {}", rms(&pcm)); + + // The replica then feeds the rest of the stream frame by frame; a + // second frame proves the packet walk does not desync on the shim's + // conversion. + let size = ec_ac3::frame_size(&data).expect("frame size"); + if let Some(next) = data.get(size..).filter(|rest| rest.len() > size) { + let (pcm, samples) = decode_ac3(&mut decoder, next).expect("the second syncframe"); + assert_eq!((pcm.len() as u64 / samples.max(1)) as u16, channels_want); + } + } + assert!(ran > 0, "no AC-3 fixtures: run scripts/gen-fixtures.sh"); +} diff --git a/shims/oxideav-core/src/lib.rs b/shims/oxideav-core/src/lib.rs index e124cd3c..e96c4537 100644 --- a/shims/oxideav-core/src/lib.rs +++ b/shims/oxideav-core/src/lib.rs @@ -133,6 +133,72 @@ impl fmt::Display for CodecId { } } +impl From<&str> for CodecId { + fn from(s: &str) -> CodecId { + CodecId(s.to_owned()) + } +} + +impl From for CodecId { + fn from(s: String) -> CodecId { + CodecId(s) + } +} + +/// How a codec is named by a container, so a demuxer can map what it read to a +/// registration. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum CodecTag { + /// A four-character code, as mp4 sample entries and RIFF write it. + FourCc([u8; 4]), + /// An MPEG-4 `ObjectTypeIndication`. + Mp4ObjectType(u8), + /// A Matroska `CodecID` string. + Matroska(String), +} + +impl CodecTag { + /// The four-character code `code`. + pub fn fourcc(code: &[u8; 4]) -> CodecTag { + CodecTag::FourCc(*code) + } + + /// The MPEG-4 object type `oti`. + pub fn mp4_object_type(oti: u8) -> CodecTag { + CodecTag::Mp4ObjectType(oti) + } + + /// The Matroska `CodecID` `id`. + pub fn matroska(id: impl Into) -> CodecTag { + CodecTag::Matroska(id.into()) + } +} + +/// How samples are laid out in a video frame. Only the format the family's own +/// encoders take and hand out is named; a caller that needs another adds it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum PixelFormat { + /// Planar 4:2:0 8-bit. + #[default] + Yuv420P, +} + +/// A codec's string-keyed knobs, parsed by whichever codec declares them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CodecOptions(HashMap); + +impl CodecOptions { + /// The value set for `key`, if any. + pub fn get(&self, key: &str) -> Option<&str> { + self.0.get(key).map(String::as_str) + } + + /// Set `key` to `value`, replacing what was there. + pub fn set(&mut self, key: impl Into, value: impl Into) { + self.0.insert(key.into(), value.into()); + } +} + /// What kind of stream a set of parameters describes. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum MediaType { @@ -164,8 +230,12 @@ pub struct CodecParameters { pub width: Option, /// Coded height. pub height: Option, + /// How a video stream's samples are laid out. + pub pixel_format: Option, /// Codec setup bytes. pub extradata: Vec, + /// Codec-specific knobs, read by whichever codec declares them. + pub options: CodecOptions, } impl CodecParameters { @@ -222,12 +292,13 @@ pub struct StreamInfo { } /// One decoded picture. +/// +/// No dimensions: the incumbent states them on the stream's +/// [`CodecParameters`] and puts only the row stride on the plane, and a codec +/// crate outside this workspace writes the literal (`oxideav-h265`'s decoder +/// does), so the field list is the incumbent's and not ours to improve. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct VideoFrame { - /// Width in pixels. - pub width: u32, - /// Height in pixels. - pub height: u32, /// Presentation time in the stream's time base. pub pts: Option, /// One plane per component group; packed formats have exactly one. @@ -267,8 +338,6 @@ impl From for Frame { fn from(frame: ec_core::Frame) -> Frame { match frame { ec_core::Frame::Video(video) => Frame::Video(VideoFrame { - width: video.width, - height: video.height, pts: video.pts.map(|t| t.ticks), planes: video .planes @@ -299,6 +368,35 @@ pub trait Decoder: Send { /// Take one frame, or [`Error::NeedMore`] when the decoder wants another /// packet first. fn receive_frame(&mut self) -> Result; + + /// Signal end of input, so whatever is held back becomes available through + /// [`receive_frame`](Decoder::receive_frame) and then [`Error::Eof`]. + /// + /// The default is for a decoder that holds nothing back — one packet in, + /// one frame out, which is what the AC-3 path is. + fn flush(&mut self) -> Result<()> { + Ok(()) + } +} + +/// An encoder: frames in, packets out. +pub trait Encoder: Send { + /// The codec this produces. + fn codec_id(&self) -> &CodecId; + + /// Parameters describing the stream it produces, for the muxer. + fn output_params(&self) -> &CodecParameters; + + /// Feed one uncompressed frame. + fn send_frame(&mut self, frame: &Frame) -> Result<()>; + + /// Take one packet, or [`Error::NeedMore`] when the encoder wants another + /// frame first. + fn receive_packet(&mut self) -> Result; + + /// Signal end of input, so the lookahead drains into + /// [`receive_packet`](Encoder::receive_packet). + fn flush(&mut self) -> Result<()>; } /// A container writer. @@ -319,6 +417,9 @@ pub trait Muxer: Send { /// How a codec crate hands out decoders. pub type DecoderFactory = fn(&CodecParameters) -> Result>; +/// How a codec crate hands out encoders. +pub type EncoderFactory = fn(&CodecParameters) -> Result>; + /// One codec's registration. #[derive(Clone)] pub struct CodecInfo { @@ -326,6 +427,10 @@ pub struct CodecInfo { pub id: CodecId, /// How to build a decoder for it. pub decoder_factory: Option, + /// How to build an encoder for it. + pub encoder_factory: Option, + /// The container-level names that mean this codec. + pub tags: Vec, } impl CodecInfo { @@ -334,6 +439,8 @@ impl CodecInfo { CodecInfo { id, decoder_factory: None, + encoder_factory: None, + tags: Vec::new(), } } @@ -342,6 +449,18 @@ impl CodecInfo { self.decoder_factory = Some(factory); self } + + /// The same registration, with an encoder. + pub fn encoder(mut self, factory: EncoderFactory) -> CodecInfo { + self.encoder_factory = Some(factory); + self + } + + /// The same registration, claiming `tags` on top of whatever it claimed. + pub fn tags(mut self, tags: impl IntoIterator) -> CodecInfo { + self.tags.extend(tags); + self + } } /// The codecs a caller has registered, in registration order per id. @@ -382,6 +501,42 @@ impl CodecRegistry { } } +/// What a codec crate is handed to register itself into. +/// +/// The incumbent's context carries four sub-registries; this one carries the +/// codecs, because a container, source or filter crate registering into the +/// replica's build does not exist. +#[derive(Clone, Default)] +pub struct RuntimeContext { + /// Decoder and encoder factories, by codec id. + pub codecs: CodecRegistry, +} + +impl RuntimeContext { + /// An empty context. + pub fn new() -> RuntimeContext { + RuntimeContext::default() + } +} + +/// Declare a codec crate's registration entry point, as the family's crates +/// spell it: `oxideav_core::register!("h265", register);`. +/// +/// The name is carried for documentation only, exactly as the incumbent does — +/// what the generated `__oxideav_entry` runs is `$func`. +#[macro_export] +macro_rules! register { + ($name:literal, $func:path) => { + /// This crate's registration entry point, generated by + /// [`oxideav_core::register!`]. + #[doc(hidden)] + pub fn __oxideav_entry(ctx: &mut $crate::RuntimeContext) { + let _ = $name; + $func(ctx); + } + }; +} + /// A [`Decoder`] over one of the family's own, converting the frames on the way /// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap. pub struct EcDecoder { @@ -460,7 +615,6 @@ mod tests { let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else { panic!("a video frame stays a video frame"); }; - assert_eq!((frame.width, frame.height), (1, 1)); assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]); assert_eq!(frame.planes[0].stride, 4); diff --git a/shims/oxideav-sub-image/src/lib.rs b/shims/oxideav-sub-image/src/lib.rs index eb7508b6..48c9c040 100644 --- a/shims/oxideav-sub-image/src/lib.rs +++ b/shims/oxideav-sub-image/src/lib.rs @@ -71,10 +71,13 @@ mod tests { let Ok(Frame::Video(frame)) = decoder.receive_frame() else { panic!("a display set is a picture"); }; - assert_eq!((frame.width, frame.height), (4, 2)); + // A 4x2 canvas: no dimensions on the frame, so the row stride and the + // byte count are what state them. + assert_eq!(frame.planes[0].stride, 4 * 4); let data = frame.planes.into_iter().next().unwrap().data; assert_eq!(data.len(), 4 * 2 * 4); - assert_eq!(&data[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); + // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`). + assert_eq!(&data[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]); assert_eq!(&data[0..4], &[0, 0, 0, 0]); } } diff --git a/shims/oxideav-sub-image/tests/replica_call_shapes.rs b/shims/oxideav-sub-image/tests/replica_call_shapes.rs index 8879674a..b7f8e223 100644 --- a/shims/oxideav-sub-image/tests/replica_call_shapes.rs +++ b/shims/oxideav-sub-image/tests/replica_call_shapes.rs @@ -102,7 +102,8 @@ fn a_matroska_pgs_block_decodes_the_way_the_replica_decodes_one() { // The whole canvas, transparent where the cue paints nothing. assert_eq!(rgba.len(), 4 * 2 * 4); assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); - assert_eq!(&rgba[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); + // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`). + assert_eq!(&rgba[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]); // The erase set after the composition must not be what gets decoded: the // loop above stops at the `END` that closes the showing set.