WebP decoding, VP8 key frames and VP8L
Browse files at this commit22ac6ab79f8452c9caedc0865f0072e54f5b0f1dParent: 7eed0e7- feat
- WebP decoding, VP8 key frames and VP8L
12 changed files +3845 -32
- crates/ec-image/src/lib.rs +3 -8
- crates/ec-image/src/webp/mod.rs +370 -0
- crates/ec-image/src/webp/vp8.rs +1612 -0
- crates/ec-image/src/webp/vp8_tables.rs +500 -0
- crates/ec-image/src/webp/vp8l.rs +896 -0
- crates/ec-pgs/src/lib.rs +24 -14
- scripts/pgs-white-level.sh +38 -0
- shims/oxideav-ac3/src/lib.rs +129 -0
- shims/oxideav-ac3/tests/edith_surface.rs +105 -0
- shims/oxideav-core/src/lib.rs +161 -7
- shims/oxideav-sub-image/src/lib.rs +5 -2
- shims/oxideav-sub-image/tests/replica_call_shapes.rs +2 -1
crates/ec-image/src/lib.rsmodified+3 -8
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | pub mod jpeg; |
| 35 | 35 | pub mod png; |
| 36 | 36 | mod upsample; |
| 37 | +pub mod webp; | |
| 37 | 38 | |
| 38 | 39 | use ec_core::{PixelFormat, Plane, VideoFrame}; |
| 39 | 40 | |
| @@ -340,10 +341,7 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> { | ||
| 340 | 341 | match ImageFormat::guess(data) { |
| 341 | 342 | Some(ImageFormat::Png) => png::decode(data, limits), |
| 342 | 343 | Some(ImageFormat::Jpeg) => jpeg::decode(data, limits), |
| 343 | - Some(ImageFormat::WebP) => Err(Error::unsupported( | |
| 344 | - "WebP", | |
| 345 | - "the WebP decoder is a later stage of this crate", | |
| 346 | - )), | |
| 344 | + Some(ImageFormat::WebP) => webp::decode(data, limits), | |
| 347 | 345 | None => Err(Error::unsupported( |
| 348 | 346 | "image", |
| 349 | 347 | "no PNG, JPEG or WebP signature at the start of the data", |
| @@ -356,10 +354,7 @@ pub fn info(data: &[u8]) -> Result<Info> { | ||
| 356 | 354 | match ImageFormat::guess(data) { |
| 357 | 355 | Some(ImageFormat::Png) => png::info(data), |
| 358 | 356 | Some(ImageFormat::Jpeg) => jpeg::info(data), |
| 359 | - Some(ImageFormat::WebP) => Err(Error::unsupported( | |
| 360 | - "WebP", | |
| 361 | - "the WebP decoder is a later stage of this crate", | |
| 362 | - )), | |
| 357 | + Some(ImageFormat::WebP) => webp::info(data), | |
| 363 | 358 | None => Err(Error::unsupported( |
| 364 | 359 | "image", |
| 365 | 360 | "no PNG, JPEG or WebP signature at the start of the data", |
crates/ec-image/src/webp/mod.rsadded+370 -0
| @@ -0,0 +1,370 @@ | ||
| 1 | +//! WebP: the RIFF container, its lossy (`VP8 `) and lossless (`VP8L`) payloads, | |
| 2 | +//! and the separate alpha plane (`ALPH`) an extended file may carry. | |
| 3 | +//! | |
| 4 | +//! Animation is refused by name. A still decoder that quietly handed back the | |
| 5 | +//! first frame of an animation would make "this file plays" and "this file | |
| 6 | +//! decoded" indistinguishable to its caller. | |
| 7 | + | |
| 8 | +pub mod vp8; | |
| 9 | +mod vp8_tables; | |
| 10 | +pub mod vp8l; | |
| 11 | + | |
| 12 | +use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; | |
| 13 | +use ec_core::{Error, Result}; | |
| 14 | + | |
| 15 | +/// One RIFF chunk. | |
| 16 | +struct Chunk<'a> { | |
| 17 | + tag: [u8; 4], | |
| 18 | + data: &'a [u8], | |
| 19 | +} | |
| 20 | + | |
| 21 | +/// Walk the chunks inside a `WEBP` RIFF file. | |
| 22 | +fn chunks(data: &[u8]) -> Result<Vec<Chunk<'_>>> { | |
| 23 | + let riff_size = data | |
| 24 | + .get(4..8) | |
| 25 | + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize) | |
| 26 | + .ok_or_else(|| Error::corrupt("WebP: truncated RIFF header"))?; | |
| 27 | + // The declared size may exceed what is present in a truncated file; take | |
| 28 | + // whichever ends sooner rather than trusting the header. | |
| 29 | + let end = (riff_size + 8).min(data.len()); | |
| 30 | + let mut out = Vec::new(); | |
| 31 | + let mut at = 12usize; | |
| 32 | + while at + 8 <= end { | |
| 33 | + let tag = [data[at], data[at + 1], data[at + 2], data[at + 3]]; | |
| 34 | + let size = | |
| 35 | + u32::from_le_bytes([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]) as usize; | |
| 36 | + let body = data | |
| 37 | + .get(at + 8..at + 8 + size) | |
| 38 | + .ok_or_else(|| Error::corrupt("WebP: chunk runs past the file"))?; | |
| 39 | + out.push(Chunk { tag, data: body }); | |
| 40 | + // Chunks are padded to an even length. | |
| 41 | + at += 8 + size + (size & 1); | |
| 42 | + } | |
| 43 | + if out.is_empty() { | |
| 44 | + return Err(Error::corrupt("WebP: no chunks")); | |
| 45 | + } | |
| 46 | + Ok(out) | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Dimensions from the container's headers alone. | |
| 50 | +pub fn info(data: &[u8]) -> Result<Info> { | |
| 51 | + let chunks = chunks(data)?; | |
| 52 | + for chunk in &chunks { | |
| 53 | + match &chunk.tag { | |
| 54 | + b"VP8X" if chunk.data.len() >= 10 => { | |
| 55 | + let d = chunk.data; | |
| 56 | + let width = 1 + (u32::from(d[4]) | u32::from(d[5]) << 8 | u32::from(d[6]) << 16); | |
| 57 | + let height = 1 + (u32::from(d[7]) | u32::from(d[8]) << 8 | u32::from(d[9]) << 16); | |
| 58 | + return Ok(Info { | |
| 59 | + format: ImageFormat::WebP, | |
| 60 | + width, | |
| 61 | + height, | |
| 62 | + }); | |
| 63 | + } | |
| 64 | + b"VP8 " => { | |
| 65 | + let (width, height) = vp8::dimensions(chunk.data)?; | |
| 66 | + return Ok(Info { | |
| 67 | + format: ImageFormat::WebP, | |
| 68 | + width, | |
| 69 | + height, | |
| 70 | + }); | |
| 71 | + } | |
| 72 | + b"VP8L" => { | |
| 73 | + let d = chunk.data; | |
| 74 | + if d.len() < 5 || d[0] != 0x2f { | |
| 75 | + return Err(Error::corrupt("WebP: short VP8L header")); | |
| 76 | + } | |
| 77 | + let packed = u32::from_le_bytes([d[1], d[2], d[3], d[4]]); | |
| 78 | + return Ok(Info { | |
| 79 | + format: ImageFormat::WebP, | |
| 80 | + width: (packed & 0x3fff) + 1, | |
| 81 | + height: ((packed >> 14) & 0x3fff) + 1, | |
| 82 | + }); | |
| 83 | + } | |
| 84 | + _ => {} | |
| 85 | + } | |
| 86 | + } | |
| 87 | + Err(Error::corrupt("WebP: no image chunk")) | |
| 88 | +} | |
| 89 | + | |
| 90 | +/// Decode a WebP file. | |
| 91 | +pub fn decode(data: &[u8], limits: Limits) -> Result<Image> { | |
| 92 | + let chunks = chunks(data)?; | |
| 93 | + let mut meta = Metadata::default(); | |
| 94 | + let mut alpha: Option<&[u8]> = None; | |
| 95 | + let mut image: Option<(&[u8; 4], &[u8])> = None; | |
| 96 | + | |
| 97 | + for chunk in &chunks { | |
| 98 | + match &chunk.tag { | |
| 99 | + b"VP8X" => { | |
| 100 | + let flags = chunk | |
| 101 | + .data | |
| 102 | + .first() | |
| 103 | + .copied() | |
| 104 | + .ok_or_else(|| Error::corrupt("WebP: empty VP8X"))?; | |
| 105 | + if flags & 0x02 != 0 { | |
| 106 | + return Err(Error::unsupported( | |
| 107 | + "animated WebP", | |
| 108 | + "this decoder returns one still picture, not a sequence of frames", | |
| 109 | + )); | |
| 110 | + } | |
| 111 | + } | |
| 112 | + b"ANIM" | b"ANMF" => { | |
| 113 | + return Err(Error::unsupported( | |
| 114 | + "animated WebP", | |
| 115 | + "this decoder returns one still picture, not a sequence of frames", | |
| 116 | + )); | |
| 117 | + } | |
| 118 | + b"ALPH" => alpha = Some(chunk.data), | |
| 119 | + b"VP8 " | b"VP8L" => { | |
| 120 | + if image.is_none() { | |
| 121 | + image = Some((&chunk.tag, chunk.data)); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + b"EXIF" => { | |
| 125 | + if let Some(o) = exif_orientation(chunk.data) { | |
| 126 | + meta.orientation = Some(o); | |
| 127 | + } | |
| 128 | + } | |
| 129 | + _ => {} | |
| 130 | + } | |
| 131 | + } | |
| 132 | + | |
| 133 | + let (tag, body) = image.ok_or_else(|| Error::corrupt("WebP: no VP8 or VP8L chunk"))?; | |
| 134 | + if tag == b"VP8L" { | |
| 135 | + let argb = vp8l::decode(body, limits)?; | |
| 136 | + let mut rgba = Vec::with_capacity(argb.pixels.len() * 4); | |
| 137 | + for p in &argb.pixels { | |
| 138 | + rgba.extend_from_slice(&[ | |
| 139 | + ((p >> 16) & 0xff) as u8, | |
| 140 | + ((p >> 8) & 0xff) as u8, | |
| 141 | + (p & 0xff) as u8, | |
| 142 | + ((p >> 24) & 0xff) as u8, | |
| 143 | + ]); | |
| 144 | + } | |
| 145 | + return Ok(Image { | |
| 146 | + width: argb.width, | |
| 147 | + height: argb.height, | |
| 148 | + pixels: Pixels::Rgba8(rgba), | |
| 149 | + meta, | |
| 150 | + }); | |
| 151 | + } | |
| 152 | + | |
| 153 | + let frame = vp8::decode(body, limits)?; | |
| 154 | + let (w, h) = (frame.width as usize, frame.height as usize); | |
| 155 | + // Chroma is stored at half resolution and upsampled with the same triangle | |
| 156 | + // filter libwebp uses; nearest-neighbour here costs about a decibel. | |
| 157 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 158 | + let crop = |plane: &[u8]| -> Vec<u8> { | |
| 159 | + (0..ch) | |
| 160 | + .flat_map(|y| plane[y * frame.stride_uv..y * frame.stride_uv + cw].to_vec()) | |
| 161 | + .collect() | |
| 162 | + }; | |
| 163 | + let u_plane = crate::upsample::upsample(&crop(&frame.u), cw, ch, w, h); | |
| 164 | + let v_plane = crate::upsample::upsample(&crop(&frame.v), cw, ch, w, h); | |
| 165 | + let alpha_plane = match alpha { | |
| 166 | + Some(chunk) => Some(decode_alpha(chunk, frame.width, frame.height)?), | |
| 167 | + None => None, | |
| 168 | + }; | |
| 169 | + let channels = if alpha_plane.is_some() { 4 } else { 3 }; | |
| 170 | + let mut out = vec![0u8; w * h * channels]; | |
| 171 | + for y in 0..h { | |
| 172 | + for x in 0..w { | |
| 173 | + let luma = frame.y[y * frame.stride_y + x]; | |
| 174 | + let cb = u_plane[y * w + x]; | |
| 175 | + let cr = v_plane[y * w + x]; | |
| 176 | + let rgb = yuv_to_rgb(luma, cb, cr); | |
| 177 | + let at = (y * w + x) * channels; | |
| 178 | + out[at..at + 3].copy_from_slice(&rgb); | |
| 179 | + if let Some(plane) = &alpha_plane { | |
| 180 | + out[at + 3] = plane[y * w + x]; | |
| 181 | + } | |
| 182 | + } | |
| 183 | + } | |
| 184 | + Ok(Image { | |
| 185 | + width: frame.width, | |
| 186 | + height: frame.height, | |
| 187 | + pixels: if channels == 4 { | |
| 188 | + Pixels::Rgba8(out) | |
| 189 | + } else { | |
| 190 | + Pixels::Rgb8(out) | |
| 191 | + }, | |
| 192 | + meta, | |
| 193 | + }) | |
| 194 | +} | |
| 195 | + | |
| 196 | +/// BT.601 studio-swing YCbCr to RGB, in 16-bit fixed point. | |
| 197 | +fn yuv_to_rgb(y: u8, u: u8, v: u8) -> [u8; 3] { | |
| 198 | + let y = (i32::from(y) - 16) * 76284; | |
| 199 | + let u = i32::from(u) - 128; | |
| 200 | + let v = i32::from(v) - 128; | |
| 201 | + let r = y + 104595 * v; | |
| 202 | + let g = y - 25624 * u - 53281 * v; | |
| 203 | + let b = y + 132251 * u; | |
| 204 | + [ | |
| 205 | + ((r + 32768) >> 16).clamp(0, 255) as u8, | |
| 206 | + ((g + 32768) >> 16).clamp(0, 255) as u8, | |
| 207 | + ((b + 32768) >> 16).clamp(0, 255) as u8, | |
| 208 | + ] | |
| 209 | +} | |
| 210 | + | |
| 211 | +/// Decode an `ALPH` chunk into one byte of alpha per pixel. | |
| 212 | +fn decode_alpha(chunk: &[u8], width: u32, height: u32) -> Result<Vec<u8>> { | |
| 213 | + let head = *chunk | |
| 214 | + .first() | |
| 215 | + .ok_or_else(|| Error::corrupt("WebP: empty ALPH chunk"))?; | |
| 216 | + let method = head & 0x03; | |
| 217 | + let filter = (head >> 2) & 0x03; | |
| 218 | + let body = &chunk[1..]; | |
| 219 | + let count = (width as usize) * (height as usize); | |
| 220 | + let mut plane = match method { | |
| 221 | + 0 => { | |
| 222 | + if body.len() < count { | |
| 223 | + return Err(Error::corrupt("WebP: ALPH shorter than the picture")); | |
| 224 | + } | |
| 225 | + body[..count].to_vec() | |
| 226 | + } | |
| 227 | + 1 => { | |
| 228 | + // Lossless-coded, dimensions implied; the alpha lives in green. | |
| 229 | + let argb = vp8l::decode_implicit(body, width, height)?; | |
| 230 | + argb.iter().map(|p| ((p >> 8) & 0xff) as u8).collect() | |
| 231 | + } | |
| 232 | + other => { | |
| 233 | + return Err(Error::corrupt(format!( | |
| 234 | + "WebP: ALPH compression method {other}" | |
| 235 | + ))); | |
| 236 | + } | |
| 237 | + }; | |
| 238 | + unfilter_alpha(&mut plane, width as usize, height as usize, filter); | |
| 239 | + Ok(plane) | |
| 240 | +} | |
| 241 | + | |
| 242 | +/// Undo the alpha plane's spatial filter (none / horizontal / vertical / | |
| 243 | +/// gradient), in place. | |
| 244 | +fn unfilter_alpha(plane: &mut [u8], width: usize, height: usize, filter: u8) { | |
| 245 | + if filter == 0 { | |
| 246 | + return; | |
| 247 | + } | |
| 248 | + for y in 0..height { | |
| 249 | + for x in 0..width { | |
| 250 | + let index = y * width + x; | |
| 251 | + let left = if x > 0 { plane[index - 1] } else { 0 }; | |
| 252 | + let above = if y > 0 { plane[index - width] } else { 0 }; | |
| 253 | + let above_left = if x > 0 && y > 0 { | |
| 254 | + plane[index - width - 1] | |
| 255 | + } else { | |
| 256 | + 0 | |
| 257 | + }; | |
| 258 | + let predictor = if x == 0 && y == 0 { | |
| 259 | + 0 | |
| 260 | + } else if y == 0 { | |
| 261 | + // The top row has no pixel above, so it predicts from the left | |
| 262 | + // whatever the filter says, and the left column from above. | |
| 263 | + left | |
| 264 | + } else if x == 0 { | |
| 265 | + above | |
| 266 | + } else { | |
| 267 | + match filter { | |
| 268 | + 1 => left, | |
| 269 | + 2 => above, | |
| 270 | + _ => (i32::from(left) + i32::from(above) - i32::from(above_left)).clamp(0, 255) | |
| 271 | + as u8, | |
| 272 | + } | |
| 273 | + }; | |
| 274 | + plane[index] = predictor.wrapping_add(plane[index]); | |
| 275 | + } | |
| 276 | + } | |
| 277 | +} | |
| 278 | + | |
| 279 | +/// EXIF orientation out of a bare TIFF block (no `Exif\0\0` prefix here). | |
| 280 | +fn exif_orientation(data: &[u8]) -> Option<u8> { | |
| 281 | + let little = match data.get(..2)? { | |
| 282 | + b"II" => true, | |
| 283 | + b"MM" => false, | |
| 284 | + _ => return None, | |
| 285 | + }; | |
| 286 | + let u16_at = |at: usize| -> Option<u16> { | |
| 287 | + let b = data.get(at..at + 2)?; | |
| 288 | + Some(if little { | |
| 289 | + u16::from_le_bytes([b[0], b[1]]) | |
| 290 | + } else { | |
| 291 | + u16::from_be_bytes([b[0], b[1]]) | |
| 292 | + }) | |
| 293 | + }; | |
| 294 | + let u32_at = |at: usize| -> Option<u32> { | |
| 295 | + let b = data.get(at..at + 4)?; | |
| 296 | + Some(if little { | |
| 297 | + u32::from_le_bytes([b[0], b[1], b[2], b[3]]) | |
| 298 | + } else { | |
| 299 | + u32::from_be_bytes([b[0], b[1], b[2], b[3]]) | |
| 300 | + }) | |
| 301 | + }; | |
| 302 | + if u16_at(2)? != 42 { | |
| 303 | + return None; | |
| 304 | + } | |
| 305 | + let ifd = u32_at(4)? as usize; | |
| 306 | + let count = usize::from(u16_at(ifd)?); | |
| 307 | + for i in 0..count { | |
| 308 | + let entry = ifd + 2 + i * 12; | |
| 309 | + if u16_at(entry)? == 0x0112 { | |
| 310 | + let value = u16_at(entry + 8)?; | |
| 311 | + return (1..=8).contains(&value).then_some(value as u8); | |
| 312 | + } | |
| 313 | + } | |
| 314 | + None | |
| 315 | +} | |
| 316 | + | |
| 317 | +#[cfg(test)] | |
| 318 | +mod tests { | |
| 319 | + use super::*; | |
| 320 | + | |
| 321 | + fn riff(chunks: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> { | |
| 322 | + let mut body = b"WEBP".to_vec(); | |
| 323 | + for (tag, data) in chunks { | |
| 324 | + body.extend_from_slice(*tag); | |
| 325 | + body.extend_from_slice(&(data.len() as u32).to_le_bytes()); | |
| 326 | + body.extend_from_slice(data); | |
| 327 | + if data.len() % 2 == 1 { | |
| 328 | + body.push(0); | |
| 329 | + } | |
| 330 | + } | |
| 331 | + let mut out = b"RIFF".to_vec(); | |
| 332 | + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); | |
| 333 | + out.extend_from_slice(&body); | |
| 334 | + out | |
| 335 | + } | |
| 336 | + | |
| 337 | + #[test] | |
| 338 | + fn odd_sized_chunks_are_padded_and_still_walked() { | |
| 339 | + let file = riff(&[(b"XXXX", vec![1, 2, 3]), (b"VP8L", vec![0x2f, 0, 0, 0, 0])]); | |
| 340 | + let found = chunks(&file).unwrap(); | |
| 341 | + assert_eq!(found.len(), 2); | |
| 342 | + assert_eq!(&found[1].tag, b"VP8L"); | |
| 343 | + assert_eq!(found[1].data.len(), 5); | |
| 344 | + } | |
| 345 | + | |
| 346 | + #[test] | |
| 347 | + fn animation_is_refused_by_name() { | |
| 348 | + let mut vp8x = vec![0x02, 0, 0, 0]; | |
| 349 | + vp8x.extend_from_slice(&[15, 0, 0, 15, 0, 0]); | |
| 350 | + let file = riff(&[(b"VP8X", vp8x), (b"ANMF", vec![0; 16])]); | |
| 351 | + let err = decode(&file, Limits::default()).unwrap_err(); | |
| 352 | + assert!(format!("{err}").contains("animated"), "{err}"); | |
| 353 | + } | |
| 354 | + | |
| 355 | + #[test] | |
| 356 | + fn yuv_conversion_puts_studio_black_and_white_at_the_ends() { | |
| 357 | + assert_eq!(yuv_to_rgb(16, 128, 128), [0, 0, 0]); | |
| 358 | + assert_eq!(yuv_to_rgb(235, 128, 128), [255, 255, 255]); | |
| 359 | + let grey = yuv_to_rgb(126, 128, 128); | |
| 360 | + assert!(grey[0] == grey[1] && grey[1] == grey[2], "{grey:?}"); | |
| 361 | + } | |
| 362 | + | |
| 363 | + #[test] | |
| 364 | + fn the_alpha_gradient_filter_inverts_its_prediction() { | |
| 365 | + // Horizontal filter: each stored byte is a difference from the left. | |
| 366 | + let mut plane = vec![10u8, 5, 250, 1]; | |
| 367 | + unfilter_alpha(&mut plane, 4, 1, 1); | |
| 368 | + assert_eq!(plane, vec![10, 15, 9, 10]); | |
| 369 | + } | |
| 370 | +} |
crates/ec-image/src/webp/vp8.rsadded+1612 -0
| @@ -0,0 +1,1612 @@ | ||
| 1 | +//! VP8 key frame decoding (RFC 6386), which is all a still WebP contains. | |
| 2 | +//! | |
| 3 | +//! A `VP8 ` chunk in a still image is one key frame: intra prediction only, no | |
| 4 | +//! reference buffers and no motion vectors. Everything else the frame format | |
| 5 | +//! carries is here — the boolean entropy decoder, segmentation, per-partition | |
| 6 | +//! token decoding, the WHT/DCT inversions, all sixteen prediction modes and | |
| 7 | +//! both loop filters — because a key frame uses all of it. | |
| 8 | +//! | |
| 9 | +//! Inter-frame syntax (motion vectors, reference selection, sub-pixel | |
| 10 | +//! interpolation) is deliberately absent: this crate decodes stills, and a | |
| 11 | +//! decoder that pretends to accept an inter frame it cannot reconstruct is | |
| 12 | +//! worse than one that names the refusal. | |
| 13 | + | |
| 14 | +use super::vp8_tables::{ | |
| 15 | + AC_QLOOKUP, COEFF_BANDS, COEFF_UPDATE_PROBS, DC_QLOOKUP, DEFAULT_COEFF_PROBS, KF_BMODE_PROBS, | |
| 16 | + ZIGZAG, | |
| 17 | +}; | |
| 18 | +use crate::Limits; | |
| 19 | +use ec_core::{Error, Result}; | |
| 20 | + | |
| 21 | +/// 16x16 luma / 8x8 chroma prediction modes. | |
| 22 | +const DC_PRED: usize = 0; | |
| 23 | +const V_PRED: usize = 1; | |
| 24 | +const H_PRED: usize = 2; | |
| 25 | +const TM_PRED: usize = 3; | |
| 26 | +const B_PRED: usize = 4; | |
| 27 | + | |
| 28 | +/// Trees are flat arrays: a positive entry is the next node, anything else is | |
| 29 | +/// the leaf value negated (so leaf 0 encodes as 0, which is never a node). | |
| 30 | +const KF_YMODE_TREE: [i8; 8] = [-(B_PRED as i8), 2, 4, 6, 0, -1, -2, -3]; | |
| 31 | +const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128]; | |
| 32 | +const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; | |
| 33 | +const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183]; | |
| 34 | +const BMODE_TREE: [i8; 18] = [ | |
| 35 | + 0, 2, -1, 4, -2, 6, 8, 12, -3, 10, -5, -6, -4, 14, -7, 16, -8, -9, | |
| 36 | +]; | |
| 37 | +const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3]; | |
| 38 | +const COEFF_TREE: [i8; 22] = [ | |
| 39 | + -11, 2, 0, 4, -1, 6, 8, 12, -2, 10, -3, -4, 14, 16, -5, -6, 18, 20, -7, -8, -9, -10, | |
| 40 | +]; | |
| 41 | + | |
| 42 | +/// Extra-bit probabilities for the six "category" tokens. | |
| 43 | +const PCAT: [&[u8]; 6] = [ | |
| 44 | + &[159], | |
| 45 | + &[165, 145], | |
| 46 | + &[173, 148, 140], | |
| 47 | + &[176, 155, 140, 135], | |
| 48 | + &[180, 157, 141, 134, 130], | |
| 49 | + &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129], | |
| 50 | +]; | |
| 51 | +/// Smallest value each category token stands for. | |
| 52 | +const CAT_BASE: [i32; 6] = [5, 7, 11, 19, 35, 67]; | |
| 53 | + | |
| 54 | +/// Subblock modes, in the enumeration order the trees and tables use. | |
| 55 | +const B_DC_PRED: usize = 0; | |
| 56 | +const B_TM_PRED: usize = 1; | |
| 57 | +const B_VE_PRED: usize = 2; | |
| 58 | +const B_HE_PRED: usize = 3; | |
| 59 | + | |
| 60 | +/// The boolean entropy decoder of RFC 6386 section 7.3. | |
| 61 | +pub struct BoolDecoder<'a> { | |
| 62 | + data: &'a [u8], | |
| 63 | + at: usize, | |
| 64 | + range: u32, | |
| 65 | + value: u32, | |
| 66 | + bit_count: i32, | |
| 67 | +} | |
| 68 | + | |
| 69 | +impl<'a> BoolDecoder<'a> { | |
| 70 | + /// Start decoding at the beginning of `data`. | |
| 71 | + pub fn new(data: &'a [u8]) -> BoolDecoder<'a> { | |
| 72 | + let mut value = 0u32; | |
| 73 | + for i in 0..2 { | |
| 74 | + value = (value << 8) | u32::from(data.get(i).copied().unwrap_or(0)); | |
| 75 | + } | |
| 76 | + BoolDecoder { | |
| 77 | + data, | |
| 78 | + at: 2, | |
| 79 | + range: 255, | |
| 80 | + value, | |
| 81 | + bit_count: 0, | |
| 82 | + } | |
| 83 | + } | |
| 84 | + | |
| 85 | + /// One bool with probability `prob / 256` of being zero. | |
| 86 | + pub fn bool(&mut self, prob: u8) -> u32 { | |
| 87 | + let split = 1 + (((self.range - 1) * u32::from(prob)) >> 8); | |
| 88 | + let big_split = split << 8; | |
| 89 | + let bit = if self.value >= big_split { | |
| 90 | + self.range -= split; | |
| 91 | + self.value -= big_split; | |
| 92 | + 1 | |
| 93 | + } else { | |
| 94 | + self.range = split; | |
| 95 | + 0 | |
| 96 | + }; | |
| 97 | + while self.range < 128 { | |
| 98 | + self.value <<= 1; | |
| 99 | + self.range <<= 1; | |
| 100 | + self.bit_count += 1; | |
| 101 | + if self.bit_count == 8 { | |
| 102 | + self.bit_count = 0; | |
| 103 | + // Past the end the decoder reads zeros; a truncated partition | |
| 104 | + // then produces a wrong picture, never a panic. | |
| 105 | + self.value |= u32::from(self.data.get(self.at).copied().unwrap_or(0)); | |
| 106 | + self.at += 1; | |
| 107 | + } | |
| 108 | + } | |
| 109 | + bit | |
| 110 | + } | |
| 111 | + | |
| 112 | + /// `n`-bit literal, high bit first, each bit at probability 128. | |
| 113 | + pub fn literal(&mut self, n: u32) -> u32 { | |
| 114 | + let mut v = 0; | |
| 115 | + for _ in 0..n { | |
| 116 | + v = (v << 1) + self.bool(128); | |
| 117 | + } | |
| 118 | + v | |
| 119 | + } | |
| 120 | + | |
| 121 | + /// A magnitude-and-sign field: `flag ? +/- L(n) : 0`. | |
| 122 | + fn signed(&mut self, n: u32) -> i32 { | |
| 123 | + let magnitude = self.literal(n) as i32; | |
| 124 | + if self.bool(128) == 1 { | |
| 125 | + -magnitude | |
| 126 | + } else { | |
| 127 | + magnitude | |
| 128 | + } | |
| 129 | + } | |
| 130 | + | |
| 131 | + /// Optional magnitude-and-sign field. | |
| 132 | + fn maybe_signed(&mut self, n: u32) -> i32 { | |
| 133 | + if self.bool(128) == 1 { | |
| 134 | + self.signed(n) | |
| 135 | + } else { | |
| 136 | + 0 | |
| 137 | + } | |
| 138 | + } | |
| 139 | + | |
| 140 | + /// Walk a tree, reading one bool per node. | |
| 141 | + fn tree(&mut self, tree: &[i8], probs: &[u8], start: usize) -> usize { | |
| 142 | + let mut i = start; | |
| 143 | + loop { | |
| 144 | + let bit = self.bool(probs[i >> 1]) as usize; | |
| 145 | + let next = tree[i + bit]; | |
| 146 | + if next > 0 { | |
| 147 | + i = next as usize; | |
| 148 | + } else { | |
| 149 | + return (-next) as usize; | |
| 150 | + } | |
| 151 | + } | |
| 152 | + } | |
| 153 | + | |
| 154 | + /// True once the decoder has read past the end of its partition. | |
| 155 | + fn exhausted(&self) -> bool { | |
| 156 | + self.at > self.data.len() + 2 | |
| 157 | + } | |
| 158 | +} | |
| 159 | + | |
| 160 | +/// Per-segment quantizer factors: `[dc, ac]` for Y, Y2 and chroma. | |
| 161 | +#[derive(Clone, Copy, Default)] | |
| 162 | +struct Dequant { | |
| 163 | + y: [i32; 2], | |
| 164 | + y2: [i32; 2], | |
| 165 | + uv: [i32; 2], | |
| 166 | +} | |
| 167 | + | |
| 168 | +/// Everything the frame header set up. | |
| 169 | +struct Header { | |
| 170 | + segmentation: bool, | |
| 171 | + update_map: bool, | |
| 172 | + segment_probs: [u8; 3], | |
| 173 | + filter_simple: bool, | |
| 174 | + filter_level: i32, | |
| 175 | + sharpness: i32, | |
| 176 | + delta_enabled: bool, | |
| 177 | + ref_delta: [i32; 4], | |
| 178 | + mode_delta: [i32; 4], | |
| 179 | + segment_lf: [i32; 4], | |
| 180 | + segment_lf_absolute: bool, | |
| 181 | + dequant: [Dequant; 4], | |
| 182 | + coeff_probs: [[[[u8; 11]; 3]; 8]; 4], | |
| 183 | + skip_enabled: bool, | |
| 184 | + skip_prob: u8, | |
| 185 | +} | |
| 186 | + | |
| 187 | +/// What one macroblock decided, kept for the loop filter pass. | |
| 188 | +#[derive(Clone, Copy)] | |
| 189 | +struct MbInfo { | |
| 190 | + y_mode: usize, | |
| 191 | + segment: usize, | |
| 192 | + has_coeffs: bool, | |
| 193 | +} | |
| 194 | + | |
| 195 | +/// A decoded key frame's planes, cropped to the visible picture. | |
| 196 | +pub struct Frame { | |
| 197 | + /// Visible width. | |
| 198 | + pub width: u32, | |
| 199 | + /// Visible height. | |
| 200 | + pub height: u32, | |
| 201 | + /// Luma plane, `stride_y` bytes per row. | |
| 202 | + pub y: Vec<u8>, | |
| 203 | + /// U plane, `stride_uv` bytes per row. | |
| 204 | + pub u: Vec<u8>, | |
| 205 | + /// V plane, `stride_uv` bytes per row. | |
| 206 | + pub v: Vec<u8>, | |
| 207 | + /// Bytes per luma row. | |
| 208 | + pub stride_y: usize, | |
| 209 | + /// Bytes per chroma row. | |
| 210 | + pub stride_uv: usize, | |
| 211 | +} | |
| 212 | + | |
| 213 | +/// Width, height and scale codes from the uncompressed chunk. | |
| 214 | +pub fn dimensions(data: &[u8]) -> Result<(u32, u32)> { | |
| 215 | + let head = data | |
| 216 | + .get(..10) | |
| 217 | + .ok_or_else(|| Error::corrupt("VP8: frame shorter than its header"))?; | |
| 218 | + let tag = u32::from(head[0]) | (u32::from(head[1]) << 8) | (u32::from(head[2]) << 16); | |
| 219 | + if tag & 1 != 0 { | |
| 220 | + return Err(Error::unsupported( | |
| 221 | + "VP8 inter frame in a still image", | |
| 222 | + "a still WebP carries one key frame; there is no reference to predict from", | |
| 223 | + )); | |
| 224 | + } | |
| 225 | + if head[3..6] != [0x9d, 0x01, 0x2a] { | |
| 226 | + return Err(Error::corrupt("VP8: bad key frame start code")); | |
| 227 | + } | |
| 228 | + let width = u32::from(u16::from_le_bytes([head[6], head[7]])) & 0x3fff; | |
| 229 | + let height = u32::from(u16::from_le_bytes([head[8], head[9]])) & 0x3fff; | |
| 230 | + Ok((width, height)) | |
| 231 | +} | |
| 232 | + | |
| 233 | +/// Decode one VP8 key frame. | |
| 234 | +pub fn decode(data: &[u8], limits: Limits) -> Result<Frame> { | |
| 235 | + let (width, height) = dimensions(data)?; | |
| 236 | + limits.check(width, height)?; | |
| 237 | + let tag = u32::from(data[0]) | (u32::from(data[1]) << 8) | (u32::from(data[2]) << 16); | |
| 238 | + let first_part_size = ((tag >> 5) & 0x7ffff) as usize; | |
| 239 | + let body = data | |
| 240 | + .get(10..) | |
| 241 | + .ok_or_else(|| Error::corrupt("VP8: no frame body"))?; | |
| 242 | + let first = body | |
| 243 | + .get(..first_part_size) | |
| 244 | + .ok_or_else(|| Error::corrupt("VP8: first partition runs past the chunk"))?; | |
| 245 | + let mut bd = BoolDecoder::new(first); | |
| 246 | + | |
| 247 | + let _color_space = bd.literal(1); | |
| 248 | + let _clamping = bd.literal(1); | |
| 249 | + let (header, partition_count) = read_header(&mut bd)?; | |
| 250 | + | |
| 251 | + // Token partitions follow the first one, preceded by their sizes. | |
| 252 | + let rest = &body[first_part_size..]; | |
| 253 | + let partitions = split_partitions(rest, partition_count)?; | |
| 254 | + | |
| 255 | + let mb_cols = (width as usize).div_ceil(16); | |
| 256 | + let mb_rows = (height as usize).div_ceil(16); | |
| 257 | + let stride_y = mb_cols * 16; | |
| 258 | + let stride_uv = mb_cols * 8; | |
| 259 | + let mut frame = Frame { | |
| 260 | + width, | |
| 261 | + height, | |
| 262 | + y: vec![0; stride_y * mb_rows * 16], | |
| 263 | + u: vec![0; stride_uv * mb_rows * 8], | |
| 264 | + v: vec![0; stride_uv * mb_rows * 8], | |
| 265 | + stride_y, | |
| 266 | + stride_uv, | |
| 267 | + }; | |
| 268 | + | |
| 269 | + let mut token_decoders: Vec<BoolDecoder<'_>> = | |
| 270 | + partitions.iter().map(|p| BoolDecoder::new(p)).collect(); | |
| 271 | + let mut above_bmodes = vec![B_DC_PRED; mb_cols * 4]; | |
| 272 | + let mut above_nz = vec![[0u8; 9]; mb_cols]; | |
| 273 | + let mut infos = Vec::with_capacity(mb_cols * mb_rows); | |
| 274 | + let mut coeffs = [[0i16; 16]; 25]; | |
| 275 | + let mut bmodes = [B_DC_PRED; 16]; | |
| 276 | + | |
| 277 | + for mb_y in 0..mb_rows { | |
| 278 | + let mut left_bmodes = [B_DC_PRED; 4]; | |
| 279 | + let mut left_nz = [0u8; 9]; | |
| 280 | + for mb_x in 0..mb_cols { | |
| 281 | + // Prediction record: segment, skip flag, then the modes. | |
| 282 | + let segment = if header.segmentation && header.update_map { | |
| 283 | + bd.tree(&SEGMENT_TREE, &header.segment_probs, 0) | |
| 284 | + } else { | |
| 285 | + 0 | |
| 286 | + }; | |
| 287 | + let skip = header.skip_enabled && bd.bool(header.skip_prob) == 1; | |
| 288 | + let y_mode = bd.tree(&KF_YMODE_TREE, &KF_YMODE_PROBS, 0); | |
| 289 | + if y_mode == B_PRED { | |
| 290 | + for by in 0..4 { | |
| 291 | + for bx in 0..4 { | |
| 292 | + let above = if by == 0 { | |
| 293 | + above_bmodes[mb_x * 4 + bx] | |
| 294 | + } else { | |
| 295 | + bmodes[(by - 1) * 4 + bx] | |
| 296 | + }; | |
| 297 | + let left = if bx == 0 { | |
| 298 | + left_bmodes[by] | |
| 299 | + } else { | |
| 300 | + bmodes[by * 4 + bx - 1] | |
| 301 | + }; | |
| 302 | + bmodes[by * 4 + bx] = bd.tree(&BMODE_TREE, &KF_BMODE_PROBS[above][left], 0); | |
| 303 | + } | |
| 304 | + } | |
| 305 | + } else { | |
| 306 | + // A whole-macroblock mode still predicts the *next* | |
| 307 | + // macroblock's subblock modes, through this equivalence. | |
| 308 | + let implied = match y_mode { | |
| 309 | + V_PRED => B_VE_PRED, | |
| 310 | + H_PRED => B_HE_PRED, | |
| 311 | + TM_PRED => B_TM_PRED, | |
| 312 | + _ => B_DC_PRED, | |
| 313 | + }; | |
| 314 | + bmodes = [implied; 16]; | |
| 315 | + } | |
| 316 | + let uv_mode = bd.tree(&UV_MODE_TREE, &KF_UV_MODE_PROBS, 0); | |
| 317 | + above_bmodes[mb_x * 4..mb_x * 4 + 4].copy_from_slice(&bmodes[12..16]); | |
| 318 | + left_bmodes = [bmodes[3], bmodes[7], bmodes[11], bmodes[15]]; | |
| 319 | + | |
| 320 | + // Residual record, from this row's token partition. | |
| 321 | + let tokens = &mut token_decoders[mb_y % partitions.len()]; | |
| 322 | + let has_y2 = y_mode != B_PRED; | |
| 323 | + let mut has_coeffs = false; | |
| 324 | + for block in coeffs.iter_mut() { | |
| 325 | + block.fill(0); | |
| 326 | + } | |
| 327 | + if skip { | |
| 328 | + left_nz[..8].fill(0); | |
| 329 | + above_nz[mb_x][..8].fill(0); | |
| 330 | + if has_y2 { | |
| 331 | + left_nz[8] = 0; | |
| 332 | + above_nz[mb_x][8] = 0; | |
| 333 | + } | |
| 334 | + } else { | |
| 335 | + has_coeffs = decode_residual( | |
| 336 | + tokens, | |
| 337 | + &header, | |
| 338 | + header.dequant[segment], | |
| 339 | + has_y2, | |
| 340 | + &mut coeffs, | |
| 341 | + &mut left_nz, | |
| 342 | + &mut above_nz[mb_x], | |
| 343 | + )?; | |
| 344 | + } | |
| 345 | + | |
| 346 | + reconstruct( | |
| 347 | + &mut frame, | |
| 348 | + mb_x, | |
| 349 | + mb_y, | |
| 350 | + mb_cols, | |
| 351 | + mb_rows, | |
| 352 | + y_mode, | |
| 353 | + uv_mode, | |
| 354 | + &bmodes, | |
| 355 | + &mut coeffs, | |
| 356 | + has_y2, | |
| 357 | + ); | |
| 358 | + infos.push(MbInfo { | |
| 359 | + y_mode, | |
| 360 | + segment, | |
| 361 | + has_coeffs, | |
| 362 | + }); | |
| 363 | + if bd.exhausted() { | |
| 364 | + return Err(Error::corrupt("VP8: first partition ran out of data")); | |
| 365 | + } | |
| 366 | + } | |
| 367 | + } | |
| 368 | + | |
| 369 | + if header.filter_level > 0 { | |
| 370 | + loop_filter(&mut frame, &header, &infos, mb_cols, mb_rows); | |
| 371 | + } | |
| 372 | + Ok(frame) | |
| 373 | +} | |
| 374 | + | |
| 375 | +/// Read the frame header; returns it with the token partition count. | |
| 376 | +fn read_header(bd: &mut BoolDecoder<'_>) -> Result<(Header, usize)> { | |
| 377 | + let mut header = Header { | |
| 378 | + segmentation: false, | |
| 379 | + update_map: false, | |
| 380 | + segment_probs: [255; 3], | |
| 381 | + filter_simple: false, | |
| 382 | + filter_level: 0, | |
| 383 | + sharpness: 0, | |
| 384 | + delta_enabled: false, | |
| 385 | + ref_delta: [0; 4], | |
| 386 | + mode_delta: [0; 4], | |
| 387 | + segment_lf: [0; 4], | |
| 388 | + segment_lf_absolute: false, | |
| 389 | + dequant: [Dequant::default(); 4], | |
| 390 | + coeff_probs: DEFAULT_COEFF_PROBS, | |
| 391 | + skip_enabled: false, | |
| 392 | + skip_prob: 0, | |
| 393 | + }; | |
| 394 | + let mut segment_quant = [0i32; 4]; | |
| 395 | + | |
| 396 | + header.segmentation = bd.literal(1) == 1; | |
| 397 | + if header.segmentation { | |
| 398 | + header.update_map = bd.literal(1) == 1; | |
| 399 | + let update_data = bd.literal(1) == 1; | |
| 400 | + if update_data { | |
| 401 | + header.segment_lf_absolute = bd.literal(1) == 1; | |
| 402 | + for q in &mut segment_quant { | |
| 403 | + *q = bd.maybe_signed(7); | |
| 404 | + } | |
| 405 | + for lf in &mut header.segment_lf { | |
| 406 | + *lf = bd.maybe_signed(6); | |
| 407 | + } | |
| 408 | + } | |
| 409 | + if header.update_map { | |
| 410 | + for p in &mut header.segment_probs { | |
| 411 | + *p = if bd.literal(1) == 1 { | |
| 412 | + bd.literal(8) as u8 | |
| 413 | + } else { | |
| 414 | + 255 | |
| 415 | + }; | |
| 416 | + } | |
| 417 | + } | |
| 418 | + } | |
| 419 | + | |
| 420 | + header.filter_simple = bd.literal(1) == 1; | |
| 421 | + header.filter_level = bd.literal(6) as i32; | |
| 422 | + header.sharpness = bd.literal(3) as i32; | |
| 423 | + header.delta_enabled = bd.literal(1) == 1; | |
| 424 | + if header.delta_enabled && bd.literal(1) == 1 { | |
| 425 | + for d in &mut header.ref_delta { | |
| 426 | + if bd.literal(1) == 1 { | |
| 427 | + *d = bd.signed(6); | |
| 428 | + } | |
| 429 | + } | |
| 430 | + for d in &mut header.mode_delta { | |
| 431 | + if bd.literal(1) == 1 { | |
| 432 | + *d = bd.signed(6); | |
| 433 | + } | |
| 434 | + } | |
| 435 | + } | |
| 436 | + | |
| 437 | + let partition_count = 1usize << bd.literal(2); | |
| 438 | + | |
| 439 | + // Quantizer indices, then the six factors per segment. | |
| 440 | + let base = bd.literal(7) as i32; | |
| 441 | + let y_dc = bd.maybe_signed(4); | |
| 442 | + let y2_dc = bd.maybe_signed(4); | |
| 443 | + let y2_ac = bd.maybe_signed(4); | |
| 444 | + let uv_dc = bd.maybe_signed(4); | |
| 445 | + let uv_ac = bd.maybe_signed(4); | |
| 446 | + for segment in 0..4 { | |
| 447 | + let q = if header.segmentation { | |
| 448 | + if header.segment_lf_absolute { | |
| 449 | + segment_quant[segment] | |
| 450 | + } else { | |
| 451 | + base + segment_quant[segment] | |
| 452 | + } | |
| 453 | + } else { | |
| 454 | + base | |
| 455 | + }; | |
| 456 | + header.dequant[segment] = Dequant { | |
| 457 | + y: [dc_q(q + y_dc), ac_q(q)], | |
| 458 | + y2: [dc_q(q + y2_dc) * 2, (ac_q(q + y2_ac) * 155 / 100).max(8)], | |
| 459 | + uv: [dc_q(q + uv_dc).min(132), ac_q(q + uv_ac)], | |
| 460 | + }; | |
| 461 | + } | |
| 462 | + | |
| 463 | + let _refresh_entropy = bd.literal(1); | |
| 464 | + for i in 0..4 { | |
| 465 | + for j in 0..8 { | |
| 466 | + for k in 0..3 { | |
| 467 | + for t in 0..11 { | |
| 468 | + if bd.bool(COEFF_UPDATE_PROBS[i][j][k][t]) == 1 { | |
| 469 | + header.coeff_probs[i][j][k][t] = bd.literal(8) as u8; | |
| 470 | + } | |
| 471 | + } | |
| 472 | + } | |
| 473 | + } | |
| 474 | + } | |
| 475 | + header.skip_enabled = bd.literal(1) == 1; | |
| 476 | + if header.skip_enabled { | |
| 477 | + header.skip_prob = bd.literal(8) as u8; | |
| 478 | + } | |
| 479 | + Ok((header, partition_count)) | |
| 480 | +} | |
| 481 | + | |
| 482 | +fn clamp_q(q: i32) -> usize { | |
| 483 | + q.clamp(0, 127) as usize | |
| 484 | +} | |
| 485 | + | |
| 486 | +fn dc_q(q: i32) -> i32 { | |
| 487 | + DC_QLOOKUP[clamp_q(q)] | |
| 488 | +} | |
| 489 | + | |
| 490 | +fn ac_q(q: i32) -> i32 { | |
| 491 | + AC_QLOOKUP[clamp_q(q)] | |
| 492 | +} | |
| 493 | + | |
| 494 | +/// Split the token partitions, whose sizes precede them three bytes each. | |
| 495 | +fn split_partitions(data: &[u8], count: usize) -> Result<Vec<&[u8]>> { | |
| 496 | + let table = (count - 1) * 3; | |
| 497 | + let body = data | |
| 498 | + .get(table..) | |
| 499 | + .ok_or_else(|| Error::corrupt("VP8: partition size table runs past the chunk"))?; | |
| 500 | + let mut parts = Vec::with_capacity(count); | |
| 501 | + let mut at = 0usize; | |
| 502 | + for i in 0..count - 1 { | |
| 503 | + let size = usize::from(data[i * 3]) | |
| 504 | + | (usize::from(data[i * 3 + 1]) << 8) | |
| 505 | + | (usize::from(data[i * 3 + 2]) << 16); | |
| 506 | + let part = body | |
| 507 | + .get(at..at + size) | |
| 508 | + .ok_or_else(|| Error::corrupt("VP8: token partition runs past the chunk"))?; | |
| 509 | + parts.push(part); | |
| 510 | + at += size; | |
| 511 | + } | |
| 512 | + parts.push(&body[at..]); | |
| 513 | + Ok(parts) | |
| 514 | +} | |
| 515 | + | |
| 516 | +/// Decode one macroblock's 25 blocks of coefficients, dequantizing as it goes. | |
| 517 | +#[allow(clippy::too_many_arguments)] | |
| 518 | +fn decode_residual( | |
| 519 | + bd: &mut BoolDecoder<'_>, | |
| 520 | + header: &Header, | |
| 521 | + dequant: Dequant, | |
| 522 | + has_y2: bool, | |
| 523 | + coeffs: &mut [[i16; 16]; 25], | |
| 524 | + left_nz: &mut [u8; 9], | |
| 525 | + above_nz: &mut [u8; 9], | |
| 526 | +) -> Result<bool> { | |
| 527 | + let mut any = false; | |
| 528 | + if has_y2 { | |
| 529 | + let ctx = usize::from(left_nz[8]) + usize::from(above_nz[8]); | |
| 530 | + let nonzero = decode_block(bd, header, 1, ctx, 0, dequant.y2, &mut coeffs[24])?; | |
| 531 | + left_nz[8] = u8::from(nonzero); | |
| 532 | + above_nz[8] = u8::from(nonzero); | |
| 533 | + any |= nonzero; | |
| 534 | + } | |
| 535 | + let (plane, first) = if has_y2 { | |
| 536 | + (0usize, 1usize) | |
| 537 | + } else { | |
| 538 | + (3usize, 0usize) | |
| 539 | + }; | |
| 540 | + for by in 0..4 { | |
| 541 | + for bx in 0..4 { | |
| 542 | + let ctx = usize::from(left_nz[by]) + usize::from(above_nz[bx]); | |
| 543 | + let nonzero = decode_block( | |
| 544 | + bd, | |
| 545 | + header, | |
| 546 | + plane, | |
| 547 | + ctx, | |
| 548 | + first, | |
| 549 | + dequant.y, | |
| 550 | + &mut coeffs[by * 4 + bx], | |
| 551 | + )?; | |
| 552 | + left_nz[by] = u8::from(nonzero); | |
| 553 | + above_nz[bx] = u8::from(nonzero); | |
| 554 | + any |= nonzero; | |
| 555 | + } | |
| 556 | + } | |
| 557 | + for (chroma, base) in [(0usize, 16usize), (1, 20)] { | |
| 558 | + for by in 0..2 { | |
| 559 | + for bx in 0..2 { | |
| 560 | + let li = 4 + chroma * 2 + by; | |
| 561 | + let ai = 4 + chroma * 2 + bx; | |
| 562 | + let ctx = usize::from(left_nz[li]) + usize::from(above_nz[ai]); | |
| 563 | + let nonzero = decode_block( | |
| 564 | + bd, | |
| 565 | + header, | |
| 566 | + 2, | |
| 567 | + ctx, | |
| 568 | + 0, | |
| 569 | + dequant.uv, | |
| 570 | + &mut coeffs[base + by * 2 + bx], | |
| 571 | + )?; | |
| 572 | + left_nz[li] = u8::from(nonzero); | |
| 573 | + above_nz[ai] = u8::from(nonzero); | |
| 574 | + any |= nonzero; | |
| 575 | + } | |
| 576 | + } | |
| 577 | + } | |
| 578 | + if bd.exhausted() { | |
| 579 | + return Err(Error::corrupt("VP8: token partition ran out of data")); | |
| 580 | + } | |
| 581 | + Ok(any) | |
| 582 | +} | |
| 583 | + | |
| 584 | +/// One 4x4 block of tokens, written out dequantized in raster order. | |
| 585 | +fn decode_block( | |
| 586 | + bd: &mut BoolDecoder<'_>, | |
| 587 | + header: &Header, | |
| 588 | + plane: usize, | |
| 589 | + ctx: usize, | |
| 590 | + first: usize, | |
| 591 | + factors: [i32; 2], | |
| 592 | + out: &mut [i16; 16], | |
| 593 | +) -> Result<bool> { | |
| 594 | + let mut ctx = ctx; | |
| 595 | + let mut nonzero = false; | |
| 596 | + let mut index = first; | |
| 597 | + let mut skip_eob = false; | |
| 598 | + while index < 16 { | |
| 599 | + let probs = &header.coeff_probs[plane][COEFF_BANDS[index]][ctx]; | |
| 600 | + let token = bd.tree(&COEFF_TREE, probs, if skip_eob { 2 } else { 0 }); | |
| 601 | + if token == 11 { | |
| 602 | + break; | |
| 603 | + } | |
| 604 | + let value = match token { | |
| 605 | + 0 => 0, | |
| 606 | + 1..=4 => token as i32, | |
| 607 | + _ => { | |
| 608 | + let cat = token - 5; | |
| 609 | + let mut extra = 0i32; | |
| 610 | + for &p in PCAT[cat] { | |
| 611 | + extra = 2 * extra + bd.bool(p) as i32; | |
| 612 | + } | |
| 613 | + CAT_BASE[cat] + extra | |
| 614 | + } | |
| 615 | + }; | |
| 616 | + ctx = match value { | |
| 617 | + 0 => 0, | |
| 618 | + 1 => 1, | |
| 619 | + _ => 2, | |
| 620 | + }; | |
| 621 | + skip_eob = value == 0; | |
| 622 | + if value != 0 { | |
| 623 | + nonzero = true; | |
| 624 | + let signed = if bd.bool(128) == 1 { -value } else { value }; | |
| 625 | + let factor = if index == 0 { factors[0] } else { factors[1] }; | |
| 626 | + out[ZIGZAG[index]] = (signed * factor).clamp(-32768, 32767) as i16; | |
| 627 | + } | |
| 628 | + index += 1; | |
| 629 | + } | |
| 630 | + Ok(nonzero) | |
| 631 | +} | |
| 632 | + | |
| 633 | +/// Inverse Walsh-Hadamard: the Y2 block's values become the Y blocks' DCs. | |
| 634 | +fn inverse_wht(input: &[i16; 16], coeffs: &mut [[i16; 16]; 25]) { | |
| 635 | + let mut tmp = [0i32; 16]; | |
| 636 | + for i in 0..4 { | |
| 637 | + let a1 = i32::from(input[i]) + i32::from(input[12 + i]); | |
| 638 | + let b1 = i32::from(input[4 + i]) + i32::from(input[8 + i]); | |
| 639 | + let c1 = i32::from(input[4 + i]) - i32::from(input[8 + i]); | |
| 640 | + let d1 = i32::from(input[i]) - i32::from(input[12 + i]); | |
| 641 | + tmp[i] = a1 + b1; | |
| 642 | + tmp[4 + i] = c1 + d1; | |
| 643 | + tmp[8 + i] = a1 - b1; | |
| 644 | + tmp[12 + i] = d1 - c1; | |
| 645 | + } | |
| 646 | + for i in 0..4 { | |
| 647 | + let a1 = tmp[i * 4] + tmp[i * 4 + 3]; | |
| 648 | + let b1 = tmp[i * 4 + 1] + tmp[i * 4 + 2]; | |
| 649 | + let c1 = tmp[i * 4 + 1] - tmp[i * 4 + 2]; | |
| 650 | + let d1 = tmp[i * 4] - tmp[i * 4 + 3]; | |
| 651 | + coeffs[i * 4][0] = ((a1 + b1 + 3) >> 3) as i16; | |
| 652 | + coeffs[i * 4 + 1][0] = ((c1 + d1 + 3) >> 3) as i16; | |
| 653 | + coeffs[i * 4 + 2][0] = ((a1 - b1 + 3) >> 3) as i16; | |
| 654 | + coeffs[i * 4 + 3][0] = ((d1 - c1 + 3) >> 3) as i16; | |
| 655 | + } | |
| 656 | +} | |
| 657 | + | |
| 658 | +const COS_PI8_SQRT2_MINUS1: i32 = 20091; | |
| 659 | +const SIN_PI8_SQRT2: i32 = 35468; | |
| 660 | + | |
| 661 | +/// The 4x4 inverse DCT of RFC 6386 section 14.4, bit-exact as specified. | |
| 662 | +fn inverse_dct(block: &[i16; 16]) -> [i32; 16] { | |
| 663 | + let mut tmp = [0i32; 16]; | |
| 664 | + for i in 0..4 { | |
| 665 | + let ip = |k: usize| i32::from(block[k * 4 + i]); | |
| 666 | + let a1 = ip(0) + ip(2); | |
| 667 | + let b1 = ip(0) - ip(2); | |
| 668 | + let t1 = (ip(1) * SIN_PI8_SQRT2) >> 16; | |
| 669 | + let t2 = ip(3) + ((ip(3) * COS_PI8_SQRT2_MINUS1) >> 16); | |
| 670 | + let c1 = t1 - t2; | |
| 671 | + let t1 = ip(1) + ((ip(1) * COS_PI8_SQRT2_MINUS1) >> 16); | |
| 672 | + let t2 = (ip(3) * SIN_PI8_SQRT2) >> 16; | |
| 673 | + let d1 = t1 + t2; | |
| 674 | + tmp[i] = a1 + d1; | |
| 675 | + tmp[12 + i] = a1 - d1; | |
| 676 | + tmp[4 + i] = b1 + c1; | |
| 677 | + tmp[8 + i] = b1 - c1; | |
| 678 | + } | |
| 679 | + let mut out = [0i32; 16]; | |
| 680 | + for i in 0..4 { | |
| 681 | + let ip = |k: usize| tmp[i * 4 + k]; | |
| 682 | + let a1 = ip(0) + ip(2); | |
| 683 | + let b1 = ip(0) - ip(2); | |
| 684 | + let t1 = (ip(1) * SIN_PI8_SQRT2) >> 16; | |
| 685 | + let t2 = ip(3) + ((ip(3) * COS_PI8_SQRT2_MINUS1) >> 16); | |
| 686 | + let c1 = t1 - t2; | |
| 687 | + let t1 = ip(1) + ((ip(1) * COS_PI8_SQRT2_MINUS1) >> 16); | |
| 688 | + let t2 = (ip(3) * SIN_PI8_SQRT2) >> 16; | |
| 689 | + let d1 = t1 + t2; | |
| 690 | + out[i * 4] = (a1 + d1 + 4) >> 3; | |
| 691 | + out[i * 4 + 3] = (a1 - d1 + 4) >> 3; | |
| 692 | + out[i * 4 + 1] = (b1 + c1 + 4) >> 3; | |
| 693 | + out[i * 4 + 2] = (b1 - c1 + 4) >> 3; | |
| 694 | + } | |
| 695 | + out | |
| 696 | +} | |
| 697 | + | |
| 698 | +/// The macroblock's working buffer: one row of "above" pixels (with the four | |
| 699 | +/// above-right ones a subblock may reach for) and one column of "left" ones, | |
| 700 | +/// surrounding the 16x16 luma and 8x8 chroma blocks being built. | |
| 701 | +struct Work { | |
| 702 | + y: [[u8; 21]; 17], | |
| 703 | + u: [[u8; 9]; 9], | |
| 704 | + v: [[u8; 9]; 9], | |
| 705 | +} | |
| 706 | + | |
| 707 | +#[allow(clippy::too_many_arguments)] | |
| 708 | +fn reconstruct( | |
| 709 | + frame: &mut Frame, | |
| 710 | + mb_x: usize, | |
| 711 | + mb_y: usize, | |
| 712 | + mb_cols: usize, | |
| 713 | + _mb_rows: usize, | |
| 714 | + y_mode: usize, | |
| 715 | + uv_mode: usize, | |
| 716 | + bmodes: &[usize; 16], | |
| 717 | + coeffs: &mut [[i16; 16]; 25], | |
| 718 | + has_y2: bool, | |
| 719 | +) { | |
| 720 | + if has_y2 { | |
| 721 | + let y2 = coeffs[24]; | |
| 722 | + inverse_wht(&y2, coeffs); | |
| 723 | + } | |
| 724 | + let mut work = Work { | |
| 725 | + y: [[0; 21]; 17], | |
| 726 | + u: [[0; 9]; 9], | |
| 727 | + v: [[0; 9]; 9], | |
| 728 | + }; | |
| 729 | + load_edges(frame, &mut work, mb_x, mb_y, mb_cols); | |
| 730 | + | |
| 731 | + if y_mode == B_PRED { | |
| 732 | + for by in 0..4 { | |
| 733 | + for bx in 0..4 { | |
| 734 | + predict_subblock(&mut work, bx, by, bmodes[by * 4 + bx]); | |
| 735 | + add_residual_4x4(&mut work.y, by * 4 + 1, bx * 4 + 1, &coeffs[by * 4 + bx]); | |
| 736 | + } | |
| 737 | + } | |
| 738 | + } else { | |
| 739 | + predict_luma_16x16(&mut work, y_mode, mb_x, mb_y); | |
| 740 | + for by in 0..4 { | |
| 741 | + for bx in 0..4 { | |
| 742 | + add_residual_4x4(&mut work.y, by * 4 + 1, bx * 4 + 1, &coeffs[by * 4 + bx]); | |
| 743 | + } | |
| 744 | + } | |
| 745 | + } | |
| 746 | + predict_chroma(&mut work, uv_mode, mb_x, mb_y); | |
| 747 | + for by in 0..2 { | |
| 748 | + for bx in 0..2 { | |
| 749 | + add_residual_4x4_c( | |
| 750 | + &mut work.u, | |
| 751 | + by * 4 + 1, | |
| 752 | + bx * 4 + 1, | |
| 753 | + &coeffs[16 + by * 2 + bx], | |
| 754 | + ); | |
| 755 | + add_residual_4x4_c( | |
| 756 | + &mut work.v, | |
| 757 | + by * 4 + 1, | |
| 758 | + bx * 4 + 1, | |
| 759 | + &coeffs[20 + by * 2 + bx], | |
| 760 | + ); | |
| 761 | + } | |
| 762 | + } | |
| 763 | + store_macroblock(frame, &work, mb_x, mb_y); | |
| 764 | +} | |
| 765 | + | |
| 766 | +/// Fill the working buffer's borders from the already-reconstructed frame, | |
| 767 | +/// using 127 above the picture and 129 to its left as the format requires. | |
| 768 | +fn load_edges(frame: &Frame, work: &mut Work, mb_x: usize, mb_y: usize, mb_cols: usize) { | |
| 769 | + let sy = frame.stride_y; | |
| 770 | + let suv = frame.stride_uv; | |
| 771 | + // Luma above row plus four above-right pixels. | |
| 772 | + if mb_y == 0 { | |
| 773 | + work.y[0] = [127; 21]; | |
| 774 | + } else { | |
| 775 | + let row = (mb_y * 16 - 1) * sy; | |
| 776 | + work.y[0][0] = if mb_x == 0 { | |
| 777 | + 129 | |
| 778 | + } else { | |
| 779 | + frame.y[row + mb_x * 16 - 1] | |
| 780 | + }; | |
| 781 | + for i in 0..16 { | |
| 782 | + work.y[0][1 + i] = frame.y[row + mb_x * 16 + i]; | |
| 783 | + } | |
| 784 | + for i in 0..4 { | |
| 785 | + work.y[0][17 + i] = if mb_x + 1 < mb_cols { | |
| 786 | + frame.y[row + mb_x * 16 + 16 + i] | |
| 787 | + } else { | |
| 788 | + // The rightmost macroblock reuses the last visible pixel of | |
| 789 | + // the row above, per section 12.3. | |
| 790 | + frame.y[row + mb_x * 16 + 15] | |
| 791 | + }; | |
| 792 | + } | |
| 793 | + } | |
| 794 | + for r in 0..16 { | |
| 795 | + work.y[r + 1][0] = if mb_x == 0 { | |
| 796 | + 129 | |
| 797 | + } else { | |
| 798 | + frame.y[(mb_y * 16 + r) * sy + mb_x * 16 - 1] | |
| 799 | + }; | |
| 800 | + } | |
| 801 | + // Chroma above rows and left columns. | |
| 802 | + for (plane, buf) in [(&frame.u, &mut work.u), (&frame.v, &mut work.v)] { | |
| 803 | + if mb_y == 0 { | |
| 804 | + buf[0] = [127; 9]; | |
| 805 | + } else { | |
| 806 | + let row = (mb_y * 8 - 1) * suv; | |
| 807 | + buf[0][0] = if mb_x == 0 { | |
| 808 | + 129 | |
| 809 | + } else { | |
| 810 | + plane[row + mb_x * 8 - 1] | |
| 811 | + }; | |
| 812 | + for i in 0..8 { | |
| 813 | + buf[0][1 + i] = plane[row + mb_x * 8 + i]; | |
| 814 | + } | |
| 815 | + } | |
| 816 | + for r in 0..8 { | |
| 817 | + buf[r + 1][0] = if mb_x == 0 { | |
| 818 | + 129 | |
| 819 | + } else { | |
| 820 | + plane[(mb_y * 8 + r) * suv + mb_x * 8 - 1] | |
| 821 | + }; | |
| 822 | + } | |
| 823 | + } | |
| 824 | +} | |
| 825 | + | |
| 826 | +fn store_macroblock(frame: &mut Frame, work: &Work, mb_x: usize, mb_y: usize) { | |
| 827 | + let sy = frame.stride_y; | |
| 828 | + let suv = frame.stride_uv; | |
| 829 | + for r in 0..16 { | |
| 830 | + let dst = (mb_y * 16 + r) * sy + mb_x * 16; | |
| 831 | + frame.y[dst..dst + 16].copy_from_slice(&work.y[r + 1][1..17]); | |
| 832 | + } | |
| 833 | + for r in 0..8 { | |
| 834 | + let dst = (mb_y * 8 + r) * suv + mb_x * 8; | |
| 835 | + frame.u[dst..dst + 8].copy_from_slice(&work.u[r + 1][1..9]); | |
| 836 | + frame.v[dst..dst + 8].copy_from_slice(&work.v[r + 1][1..9]); | |
| 837 | + } | |
| 838 | +} | |
| 839 | + | |
| 840 | +fn add_residual_4x4(buf: &mut [[u8; 21]; 17], row: usize, col: usize, block: &[i16; 16]) { | |
| 841 | + if block.iter().all(|&c| c == 0) { | |
| 842 | + return; | |
| 843 | + } | |
| 844 | + let residue = inverse_dct(block); | |
| 845 | + for r in 0..4 { | |
| 846 | + for c in 0..4 { | |
| 847 | + let v = i32::from(buf[row + r][col + c]) + residue[r * 4 + c]; | |
| 848 | + buf[row + r][col + c] = v.clamp(0, 255) as u8; | |
| 849 | + } | |
| 850 | + } | |
| 851 | +} | |
| 852 | + | |
| 853 | +fn add_residual_4x4_c(buf: &mut [[u8; 9]; 9], row: usize, col: usize, block: &[i16; 16]) { | |
| 854 | + if block.iter().all(|&c| c == 0) { | |
| 855 | + return; | |
| 856 | + } | |
| 857 | + let residue = inverse_dct(block); | |
| 858 | + for r in 0..4 { | |
| 859 | + for c in 0..4 { | |
| 860 | + let v = i32::from(buf[row + r][col + c]) + residue[r * 4 + c]; | |
| 861 | + buf[row + r][col + c] = v.clamp(0, 255) as u8; | |
| 862 | + } | |
| 863 | + } | |
| 864 | +} | |
| 865 | + | |
| 866 | +/// DC prediction's rounded average, over whichever edges exist. | |
| 867 | +fn dc_value(above: &[u8], left: &[u8], have_above: bool, have_left: bool) -> u8 { | |
| 868 | + let mut sum = 0u32; | |
| 869 | + let mut count = 0u32; | |
| 870 | + if have_above { | |
| 871 | + sum += above.iter().map(|&p| u32::from(p)).sum::<u32>(); | |
| 872 | + count += above.len() as u32; | |
| 873 | + } | |
| 874 | + if have_left { | |
| 875 | + sum += left.iter().map(|&p| u32::from(p)).sum::<u32>(); | |
| 876 | + count += left.len() as u32; | |
| 877 | + } | |
| 878 | + if count == 0 { | |
| 879 | + return 128; | |
| 880 | + } | |
| 881 | + let shift = count.trailing_zeros(); | |
| 882 | + ((sum + (1 << (shift - 1))) >> shift) as u8 | |
| 883 | +} | |
| 884 | + | |
| 885 | +fn predict_luma_16x16(work: &mut Work, mode: usize, mb_x: usize, mb_y: usize) { | |
| 886 | + let above: Vec<u8> = work.y[0][1..17].to_vec(); | |
| 887 | + let left: Vec<u8> = (0..16).map(|r| work.y[r + 1][0]).collect(); | |
| 888 | + let corner = work.y[0][0]; | |
| 889 | + let dc = dc_value(&above, &left, mb_y > 0, mb_x > 0); | |
| 890 | + for r in 0..16 { | |
| 891 | + for c in 0..16 { | |
| 892 | + work.y[r + 1][c + 1] = match mode { | |
| 893 | + V_PRED => above[c], | |
| 894 | + H_PRED => left[r], | |
| 895 | + TM_PRED => (i32::from(left[r]) + i32::from(above[c]) - i32::from(corner)) | |
| 896 | + .clamp(0, 255) as u8, | |
| 897 | + DC_PRED => dc, | |
| 898 | + _ => dc, | |
| 899 | + }; | |
| 900 | + } | |
| 901 | + } | |
| 902 | +} | |
| 903 | + | |
| 904 | +fn predict_chroma(work: &mut Work, mode: usize, mb_x: usize, mb_y: usize) { | |
| 905 | + for buf in [&mut work.u, &mut work.v] { | |
| 906 | + let above: Vec<u8> = buf[0][1..9].to_vec(); | |
| 907 | + let left: Vec<u8> = (0..8).map(|r| buf[r + 1][0]).collect(); | |
| 908 | + let corner = buf[0][0]; | |
| 909 | + let dc = dc_value(&above, &left, mb_y > 0, mb_x > 0); | |
| 910 | + for r in 0..8 { | |
| 911 | + for c in 0..8 { | |
| 912 | + buf[r + 1][c + 1] = match mode { | |
| 913 | + V_PRED => above[c], | |
| 914 | + H_PRED => left[r], | |
| 915 | + TM_PRED => (i32::from(left[r]) + i32::from(above[c]) - i32::from(corner)) | |
| 916 | + .clamp(0, 255) as u8, | |
| 917 | + DC_PRED => dc, | |
| 918 | + _ => dc, | |
| 919 | + }; | |
| 920 | + } | |
| 921 | + } | |
| 922 | + } | |
| 923 | +} | |
| 924 | + | |
| 925 | +fn avg3(x: u8, y: u8, z: u8) -> u8 { | |
| 926 | + ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8 | |
| 927 | +} | |
| 928 | + | |
| 929 | +fn avg2(x: u8, y: u8) -> u8 { | |
| 930 | + ((u32::from(x) + u32::from(y) + 1) >> 1) as u8 | |
| 931 | +} | |
| 932 | + | |
| 933 | +/// The ten 4x4 subblock predictions of section 12.3. | |
| 934 | +fn predict_subblock(work: &mut Work, bx: usize, by: usize, mode: usize) { | |
| 935 | + let row = by * 4; | |
| 936 | + let col = bx * 4; | |
| 937 | + // A[-1] is P; A[0..8] the above row and its four right-hand neighbours. | |
| 938 | + let mut a = [0u8; 9]; | |
| 939 | + a[0] = work.y[row][col]; | |
| 940 | + for i in 0..8 { | |
| 941 | + // Subblocks on the macroblock's right edge take their above-right from | |
| 942 | + // row -1 whatever their own row is: the pixels to their upper right | |
| 943 | + // have not been reconstructed yet. | |
| 944 | + a[1 + i] = if bx == 3 && i >= 4 { | |
| 945 | + work.y[0][17 + (i - 4)] | |
| 946 | + } else { | |
| 947 | + work.y[row][col + 1 + i] | |
| 948 | + }; | |
| 949 | + } | |
| 950 | + let l = [ | |
| 951 | + work.y[row + 1][col], | |
| 952 | + work.y[row + 2][col], | |
| 953 | + work.y[row + 3][col], | |
| 954 | + work.y[row + 4][col], | |
| 955 | + ]; | |
| 956 | + let p = a[0]; | |
| 957 | + let above = &a[1..9]; | |
| 958 | + // E[0..9]: the left column reversed, then P, then the above row. | |
| 959 | + let e = [ | |
| 960 | + l[3], l[2], l[1], l[0], p, above[0], above[1], above[2], above[3], | |
| 961 | + ]; | |
| 962 | + let mut b = [[0u8; 4]; 4]; | |
| 963 | + match mode { | |
| 964 | + B_DC_PRED => { | |
| 965 | + let mut v = 4u32; | |
| 966 | + for i in 0..4 { | |
| 967 | + v += u32::from(above[i]) + u32::from(l[i]); | |
| 968 | + } | |
| 969 | + let v = (v >> 3) as u8; | |
| 970 | + b = [[v; 4]; 4]; | |
| 971 | + } | |
| 972 | + B_TM_PRED => { | |
| 973 | + for r in 0..4 { | |
| 974 | + for c in 0..4 { | |
| 975 | + b[r][c] = | |
| 976 | + (i32::from(l[r]) + i32::from(above[c]) - i32::from(p)).clamp(0, 255) as u8; | |
| 977 | + } | |
| 978 | + } | |
| 979 | + } | |
| 980 | + B_VE_PRED => { | |
| 981 | + for c in 0..4 { | |
| 982 | + let v = avg3( | |
| 983 | + if c == 0 { p } else { above[c - 1] }, | |
| 984 | + above[c], | |
| 985 | + above[c + 1], | |
| 986 | + ); | |
| 987 | + for r in 0..4 { | |
| 988 | + b[r][c] = v; | |
| 989 | + } | |
| 990 | + } | |
| 991 | + } | |
| 992 | + B_HE_PRED => { | |
| 993 | + let values = [ | |
| 994 | + avg3(p, l[0], l[1]), | |
| 995 | + avg3(l[0], l[1], l[2]), | |
| 996 | + avg3(l[1], l[2], l[3]), | |
| 997 | + avg3(l[2], l[3], l[3]), | |
| 998 | + ]; | |
| 999 | + for r in 0..4 { | |
| 1000 | + b[r] = [values[r]; 4]; | |
| 1001 | + } | |
| 1002 | + } | |
| 1003 | + 4 => { | |
| 1004 | + // B_LD_PRED: 45 degrees down-left. | |
| 1005 | + let d = |i: usize| avg3(above[i - 1], above[i], above[i + 1]); | |
| 1006 | + b[0][0] = d(1); | |
| 1007 | + b[0][1] = d(2); | |
| 1008 | + b[1][0] = d(2); | |
| 1009 | + b[0][2] = d(3); | |
| 1010 | + b[1][1] = d(3); | |
| 1011 | + b[2][0] = d(3); | |
| 1012 | + b[0][3] = d(4); | |
| 1013 | + b[1][2] = d(4); | |
| 1014 | + b[2][1] = d(4); | |
| 1015 | + b[3][0] = d(4); | |
| 1016 | + b[1][3] = d(5); | |
| 1017 | + b[2][2] = d(5); | |
| 1018 | + b[3][1] = d(5); | |
| 1019 | + b[2][3] = d(6); | |
| 1020 | + b[3][2] = d(6); | |
| 1021 | + b[3][3] = avg3(above[6], above[7], above[7]); | |
| 1022 | + } | |
| 1023 | + 5 => { | |
| 1024 | + // B_RD_PRED: 45 degrees down-right. | |
| 1025 | + let d = |i: usize| avg3(e[i - 1], e[i], e[i + 1]); | |
| 1026 | + b[3][0] = d(1); | |
| 1027 | + b[3][1] = d(2); | |
| 1028 | + b[2][0] = d(2); | |
| 1029 | + b[3][2] = d(3); | |
| 1030 | + b[2][1] = d(3); | |
| 1031 | + b[1][0] = d(3); | |
| 1032 | + b[3][3] = d(4); | |
| 1033 | + b[2][2] = d(4); | |
| 1034 | + b[1][1] = d(4); | |
| 1035 | + b[0][0] = d(4); | |
| 1036 | + b[2][3] = d(5); | |
| 1037 | + b[1][2] = d(5); | |
| 1038 | + b[0][1] = d(5); | |
| 1039 | + b[1][3] = d(6); | |
| 1040 | + b[0][2] = d(6); | |
| 1041 | + b[0][3] = d(7); | |
| 1042 | + } | |
| 1043 | + 6 => { | |
| 1044 | + // B_VR_PRED. | |
| 1045 | + let d3 = |i: usize| avg3(e[i - 1], e[i], e[i + 1]); | |
| 1046 | + let d2 = |i: usize| avg2(e[i], e[i + 1]); | |
| 1047 | + b[3][0] = d3(2); | |
| 1048 | + b[2][0] = d3(3); | |
| 1049 | + b[3][1] = d3(4); | |
| 1050 | + b[1][0] = d3(4); | |
| 1051 | + b[2][1] = d2(4); | |
| 1052 | + b[0][0] = d2(4); | |
| 1053 | + b[3][2] = d3(5); | |
| 1054 | + b[1][1] = d3(5); | |
| 1055 | + b[2][2] = d2(5); | |
| 1056 | + b[0][1] = d2(5); | |
| 1057 | + b[3][3] = d3(6); | |
| 1058 | + b[1][2] = d3(6); | |
| 1059 | + b[2][3] = d2(6); | |
| 1060 | + b[0][2] = d2(6); | |
| 1061 | + b[1][3] = d3(7); | |
| 1062 | + b[0][3] = d2(7); | |
| 1063 | + } | |
| 1064 | + 7 => { | |
| 1065 | + // B_VL_PRED. | |
| 1066 | + let d3 = |i: usize| avg3(above[i - 1], above[i], above[i + 1]); | |
| 1067 | + let d2 = |i: usize| avg2(above[i], above[i + 1]); | |
| 1068 | + b[0][0] = d2(0); | |
| 1069 | + b[1][0] = d3(1); | |
| 1070 | + b[2][0] = d2(1); | |
| 1071 | + b[0][1] = d2(1); | |
| 1072 | + b[1][1] = d3(2); | |
| 1073 | + b[3][0] = d3(2); | |
| 1074 | + b[2][1] = d2(2); | |
| 1075 | + b[0][2] = d2(2); | |
| 1076 | + b[3][1] = d3(3); | |
| 1077 | + b[1][2] = d3(3); | |
| 1078 | + b[2][2] = d2(3); | |
| 1079 | + b[0][3] = d2(3); | |
| 1080 | + b[3][2] = d3(4); | |
| 1081 | + b[1][3] = d3(4); | |
| 1082 | + b[2][3] = d3(5); | |
| 1083 | + b[3][3] = d3(6); | |
| 1084 | + } | |
| 1085 | + 8 => { | |
| 1086 | + // B_HD_PRED. | |
| 1087 | + let d3 = |i: usize| avg3(e[i - 1], e[i], e[i + 1]); | |
| 1088 | + let d2 = |i: usize| avg2(e[i], e[i + 1]); | |
| 1089 | + b[3][0] = d2(0); | |
| 1090 | + b[3][1] = d3(1); | |
| 1091 | + b[2][0] = d2(1); | |
| 1092 | + b[3][2] = d2(1); | |
| 1093 | + b[2][1] = d3(2); | |
| 1094 | + b[3][3] = d3(2); | |
| 1095 | + b[2][2] = d2(2); | |
| 1096 | + b[1][0] = d2(2); | |
| 1097 | + b[2][3] = d3(3); | |
| 1098 | + b[1][1] = d3(3); | |
| 1099 | + b[1][2] = d2(3); | |
| 1100 | + b[0][0] = d2(3); | |
| 1101 | + b[1][3] = d3(4); | |
| 1102 | + b[0][1] = d3(4); | |
| 1103 | + b[0][2] = d3(5); | |
| 1104 | + b[0][3] = d3(6); | |
| 1105 | + } | |
| 1106 | + _ => { | |
| 1107 | + // B_HU_PRED. | |
| 1108 | + b[0][0] = avg2(l[0], l[1]); | |
| 1109 | + b[0][1] = avg3(l[0], l[1], l[2]); | |
| 1110 | + b[0][2] = avg2(l[1], l[2]); | |
| 1111 | + b[1][0] = avg2(l[1], l[2]); | |
| 1112 | + b[0][3] = avg3(l[1], l[2], l[3]); | |
| 1113 | + b[1][1] = avg3(l[1], l[2], l[3]); | |
| 1114 | + b[1][2] = avg2(l[2], l[3]); | |
| 1115 | + b[2][0] = avg2(l[2], l[3]); | |
| 1116 | + b[1][3] = avg3(l[2], l[3], l[3]); | |
| 1117 | + b[2][1] = avg3(l[2], l[3], l[3]); | |
| 1118 | + b[2][2] = l[3]; | |
| 1119 | + b[2][3] = l[3]; | |
| 1120 | + b[3][0] = l[3]; | |
| 1121 | + b[3][1] = l[3]; | |
| 1122 | + b[3][2] = l[3]; | |
| 1123 | + b[3][3] = l[3]; | |
| 1124 | + } | |
| 1125 | + } | |
| 1126 | + for r in 0..4 { | |
| 1127 | + for c in 0..4 { | |
| 1128 | + work.y[row + 1 + r][col + 1 + c] = b[r][c]; | |
| 1129 | + } | |
| 1130 | + } | |
| 1131 | +} | |
| 1132 | + | |
| 1133 | +// ---- Loop filter (section 15) -------------------------------------------- | |
| 1134 | + | |
| 1135 | +fn c8(v: i32) -> i32 { | |
| 1136 | + v.clamp(-128, 127) | |
| 1137 | +} | |
| 1138 | + | |
| 1139 | +fn u2s(v: u8) -> i32 { | |
| 1140 | + i32::from(v) - 128 | |
| 1141 | +} | |
| 1142 | + | |
| 1143 | +fn s2u(v: i32) -> u8 { | |
| 1144 | + (c8(v) + 128) as u8 | |
| 1145 | +} | |
| 1146 | + | |
| 1147 | +/// The shared 2-or-4-tap adjustment; returns the value the wider filters need. | |
| 1148 | +fn common_adjust(use_outer: bool, plane: &mut [u8], q0: usize, step: usize) -> i32 { | |
| 1149 | + let p1 = u2s(plane[q0 - 2 * step]); | |
| 1150 | + let p0 = u2s(plane[q0 - step]); | |
| 1151 | + let q0v = u2s(plane[q0]); | |
| 1152 | + let q1 = u2s(plane[q0 + step]); | |
| 1153 | + let a = c8((if use_outer { c8(p1 - q1) } else { 0 }) + 3 * (q0v - p0)); | |
| 1154 | + let b = c8(a + 3) >> 3; | |
| 1155 | + let a = c8(a + 4) >> 3; | |
| 1156 | + plane[q0] = s2u(q0v - a); | |
| 1157 | + plane[q0 - step] = s2u(p0 + b); | |
| 1158 | + a | |
| 1159 | +} | |
| 1160 | + | |
| 1161 | +fn simple_segment(edge_limit: i32, plane: &mut [u8], q0: usize, step: usize) { | |
| 1162 | + let p1 = i32::from(plane[q0 - 2 * step]); | |
| 1163 | + let p0 = i32::from(plane[q0 - step]); | |
| 1164 | + let q0v = i32::from(plane[q0]); | |
| 1165 | + let q1 = i32::from(plane[q0 + step]); | |
| 1166 | + if (p0 - q0v).abs() * 2 + (p1 - q1).abs() / 2 <= edge_limit { | |
| 1167 | + common_adjust(true, plane, q0, step); | |
| 1168 | + } | |
| 1169 | +} | |
| 1170 | + | |
| 1171 | +fn filter_yes(interior: i32, edge: i32, plane: &[u8], q0: usize, step: usize) -> bool { | |
| 1172 | + let at = |k: i32| i32::from(plane[(q0 as i32 + k * step as i32) as usize]); | |
| 1173 | + let (p3, p2, p1, p0) = (at(-4), at(-3), at(-2), at(-1)); | |
| 1174 | + let (q0v, q1, q2, q3) = (at(0), at(1), at(2), at(3)); | |
| 1175 | + (p0 - q0v).abs() * 2 + (p1 - q1).abs() / 2 <= edge | |
| 1176 | + && (p3 - p2).abs() <= interior | |
| 1177 | + && (p2 - p1).abs() <= interior | |
| 1178 | + && (p1 - p0).abs() <= interior | |
| 1179 | + && (q3 - q2).abs() <= interior | |
| 1180 | + && (q2 - q1).abs() <= interior | |
| 1181 | + && (q1 - q0v).abs() <= interior | |
| 1182 | +} | |
| 1183 | + | |
| 1184 | +fn hev(threshold: i32, plane: &[u8], q0: usize, step: usize) -> bool { | |
| 1185 | + let at = |k: i32| i32::from(plane[(q0 as i32 + k * step as i32) as usize]); | |
| 1186 | + (at(-2) - at(-1)).abs() > threshold || (at(1) - at(0)).abs() > threshold | |
| 1187 | +} | |
| 1188 | + | |
| 1189 | +fn subblock_filter( | |
| 1190 | + hev_threshold: i32, | |
| 1191 | + interior: i32, | |
| 1192 | + edge: i32, | |
| 1193 | + plane: &mut [u8], | |
| 1194 | + q0: usize, | |
| 1195 | + step: usize, | |
| 1196 | +) { | |
| 1197 | + if !filter_yes(interior, edge, plane, q0, step) { | |
| 1198 | + return; | |
| 1199 | + } | |
| 1200 | + let high = hev(hev_threshold, plane, q0, step); | |
| 1201 | + let a = (common_adjust(high, plane, q0, step) + 1) >> 1; | |
| 1202 | + if !high { | |
| 1203 | + let q1 = u2s(plane[q0 + step]); | |
| 1204 | + let p1 = u2s(plane[q0 - 2 * step]); | |
| 1205 | + plane[q0 + step] = s2u(q1 - a); | |
| 1206 | + plane[q0 - 2 * step] = s2u(p1 + a); | |
| 1207 | + } | |
| 1208 | +} | |
| 1209 | + | |
| 1210 | +fn mb_filter( | |
| 1211 | + hev_threshold: i32, | |
| 1212 | + interior: i32, | |
| 1213 | + edge: i32, | |
| 1214 | + plane: &mut [u8], | |
| 1215 | + q0: usize, | |
| 1216 | + step: usize, | |
| 1217 | +) { | |
| 1218 | + if !filter_yes(interior, edge, plane, q0, step) { | |
| 1219 | + return; | |
| 1220 | + } | |
| 1221 | + if hev(hev_threshold, plane, q0, step) { | |
| 1222 | + common_adjust(true, plane, q0, step); | |
| 1223 | + return; | |
| 1224 | + } | |
| 1225 | + let p2 = u2s(plane[q0 - 3 * step]); | |
| 1226 | + let p1 = u2s(plane[q0 - 2 * step]); | |
| 1227 | + let p0 = u2s(plane[q0 - step]); | |
| 1228 | + let q0v = u2s(plane[q0]); | |
| 1229 | + let q1 = u2s(plane[q0 + step]); | |
| 1230 | + let q2 = u2s(plane[q0 + 2 * step]); | |
| 1231 | + let w = c8(c8(p1 - q1) + 3 * (q0v - p0)); | |
| 1232 | + let a = c8((27 * w + 63) >> 7); | |
| 1233 | + plane[q0] = s2u(q0v - a); | |
| 1234 | + plane[q0 - step] = s2u(p0 + a); | |
| 1235 | + let a = c8((18 * w + 63) >> 7); | |
| 1236 | + plane[q0 + step] = s2u(q1 - a); | |
| 1237 | + plane[q0 - 2 * step] = s2u(p1 + a); | |
| 1238 | + let a = c8((9 * w + 63) >> 7); | |
| 1239 | + plane[q0 + 2 * step] = s2u(q2 - a); | |
| 1240 | + plane[q0 - 3 * step] = s2u(p2 + a); | |
| 1241 | +} | |
| 1242 | + | |
| 1243 | +/// Per-macroblock filter strength, exactly as section 15.4 derives it. | |
| 1244 | +fn filter_parameters(header: &Header, info: &MbInfo) -> (i32, i32, i32) { | |
| 1245 | + let mut level = header.filter_level; | |
| 1246 | + if header.segmentation { | |
| 1247 | + level = if header.segment_lf_absolute { | |
| 1248 | + header.segment_lf[info.segment] | |
| 1249 | + } else { | |
| 1250 | + level + header.segment_lf[info.segment] | |
| 1251 | + }; | |
| 1252 | + } | |
| 1253 | + level = level.clamp(0, 63); | |
| 1254 | + if header.delta_enabled { | |
| 1255 | + // A key frame's every macroblock references the current frame, so the | |
| 1256 | + // reference delta is always index 0 and the mode delta only applies to | |
| 1257 | + // B_PRED. | |
| 1258 | + level += header.ref_delta[0]; | |
| 1259 | + if info.y_mode == B_PRED { | |
| 1260 | + level += header.mode_delta[0]; | |
| 1261 | + } | |
| 1262 | + } | |
| 1263 | + let level = level.clamp(0, 63); | |
| 1264 | + let mut interior = level; | |
| 1265 | + if header.sharpness > 0 { | |
| 1266 | + interior >>= if header.sharpness > 4 { 2 } else { 1 }; | |
| 1267 | + interior = interior.min(9 - header.sharpness); | |
| 1268 | + } | |
| 1269 | + interior = interior.max(1); | |
| 1270 | + let mut hev_threshold = i32::from(level >= 15); | |
| 1271 | + if level >= 40 { | |
| 1272 | + hev_threshold += 1; | |
| 1273 | + } | |
| 1274 | + (level, interior, hev_threshold) | |
| 1275 | +} | |
| 1276 | + | |
| 1277 | +fn loop_filter( | |
| 1278 | + frame: &mut Frame, | |
| 1279 | + header: &Header, | |
| 1280 | + infos: &[MbInfo], | |
| 1281 | + mb_cols: usize, | |
| 1282 | + mb_rows: usize, | |
| 1283 | +) { | |
| 1284 | + let sy = frame.stride_y; | |
| 1285 | + let suv = frame.stride_uv; | |
| 1286 | + for mb_y in 0..mb_rows { | |
| 1287 | + for mb_x in 0..mb_cols { | |
| 1288 | + let info = infos[mb_y * mb_cols + mb_x]; | |
| 1289 | + let (level, interior, hev_threshold) = filter_parameters(header, &info); | |
| 1290 | + if level == 0 { | |
| 1291 | + continue; | |
| 1292 | + } | |
| 1293 | + let mb_edge = (level + 2) * 2 + interior; | |
| 1294 | + let sub_edge = level * 2 + interior; | |
| 1295 | + // Interior edges are skipped where the macroblock has no residue | |
| 1296 | + // and predicts as a whole; nothing there can have a block edge. | |
| 1297 | + let skip_interior = !info.has_coeffs && info.y_mode != B_PRED; | |
| 1298 | + let (yx, yy) = (mb_x * 16, mb_y * 16); | |
| 1299 | + let (cx, cy) = (mb_x * 8, mb_y * 8); | |
| 1300 | + | |
| 1301 | + if header.filter_simple { | |
| 1302 | + if mb_x > 0 { | |
| 1303 | + for r in 0..16 { | |
| 1304 | + simple_segment(mb_edge, &mut frame.y, (yy + r) * sy + yx, 1); | |
| 1305 | + } | |
| 1306 | + } | |
| 1307 | + if !skip_interior { | |
| 1308 | + for c in [4, 8, 12] { | |
| 1309 | + for r in 0..16 { | |
| 1310 | + simple_segment(sub_edge, &mut frame.y, (yy + r) * sy + yx + c, 1); | |
| 1311 | + } | |
| 1312 | + } | |
| 1313 | + } | |
| 1314 | + if mb_y > 0 { | |
| 1315 | + for c in 0..16 { | |
| 1316 | + simple_segment(mb_edge, &mut frame.y, yy * sy + yx + c, sy); | |
| 1317 | + } | |
| 1318 | + } | |
| 1319 | + if !skip_interior { | |
| 1320 | + for r in [4, 8, 12] { | |
| 1321 | + for c in 0..16 { | |
| 1322 | + simple_segment(sub_edge, &mut frame.y, (yy + r) * sy + yx + c, sy); | |
| 1323 | + } | |
| 1324 | + } | |
| 1325 | + } | |
| 1326 | + continue; | |
| 1327 | + } | |
| 1328 | + | |
| 1329 | + if mb_x > 0 { | |
| 1330 | + for r in 0..16 { | |
| 1331 | + mb_filter( | |
| 1332 | + hev_threshold, | |
| 1333 | + interior, | |
| 1334 | + mb_edge, | |
| 1335 | + &mut frame.y, | |
| 1336 | + (yy + r) * sy + yx, | |
| 1337 | + 1, | |
| 1338 | + ); | |
| 1339 | + } | |
| 1340 | + for r in 0..8 { | |
| 1341 | + mb_filter( | |
| 1342 | + hev_threshold, | |
| 1343 | + interior, | |
| 1344 | + mb_edge, | |
| 1345 | + &mut frame.u, | |
| 1346 | + (cy + r) * suv + cx, | |
| 1347 | + 1, | |
| 1348 | + ); | |
| 1349 | + mb_filter( | |
| 1350 | + hev_threshold, | |
| 1351 | + interior, | |
| 1352 | + mb_edge, | |
| 1353 | + &mut frame.v, | |
| 1354 | + (cy + r) * suv + cx, | |
| 1355 | + 1, | |
| 1356 | + ); | |
| 1357 | + } | |
| 1358 | + } | |
| 1359 | + if !skip_interior { | |
| 1360 | + for c in [4, 8, 12] { | |
| 1361 | + for r in 0..16 { | |
| 1362 | + subblock_filter( | |
| 1363 | + hev_threshold, | |
| 1364 | + interior, | |
| 1365 | + sub_edge, | |
| 1366 | + &mut frame.y, | |
| 1367 | + (yy + r) * sy + yx + c, | |
| 1368 | + 1, | |
| 1369 | + ); | |
| 1370 | + } | |
| 1371 | + } | |
| 1372 | + for r in 0..8 { | |
| 1373 | + subblock_filter( | |
| 1374 | + hev_threshold, | |
| 1375 | + interior, | |
| 1376 | + sub_edge, | |
| 1377 | + &mut frame.u, | |
| 1378 | + (cy + r) * suv + cx + 4, | |
| 1379 | + 1, | |
| 1380 | + ); | |
| 1381 | + subblock_filter( | |
| 1382 | + hev_threshold, | |
| 1383 | + interior, | |
| 1384 | + sub_edge, | |
| 1385 | + &mut frame.v, | |
| 1386 | + (cy + r) * suv + cx + 4, | |
| 1387 | + 1, | |
| 1388 | + ); | |
| 1389 | + } | |
| 1390 | + } | |
| 1391 | + if mb_y > 0 { | |
| 1392 | + for c in 0..16 { | |
| 1393 | + mb_filter( | |
| 1394 | + hev_threshold, | |
| 1395 | + interior, | |
| 1396 | + mb_edge, | |
| 1397 | + &mut frame.y, | |
| 1398 | + yy * sy + yx + c, | |
| 1399 | + sy, | |
| 1400 | + ); | |
| 1401 | + } | |
| 1402 | + for c in 0..8 { | |
| 1403 | + mb_filter( | |
| 1404 | + hev_threshold, | |
| 1405 | + interior, | |
| 1406 | + mb_edge, | |
| 1407 | + &mut frame.u, | |
| 1408 | + cy * suv + cx + c, | |
| 1409 | + suv, | |
| 1410 | + ); | |
| 1411 | + mb_filter( | |
| 1412 | + hev_threshold, | |
| 1413 | + interior, | |
| 1414 | + mb_edge, | |
| 1415 | + &mut frame.v, | |
| 1416 | + cy * suv + cx + c, | |
| 1417 | + suv, | |
| 1418 | + ); | |
| 1419 | + } | |
| 1420 | + } | |
| 1421 | + if !skip_interior { | |
| 1422 | + for r in [4, 8, 12] { | |
| 1423 | + for c in 0..16 { | |
| 1424 | + subblock_filter( | |
| 1425 | + hev_threshold, | |
| 1426 | + interior, | |
| 1427 | + sub_edge, | |
| 1428 | + &mut frame.y, | |
| 1429 | + (yy + r) * sy + yx + c, | |
| 1430 | + sy, | |
| 1431 | + ); | |
| 1432 | + } | |
| 1433 | + } | |
| 1434 | + for c in 0..8 { | |
| 1435 | + subblock_filter( | |
| 1436 | + hev_threshold, | |
| 1437 | + interior, | |
| 1438 | + sub_edge, | |
| 1439 | + &mut frame.u, | |
| 1440 | + (cy + 4) * suv + cx + c, | |
| 1441 | + suv, | |
| 1442 | + ); | |
| 1443 | + subblock_filter( | |
| 1444 | + hev_threshold, | |
| 1445 | + interior, | |
| 1446 | + sub_edge, | |
| 1447 | + &mut frame.v, | |
| 1448 | + (cy + 4) * suv + cx + c, | |
| 1449 | + suv, | |
| 1450 | + ); | |
| 1451 | + } | |
| 1452 | + } | |
| 1453 | + } | |
| 1454 | + } | |
| 1455 | +} | |
| 1456 | + | |
| 1457 | +#[cfg(test)] | |
| 1458 | +mod tests { | |
| 1459 | + use super::*; | |
| 1460 | + | |
| 1461 | + /// The encoder of RFC 6386 section 7.3, so the decoder can be checked | |
| 1462 | + /// against the thing it has to invert rather than against an assumption | |
| 1463 | + /// about what the bits look like. | |
| 1464 | + struct BoolEncoder { | |
| 1465 | + out: Vec<u8>, | |
| 1466 | + range: u32, | |
| 1467 | + bottom: u32, | |
| 1468 | + bit_count: i32, | |
| 1469 | + } | |
| 1470 | + | |
| 1471 | + impl BoolEncoder { | |
| 1472 | + fn new() -> BoolEncoder { | |
| 1473 | + BoolEncoder { | |
| 1474 | + out: Vec::new(), | |
| 1475 | + range: 255, | |
| 1476 | + bottom: 0, | |
| 1477 | + bit_count: 24, | |
| 1478 | + } | |
| 1479 | + } | |
| 1480 | + | |
| 1481 | + fn carry(&mut self) { | |
| 1482 | + let mut i = self.out.len(); | |
| 1483 | + while i > 0 { | |
| 1484 | + i -= 1; | |
| 1485 | + if self.out[i] == 255 { | |
| 1486 | + self.out[i] = 0; | |
| 1487 | + } else { | |
| 1488 | + self.out[i] += 1; | |
| 1489 | + return; | |
| 1490 | + } | |
| 1491 | + } | |
| 1492 | + } | |
| 1493 | + | |
| 1494 | + fn write(&mut self, prob: u8, value: u32) { | |
| 1495 | + let split = 1 + (((self.range - 1) * u32::from(prob)) >> 8); | |
| 1496 | + if value != 0 { | |
| 1497 | + self.bottom += split; | |
| 1498 | + self.range -= split; | |
| 1499 | + } else { | |
| 1500 | + self.range = split; | |
| 1501 | + } | |
| 1502 | + while self.range < 128 { | |
| 1503 | + self.range <<= 1; | |
| 1504 | + if self.bottom & (1 << 31) != 0 { | |
| 1505 | + self.carry(); | |
| 1506 | + } | |
| 1507 | + self.bottom <<= 1; | |
| 1508 | + self.bit_count -= 1; | |
| 1509 | + if self.bit_count == 0 { | |
| 1510 | + self.out.push((self.bottom >> 24) as u8); | |
| 1511 | + self.bottom &= (1 << 24) - 1; | |
| 1512 | + self.bit_count = 8; | |
| 1513 | + } | |
| 1514 | + } | |
| 1515 | + } | |
| 1516 | + | |
| 1517 | + fn literal(&mut self, n: u32, value: u32) { | |
| 1518 | + for i in (0..n).rev() { | |
| 1519 | + self.write(128, (value >> i) & 1); | |
| 1520 | + } | |
| 1521 | + } | |
| 1522 | + | |
| 1523 | + fn finish(mut self) -> Vec<u8> { | |
| 1524 | + let mut c = self.bit_count; | |
| 1525 | + let mut v = self.bottom; | |
| 1526 | + if v & (1u32 << (32 - c)) != 0 { | |
| 1527 | + self.carry(); | |
| 1528 | + } | |
| 1529 | + v <<= c & 7; | |
| 1530 | + c >>= 3; | |
| 1531 | + while c > 0 { | |
| 1532 | + v <<= 8; | |
| 1533 | + c -= 1; | |
| 1534 | + } | |
| 1535 | + for _ in 0..4 { | |
| 1536 | + self.out.push((v >> 24) as u8); | |
| 1537 | + v <<= 8; | |
| 1538 | + } | |
| 1539 | + self.out | |
| 1540 | + } | |
| 1541 | + } | |
| 1542 | + | |
| 1543 | + #[test] | |
| 1544 | + fn the_bool_decoder_inverts_the_specification_encoder() { | |
| 1545 | + let probs = [128u8, 1, 255, 200, 32, 145]; | |
| 1546 | + let bits: Vec<u32> = (0..600) | |
| 1547 | + .map(|i: u32| (i.wrapping_mul(2_654_435_761)) >> 31) | |
| 1548 | + .collect(); | |
| 1549 | + let mut encoder = BoolEncoder::new(); | |
| 1550 | + for (i, &bit) in bits.iter().enumerate() { | |
| 1551 | + encoder.write(probs[i % probs.len()], bit); | |
| 1552 | + } | |
| 1553 | + encoder.literal(8, 0xb2); | |
| 1554 | + encoder.literal(12, 0x4d3); | |
| 1555 | + let data = encoder.finish(); | |
| 1556 | + | |
| 1557 | + let mut bd = BoolDecoder::new(&data); | |
| 1558 | + for (i, &bit) in bits.iter().enumerate() { | |
| 1559 | + assert_eq!(bd.bool(probs[i % probs.len()]), bit, "bool {i}"); | |
| 1560 | + } | |
| 1561 | + assert_eq!(bd.literal(8), 0xb2); | |
| 1562 | + assert_eq!(bd.literal(12), 0x4d3); | |
| 1563 | + } | |
| 1564 | + | |
| 1565 | + #[test] | |
| 1566 | + fn trees_decode_their_leaves() { | |
| 1567 | + // A stream of zero bits walks the leftmost branch of each tree. | |
| 1568 | + let data = [0u8; 8]; | |
| 1569 | + let mut bd = BoolDecoder::new(&data); | |
| 1570 | + assert_eq!(bd.tree(&KF_YMODE_TREE, &KF_YMODE_PROBS, 0), B_PRED); | |
| 1571 | + let mut bd = BoolDecoder::new(&data); | |
| 1572 | + assert_eq!(bd.tree(&UV_MODE_TREE, &KF_UV_MODE_PROBS, 0), DC_PRED); | |
| 1573 | + let mut bd = BoolDecoder::new(&data); | |
| 1574 | + assert_eq!(bd.tree(&BMODE_TREE, &KF_BMODE_PROBS[0][0], 0), B_DC_PRED); | |
| 1575 | + let mut bd = BoolDecoder::new(&data); | |
| 1576 | + assert_eq!( | |
| 1577 | + bd.tree(&COEFF_TREE, &[128; 11], 0), | |
| 1578 | + 11, | |
| 1579 | + "eob is the 0 branch" | |
| 1580 | + ); | |
| 1581 | + } | |
| 1582 | + | |
| 1583 | + #[test] | |
| 1584 | + fn the_inverse_dct_of_a_dc_only_block_is_flat() { | |
| 1585 | + let mut block = [0i16; 16]; | |
| 1586 | + block[0] = 80; | |
| 1587 | + let out = inverse_dct(&block); | |
| 1588 | + for v in out { | |
| 1589 | + assert_eq!(v, 10, "DC 80 spreads to (80 + 4) >> 3 everywhere"); | |
| 1590 | + } | |
| 1591 | + } | |
| 1592 | + | |
| 1593 | + #[test] | |
| 1594 | + fn the_inverse_wht_matches_its_specification() { | |
| 1595 | + let mut input = [0i16; 16]; | |
| 1596 | + input[0] = 64; | |
| 1597 | + let mut coeffs = [[0i16; 16]; 25]; | |
| 1598 | + inverse_wht(&input, &mut coeffs); | |
| 1599 | + for block in coeffs.iter().take(16) { | |
| 1600 | + assert_eq!(block[0], 8, "a flat WHT spreads its DC over the 16 blocks"); | |
| 1601 | + } | |
| 1602 | + } | |
| 1603 | + | |
| 1604 | + #[test] | |
| 1605 | + fn dequant_factors_follow_the_scaling_rules() { | |
| 1606 | + assert_eq!(dc_q(0), 4); | |
| 1607 | + assert_eq!(ac_q(127), 284); | |
| 1608 | + // Y2 AC is scaled by 155/100 with a floor of 8, chroma DC caps at 132. | |
| 1609 | + assert_eq!((ac_q(0) * 155 / 100).max(8), 8); | |
| 1610 | + assert_eq!(dc_q(127).min(132), 132); | |
| 1611 | + } | |
| 1612 | +} |
crates/ec-image/src/webp/vp8_tables.rsadded+500 -0
| @@ -0,0 +1,500 @@ | ||
| 1 | +//! VP8 constant tables, generated from the RFC 6386 text by | |
| 2 | +//! `scratchpad/s40/gen_vp8_tables.py` — every value is the spec's own. | |
| 3 | +//! | |
| 4 | +//! Regenerating beats retyping: a single transposed probability shows up as a | |
| 5 | +//! plausible-looking decode that drifts from the reference several | |
| 6 | +//! macroblocks later. | |
| 7 | + | |
| 8 | +/// Keyframe subblock mode probabilities, indexed [above][left][node]. | |
| 9 | +pub const KF_BMODE_PROBS: [[[u8; 9]; 10]; 10] = [ | |
| 10 | + [ | |
| 11 | + [231, 120, 48, 89, 115, 113, 120, 152, 112], | |
| 12 | + [152, 179, 64, 126, 170, 118, 46, 70, 95], | |
| 13 | + [175, 69, 143, 80, 85, 82, 72, 155, 103], | |
| 14 | + [56, 58, 10, 171, 218, 189, 17, 13, 152], | |
| 15 | + [144, 71, 10, 38, 171, 213, 144, 34, 26], | |
| 16 | + [114, 26, 17, 163, 44, 195, 21, 10, 173], | |
| 17 | + [121, 24, 80, 195, 26, 62, 44, 64, 85], | |
| 18 | + [170, 46, 55, 19, 136, 160, 33, 206, 71], | |
| 19 | + [63, 20, 8, 114, 114, 208, 12, 9, 226], | |
| 20 | + [81, 40, 11, 96, 182, 84, 29, 16, 36], | |
| 21 | + ], | |
| 22 | + [ | |
| 23 | + [134, 183, 89, 137, 98, 101, 106, 165, 148], | |
| 24 | + [72, 187, 100, 130, 157, 111, 32, 75, 80], | |
| 25 | + [66, 102, 167, 99, 74, 62, 40, 234, 128], | |
| 26 | + [41, 53, 9, 178, 241, 141, 26, 8, 107], | |
| 27 | + [104, 79, 12, 27, 217, 255, 87, 17, 7], | |
| 28 | + [74, 43, 26, 146, 73, 166, 49, 23, 157], | |
| 29 | + [65, 38, 105, 160, 51, 52, 31, 115, 128], | |
| 30 | + [87, 68, 71, 44, 114, 51, 15, 186, 23], | |
| 31 | + [47, 41, 14, 110, 182, 183, 21, 17, 194], | |
| 32 | + [66, 45, 25, 102, 197, 189, 23, 18, 22], | |
| 33 | + ], | |
| 34 | + [ | |
| 35 | + [88, 88, 147, 150, 42, 46, 45, 196, 205], | |
| 36 | + [43, 97, 183, 117, 85, 38, 35, 179, 61], | |
| 37 | + [39, 53, 200, 87, 26, 21, 43, 232, 171], | |
| 38 | + [56, 34, 51, 104, 114, 102, 29, 93, 77], | |
| 39 | + [107, 54, 32, 26, 51, 1, 81, 43, 31], | |
| 40 | + [39, 28, 85, 171, 58, 165, 90, 98, 64], | |
| 41 | + [34, 22, 116, 206, 23, 34, 43, 166, 73], | |
| 42 | + [68, 25, 106, 22, 64, 171, 36, 225, 114], | |
| 43 | + [34, 19, 21, 102, 132, 188, 16, 76, 124], | |
| 44 | + [62, 18, 78, 95, 85, 57, 50, 48, 51], | |
| 45 | + ], | |
| 46 | + [ | |
| 47 | + [193, 101, 35, 159, 215, 111, 89, 46, 111], | |
| 48 | + [60, 148, 31, 172, 219, 228, 21, 18, 111], | |
| 49 | + [112, 113, 77, 85, 179, 255, 38, 120, 114], | |
| 50 | + [40, 42, 1, 196, 245, 209, 10, 25, 109], | |
| 51 | + [100, 80, 8, 43, 154, 1, 51, 26, 71], | |
| 52 | + [88, 43, 29, 140, 166, 213, 37, 43, 154], | |
| 53 | + [61, 63, 30, 155, 67, 45, 68, 1, 209], | |
| 54 | + [142, 78, 78, 16, 255, 128, 34, 197, 171], | |
| 55 | + [41, 40, 5, 102, 211, 183, 4, 1, 221], | |
| 56 | + [51, 50, 17, 168, 209, 192, 23, 25, 82], | |
| 57 | + ], | |
| 58 | + [ | |
| 59 | + [125, 98, 42, 88, 104, 85, 117, 175, 82], | |
| 60 | + [95, 84, 53, 89, 128, 100, 113, 101, 45], | |
| 61 | + [75, 79, 123, 47, 51, 128, 81, 171, 1], | |
| 62 | + [57, 17, 5, 71, 102, 57, 53, 41, 49], | |
| 63 | + [115, 21, 2, 10, 102, 255, 166, 23, 6], | |
| 64 | + [38, 33, 13, 121, 57, 73, 26, 1, 85], | |
| 65 | + [41, 10, 67, 138, 77, 110, 90, 47, 114], | |
| 66 | + [101, 29, 16, 10, 85, 128, 101, 196, 26], | |
| 67 | + [57, 18, 10, 102, 102, 213, 34, 20, 43], | |
| 68 | + [117, 20, 15, 36, 163, 128, 68, 1, 26], | |
| 69 | + ], | |
| 70 | + [ | |
| 71 | + [138, 31, 36, 171, 27, 166, 38, 44, 229], | |
| 72 | + [67, 87, 58, 169, 82, 115, 26, 59, 179], | |
| 73 | + [63, 59, 90, 180, 59, 166, 93, 73, 154], | |
| 74 | + [40, 40, 21, 116, 143, 209, 34, 39, 175], | |
| 75 | + [57, 46, 22, 24, 128, 1, 54, 17, 37], | |
| 76 | + [47, 15, 16, 183, 34, 223, 49, 45, 183], | |
| 77 | + [46, 17, 33, 183, 6, 98, 15, 32, 183], | |
| 78 | + [65, 32, 73, 115, 28, 128, 23, 128, 205], | |
| 79 | + [40, 3, 9, 115, 51, 192, 18, 6, 223], | |
| 80 | + [87, 37, 9, 115, 59, 77, 64, 21, 47], | |
| 81 | + ], | |
| 82 | + [ | |
| 83 | + [104, 55, 44, 218, 9, 54, 53, 130, 226], | |
| 84 | + [64, 90, 70, 205, 40, 41, 23, 26, 57], | |
| 85 | + [54, 57, 112, 184, 5, 41, 38, 166, 213], | |
| 86 | + [30, 34, 26, 133, 152, 116, 10, 32, 134], | |
| 87 | + [75, 32, 12, 51, 192, 255, 160, 43, 51], | |
| 88 | + [39, 19, 53, 221, 26, 114, 32, 73, 255], | |
| 89 | + [31, 9, 65, 234, 2, 15, 1, 118, 73], | |
| 90 | + [88, 31, 35, 67, 102, 85, 55, 186, 85], | |
| 91 | + [56, 21, 23, 111, 59, 205, 45, 37, 192], | |
| 92 | + [55, 38, 70, 124, 73, 102, 1, 34, 98], | |
| 93 | + ], | |
| 94 | + [ | |
| 95 | + [102, 61, 71, 37, 34, 53, 31, 243, 192], | |
| 96 | + [69, 60, 71, 38, 73, 119, 28, 222, 37], | |
| 97 | + [68, 45, 128, 34, 1, 47, 11, 245, 171], | |
| 98 | + [62, 17, 19, 70, 146, 85, 55, 62, 70], | |
| 99 | + [75, 15, 9, 9, 64, 255, 184, 119, 16], | |
| 100 | + [37, 43, 37, 154, 100, 163, 85, 160, 1], | |
| 101 | + [63, 9, 92, 136, 28, 64, 32, 201, 85], | |
| 102 | + [86, 6, 28, 5, 64, 255, 25, 248, 1], | |
| 103 | + [56, 8, 17, 132, 137, 255, 55, 116, 128], | |
| 104 | + [58, 15, 20, 82, 135, 57, 26, 121, 40], | |
| 105 | + ], | |
| 106 | + [ | |
| 107 | + [164, 50, 31, 137, 154, 133, 25, 35, 218], | |
| 108 | + [51, 103, 44, 131, 131, 123, 31, 6, 158], | |
| 109 | + [86, 40, 64, 135, 148, 224, 45, 183, 128], | |
| 110 | + [22, 26, 17, 131, 240, 154, 14, 1, 209], | |
| 111 | + [83, 12, 13, 54, 192, 255, 68, 47, 28], | |
| 112 | + [45, 16, 21, 91, 64, 222, 7, 1, 197], | |
| 113 | + [56, 21, 39, 155, 60, 138, 23, 102, 213], | |
| 114 | + [85, 26, 85, 85, 128, 128, 32, 146, 171], | |
| 115 | + [18, 11, 7, 63, 144, 171, 4, 4, 246], | |
| 116 | + [35, 27, 10, 146, 174, 171, 12, 26, 128], | |
| 117 | + ], | |
| 118 | + [ | |
| 119 | + [190, 80, 35, 99, 180, 80, 126, 54, 45], | |
| 120 | + [85, 126, 47, 87, 176, 51, 41, 20, 32], | |
| 121 | + [101, 75, 128, 139, 118, 146, 116, 128, 85], | |
| 122 | + [56, 41, 15, 176, 236, 85, 37, 9, 62], | |
| 123 | + [146, 36, 19, 30, 171, 255, 97, 27, 20], | |
| 124 | + [71, 30, 17, 119, 118, 255, 17, 18, 138], | |
| 125 | + [101, 38, 60, 138, 55, 70, 43, 26, 142], | |
| 126 | + [138, 45, 61, 62, 219, 1, 81, 188, 64], | |
| 127 | + [32, 41, 20, 117, 151, 142, 20, 21, 163], | |
| 128 | + [112, 19, 12, 61, 195, 128, 48, 4, 24], | |
| 129 | + ], | |
| 130 | +]; | |
| 131 | + | |
| 132 | +/// Probability that a given token probability is updated in the header. | |
| 133 | +pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ | |
| 134 | + [ | |
| 135 | + [ | |
| 136 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 137 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 138 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 139 | + ], | |
| 140 | + [ | |
| 141 | + [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 142 | + [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 143 | + [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 144 | + ], | |
| 145 | + [ | |
| 146 | + [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 147 | + [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 148 | + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 149 | + ], | |
| 150 | + [ | |
| 151 | + [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 152 | + [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 153 | + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 154 | + ], | |
| 155 | + [ | |
| 156 | + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 157 | + [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 158 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 159 | + ], | |
| 160 | + [ | |
| 161 | + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 162 | + [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 163 | + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 164 | + ], | |
| 165 | + [ | |
| 166 | + [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255], | |
| 167 | + [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255], | |
| 168 | + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 169 | + ], | |
| 170 | + [ | |
| 171 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 172 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 173 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 174 | + ], | |
| 175 | + ], | |
| 176 | + [ | |
| 177 | + [ | |
| 178 | + [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 179 | + [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255], | |
| 180 | + [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255], | |
| 181 | + ], | |
| 182 | + [ | |
| 183 | + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 184 | + [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 185 | + [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255], | |
| 186 | + ], | |
| 187 | + [ | |
| 188 | + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 189 | + [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 190 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 191 | + ], | |
| 192 | + [ | |
| 193 | + [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 194 | + [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 195 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 196 | + ], | |
| 197 | + [ | |
| 198 | + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 199 | + [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 200 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 201 | + ], | |
| 202 | + [ | |
| 203 | + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 204 | + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 205 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 206 | + ], | |
| 207 | + [ | |
| 208 | + [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 209 | + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 210 | + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 211 | + ], | |
| 212 | + [ | |
| 213 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 214 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 215 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 216 | + ], | |
| 217 | + ], | |
| 218 | + [ | |
| 219 | + [ | |
| 220 | + [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 221 | + [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255], | |
| 222 | + [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255], | |
| 223 | + ], | |
| 224 | + [ | |
| 225 | + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 226 | + [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 227 | + [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255], | |
| 228 | + ], | |
| 229 | + [ | |
| 230 | + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 231 | + [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 232 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 233 | + ], | |
| 234 | + [ | |
| 235 | + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 236 | + [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 237 | + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 238 | + ], | |
| 239 | + [ | |
| 240 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 241 | + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 242 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 243 | + ], | |
| 244 | + [ | |
| 245 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 246 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 247 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 248 | + ], | |
| 249 | + [ | |
| 250 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 251 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 252 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 253 | + ], | |
| 254 | + [ | |
| 255 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 256 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 257 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 258 | + ], | |
| 259 | + ], | |
| 260 | + [ | |
| 261 | + [ | |
| 262 | + [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 263 | + [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255], | |
| 264 | + [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255], | |
| 265 | + ], | |
| 266 | + [ | |
| 267 | + [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 268 | + [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 269 | + [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255], | |
| 270 | + ], | |
| 271 | + [ | |
| 272 | + [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 273 | + [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 274 | + [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255], | |
| 275 | + ], | |
| 276 | + [ | |
| 277 | + [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 278 | + [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 279 | + [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 280 | + ], | |
| 281 | + [ | |
| 282 | + [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 283 | + [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 284 | + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 285 | + ], | |
| 286 | + [ | |
| 287 | + [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 288 | + [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 289 | + [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 290 | + ], | |
| 291 | + [ | |
| 292 | + [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 293 | + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 294 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 295 | + ], | |
| 296 | + [ | |
| 297 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 298 | + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 299 | + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], | |
| 300 | + ], | |
| 301 | + ], | |
| 302 | +]; | |
| 303 | + | |
| 304 | +/// Token probabilities a keyframe starts from, [type][band][context][node]. | |
| 305 | +pub const DEFAULT_COEFF_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ | |
| 306 | + [ | |
| 307 | + [ | |
| 308 | + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 309 | + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 310 | + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 311 | + ], | |
| 312 | + [ | |
| 313 | + [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128], | |
| 314 | + [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128], | |
| 315 | + [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128], | |
| 316 | + ], | |
| 317 | + [ | |
| 318 | + [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128], | |
| 319 | + [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128], | |
| 320 | + [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128], | |
| 321 | + ], | |
| 322 | + [ | |
| 323 | + [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128], | |
| 324 | + [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128], | |
| 325 | + [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128], | |
| 326 | + ], | |
| 327 | + [ | |
| 328 | + [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128], | |
| 329 | + [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128], | |
| 330 | + [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128], | |
| 331 | + ], | |
| 332 | + [ | |
| 333 | + [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128], | |
| 334 | + [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128], | |
| 335 | + [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128], | |
| 336 | + ], | |
| 337 | + [ | |
| 338 | + [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128], | |
| 339 | + [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128], | |
| 340 | + [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128], | |
| 341 | + ], | |
| 342 | + [ | |
| 343 | + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 344 | + [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 345 | + [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 346 | + ], | |
| 347 | + ], | |
| 348 | + [ | |
| 349 | + [ | |
| 350 | + [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62], | |
| 351 | + [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1], | |
| 352 | + [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128], | |
| 353 | + ], | |
| 354 | + [ | |
| 355 | + [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128], | |
| 356 | + [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128], | |
| 357 | + [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128], | |
| 358 | + ], | |
| 359 | + [ | |
| 360 | + [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128], | |
| 361 | + [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128], | |
| 362 | + [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128], | |
| 363 | + ], | |
| 364 | + [ | |
| 365 | + [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128], | |
| 366 | + [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128], | |
| 367 | + [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128], | |
| 368 | + ], | |
| 369 | + [ | |
| 370 | + [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128], | |
| 371 | + [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128], | |
| 372 | + [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128], | |
| 373 | + ], | |
| 374 | + [ | |
| 375 | + [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128], | |
| 376 | + [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128], | |
| 377 | + [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128], | |
| 378 | + ], | |
| 379 | + [ | |
| 380 | + [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128], | |
| 381 | + [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128], | |
| 382 | + [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128], | |
| 383 | + ], | |
| 384 | + [ | |
| 385 | + [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128], | |
| 386 | + [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128], | |
| 387 | + [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128], | |
| 388 | + ], | |
| 389 | + ], | |
| 390 | + [ | |
| 391 | + [ | |
| 392 | + [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128], | |
| 393 | + [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128], | |
| 394 | + [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128], | |
| 395 | + ], | |
| 396 | + [ | |
| 397 | + [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128], | |
| 398 | + [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128], | |
| 399 | + [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128], | |
| 400 | + ], | |
| 401 | + [ | |
| 402 | + [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128], | |
| 403 | + [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128], | |
| 404 | + [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128], | |
| 405 | + ], | |
| 406 | + [ | |
| 407 | + [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128], | |
| 408 | + [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128], | |
| 409 | + [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128], | |
| 410 | + ], | |
| 411 | + [ | |
| 412 | + [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128], | |
| 413 | + [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128], | |
| 414 | + [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 415 | + ], | |
| 416 | + [ | |
| 417 | + [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 418 | + [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 419 | + [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 420 | + ], | |
| 421 | + [ | |
| 422 | + [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128], | |
| 423 | + [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128], | |
| 424 | + [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 425 | + ], | |
| 426 | + [ | |
| 427 | + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 428 | + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 429 | + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 430 | + ], | |
| 431 | + ], | |
| 432 | + [ | |
| 433 | + [ | |
| 434 | + [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255], | |
| 435 | + [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128], | |
| 436 | + [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128], | |
| 437 | + ], | |
| 438 | + [ | |
| 439 | + [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128], | |
| 440 | + [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128], | |
| 441 | + [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128], | |
| 442 | + ], | |
| 443 | + [ | |
| 444 | + [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128], | |
| 445 | + [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128], | |
| 446 | + [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128], | |
| 447 | + ], | |
| 448 | + [ | |
| 449 | + [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128], | |
| 450 | + [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128], | |
| 451 | + [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128], | |
| 452 | + ], | |
| 453 | + [ | |
| 454 | + [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128], | |
| 455 | + [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128], | |
| 456 | + [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128], | |
| 457 | + ], | |
| 458 | + [ | |
| 459 | + [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128], | |
| 460 | + [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128], | |
| 461 | + [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128], | |
| 462 | + ], | |
| 463 | + [ | |
| 464 | + [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128], | |
| 465 | + [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128], | |
| 466 | + [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128], | |
| 467 | + ], | |
| 468 | + [ | |
| 469 | + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 470 | + [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 471 | + [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], | |
| 472 | + ], | |
| 473 | + ], | |
| 474 | +]; | |
| 475 | + | |
| 476 | +/// DC dequantization factor per quantizer index. | |
| 477 | +pub const DC_QLOOKUP: [i32; 128] = [ | |
| 478 | + 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, | |
| 479 | + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, | |
| 480 | + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, | |
| 481 | + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, | |
| 482 | + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, | |
| 483 | + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, | |
| 484 | +]; | |
| 485 | + | |
| 486 | +/// AC dequantization factor per quantizer index. | |
| 487 | +pub const AC_QLOOKUP: [i32; 128] = [ | |
| 488 | + 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, | |
| 489 | + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, | |
| 490 | + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, | |
| 491 | + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, | |
| 492 | + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, | |
| 493 | + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, | |
| 494 | +]; | |
| 495 | + | |
| 496 | +/// Which probability band each coefficient position uses. | |
| 497 | +pub const COEFF_BANDS: [usize; 16] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7]; | |
| 498 | + | |
| 499 | +/// Coefficient scan order within a 4x4 block. | |
| 500 | +pub const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; |
crates/ec-image/src/webp/vp8l.rsadded+896 -0
| @@ -0,0 +1,896 @@ | ||
| 1 | +//! VP8L: the WebP lossless bitstream. | |
| 2 | +//! | |
| 3 | +//! Prefix-coded ARGB literals, LZ77 backward references over a | |
| 4 | +//! two-dimensionally mapped distance space, a hash-addressed colour cache, and | |
| 5 | +//! four reversible transforms (predictor, colour, subtract-green, colour | |
| 6 | +//! indexing) applied in the reverse of the order they were read. | |
| 7 | +//! | |
| 8 | +//! Decoding is pixel-exact by construction: every step is integer and the | |
| 9 | +//! format is lossless, so a differential test against any other implementation | |
| 10 | +//! either matches every sample or has found a bug. | |
| 11 | + | |
| 12 | +use ec_core::{Error, Result}; | |
| 13 | + | |
| 14 | +/// Distance codes 1..=120 name a pixel in the neighbourhood above/left of the | |
| 15 | +/// current one, as `(x, y)` offsets, straight from the specification's table. | |
| 16 | +const DISTANCE_MAP: [(i32, i32); 120] = [ | |
| 17 | + (0, 1), | |
| 18 | + (1, 0), | |
| 19 | + (1, 1), | |
| 20 | + (-1, 1), | |
| 21 | + (0, 2), | |
| 22 | + (2, 0), | |
| 23 | + (1, 2), | |
| 24 | + (-1, 2), | |
| 25 | + (2, 1), | |
| 26 | + (-2, 1), | |
| 27 | + (2, 2), | |
| 28 | + (-2, 2), | |
| 29 | + (0, 3), | |
| 30 | + (3, 0), | |
| 31 | + (1, 3), | |
| 32 | + (-1, 3), | |
| 33 | + (3, 1), | |
| 34 | + (-3, 1), | |
| 35 | + (2, 3), | |
| 36 | + (-2, 3), | |
| 37 | + (3, 2), | |
| 38 | + (-3, 2), | |
| 39 | + (0, 4), | |
| 40 | + (4, 0), | |
| 41 | + (1, 4), | |
| 42 | + (-1, 4), | |
| 43 | + (4, 1), | |
| 44 | + (-4, 1), | |
| 45 | + (3, 3), | |
| 46 | + (-3, 3), | |
| 47 | + (2, 4), | |
| 48 | + (-2, 4), | |
| 49 | + (4, 2), | |
| 50 | + (-4, 2), | |
| 51 | + (0, 5), | |
| 52 | + (3, 4), | |
| 53 | + (-3, 4), | |
| 54 | + (4, 3), | |
| 55 | + (-4, 3), | |
| 56 | + (5, 0), | |
| 57 | + (1, 5), | |
| 58 | + (-1, 5), | |
| 59 | + (5, 1), | |
| 60 | + (-5, 1), | |
| 61 | + (2, 5), | |
| 62 | + (-2, 5), | |
| 63 | + (5, 2), | |
| 64 | + (-5, 2), | |
| 65 | + (4, 4), | |
| 66 | + (-4, 4), | |
| 67 | + (3, 5), | |
| 68 | + (-3, 5), | |
| 69 | + (5, 3), | |
| 70 | + (-5, 3), | |
| 71 | + (0, 6), | |
| 72 | + (6, 0), | |
| 73 | + (1, 6), | |
| 74 | + (-1, 6), | |
| 75 | + (6, 1), | |
| 76 | + (-6, 1), | |
| 77 | + (2, 6), | |
| 78 | + (-2, 6), | |
| 79 | + (6, 2), | |
| 80 | + (-6, 2), | |
| 81 | + (4, 5), | |
| 82 | + (-4, 5), | |
| 83 | + (5, 4), | |
| 84 | + (-5, 4), | |
| 85 | + (3, 6), | |
| 86 | + (-3, 6), | |
| 87 | + (6, 3), | |
| 88 | + (-6, 3), | |
| 89 | + (0, 7), | |
| 90 | + (7, 0), | |
| 91 | + (1, 7), | |
| 92 | + (-1, 7), | |
| 93 | + (5, 5), | |
| 94 | + (-5, 5), | |
| 95 | + (7, 1), | |
| 96 | + (-7, 1), | |
| 97 | + (4, 6), | |
| 98 | + (-4, 6), | |
| 99 | + (6, 4), | |
| 100 | + (-6, 4), | |
| 101 | + (2, 7), | |
| 102 | + (-2, 7), | |
| 103 | + (7, 2), | |
| 104 | + (-7, 2), | |
| 105 | + (3, 7), | |
| 106 | + (-3, 7), | |
| 107 | + (7, 3), | |
| 108 | + (-7, 3), | |
| 109 | + (5, 6), | |
| 110 | + (-5, 6), | |
| 111 | + (6, 5), | |
| 112 | + (-6, 5), | |
| 113 | + (8, 0), | |
| 114 | + (4, 7), | |
| 115 | + (-4, 7), | |
| 116 | + (7, 4), | |
| 117 | + (-7, 4), | |
| 118 | + (8, 1), | |
| 119 | + (8, 2), | |
| 120 | + (6, 6), | |
| 121 | + (-6, 6), | |
| 122 | + (8, 3), | |
| 123 | + (5, 7), | |
| 124 | + (-5, 7), | |
| 125 | + (7, 5), | |
| 126 | + (-7, 5), | |
| 127 | + (8, 4), | |
| 128 | + (6, 7), | |
| 129 | + (-6, 7), | |
| 130 | + (7, 6), | |
| 131 | + (-7, 6), | |
| 132 | + (8, 5), | |
| 133 | + (7, 7), | |
| 134 | + (-7, 7), | |
| 135 | + (8, 6), | |
| 136 | + (8, 7), | |
| 137 | +]; | |
| 138 | + | |
| 139 | +/// The order code-length code lengths arrive in. | |
| 140 | +const CODE_LENGTH_ORDER: [usize; 19] = [ | |
| 141 | + 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | |
| 142 | +]; | |
| 143 | + | |
| 144 | +const GREEN_EXTRA: usize = 24; | |
| 145 | +const MAX_ALLOWED_CODE_LENGTH: usize = 15; | |
| 146 | + | |
| 147 | +/// Least-significant-bit-first bit reader, as VP8L reads its stream. | |
| 148 | +pub struct BitReader<'a> { | |
| 149 | + data: &'a [u8], | |
| 150 | + /// Bit position from the start of `data`. | |
| 151 | + pos: usize, | |
| 152 | +} | |
| 153 | + | |
| 154 | +impl<'a> BitReader<'a> { | |
| 155 | + /// A reader over `data`, starting at its first bit. | |
| 156 | + pub fn new(data: &'a [u8]) -> BitReader<'a> { | |
| 157 | + BitReader { data, pos: 0 } | |
| 158 | + } | |
| 159 | + | |
| 160 | + /// Read `n` bits (`n <= 24`), low bit first. | |
| 161 | + /// | |
| 162 | + /// Past the end of the data the reader yields zeros and records that it | |
| 163 | + /// ran out; the decode loop reports the truncation rather than panicking | |
| 164 | + /// on a short buffer. | |
| 165 | + pub fn read(&mut self, n: u32) -> u32 { | |
| 166 | + let mut value = 0u32; | |
| 167 | + for i in 0..n { | |
| 168 | + let byte = self.data.get(self.pos >> 3).copied().unwrap_or(0); | |
| 169 | + let bit = (byte >> (self.pos & 7)) & 1; | |
| 170 | + value |= u32::from(bit) << i; | |
| 171 | + self.pos += 1; | |
| 172 | + } | |
| 173 | + value | |
| 174 | + } | |
| 175 | + | |
| 176 | + /// True once more bits have been read than the buffer holds. | |
| 177 | + pub fn exhausted(&self) -> bool { | |
| 178 | + self.pos > self.data.len() * 8 | |
| 179 | + } | |
| 180 | +} | |
| 181 | + | |
| 182 | +/// A canonical prefix code, decoded bit by bit. | |
| 183 | +struct Huffman { | |
| 184 | + /// Number of codes of each length, 1..=15. | |
| 185 | + counts: [u16; MAX_ALLOWED_CODE_LENGTH + 1], | |
| 186 | + /// Symbols ordered by (length, symbol). | |
| 187 | + symbols: Vec<u16>, | |
| 188 | + /// The one symbol, when the code is a single leaf that consumes no bits. | |
| 189 | + single: Option<u16>, | |
| 190 | +} | |
| 191 | + | |
| 192 | +impl Huffman { | |
| 193 | + fn from_lengths(lengths: &[u8]) -> Result<Huffman> { | |
| 194 | + let mut counts = [0u16; MAX_ALLOWED_CODE_LENGTH + 1]; | |
| 195 | + let mut used = 0; | |
| 196 | + let mut last = 0u16; | |
| 197 | + for (symbol, &len) in lengths.iter().enumerate() { | |
| 198 | + if len as usize > MAX_ALLOWED_CODE_LENGTH { | |
| 199 | + return Err(Error::corrupt(format!("VP8L: code length {len}"))); | |
| 200 | + } | |
| 201 | + if len > 0 { | |
| 202 | + counts[len as usize] += 1; | |
| 203 | + used += 1; | |
| 204 | + last = symbol as u16; | |
| 205 | + } | |
| 206 | + } | |
| 207 | + if used == 0 { | |
| 208 | + return Err(Error::corrupt("VP8L: prefix code with no symbols")); | |
| 209 | + } | |
| 210 | + if used == 1 { | |
| 211 | + return Ok(Huffman { | |
| 212 | + counts, | |
| 213 | + symbols: vec![last], | |
| 214 | + single: Some(last), | |
| 215 | + }); | |
| 216 | + } | |
| 217 | + // Kraft check: an over- or under-subscribed code is a corrupt stream, | |
| 218 | + // and an under-subscribed one would otherwise decode into a hole. | |
| 219 | + let mut left = 1i32; | |
| 220 | + for len in 1..=MAX_ALLOWED_CODE_LENGTH { | |
| 221 | + left <<= 1; | |
| 222 | + left -= i32::from(counts[len]); | |
| 223 | + if left < 0 { | |
| 224 | + return Err(Error::corrupt("VP8L: over-subscribed prefix code")); | |
| 225 | + } | |
| 226 | + } | |
| 227 | + if left != 0 { | |
| 228 | + return Err(Error::corrupt("VP8L: incomplete prefix code")); | |
| 229 | + } | |
| 230 | + // Symbols ordered by code length, then by symbol: exactly the order | |
| 231 | + // `decode` walks them in. | |
| 232 | + let mut offsets = [0usize; MAX_ALLOWED_CODE_LENGTH + 1]; | |
| 233 | + let mut total = 0usize; | |
| 234 | + for len in 1..=MAX_ALLOWED_CODE_LENGTH { | |
| 235 | + offsets[len] = total; | |
| 236 | + total += usize::from(counts[len]); | |
| 237 | + } | |
| 238 | + let mut symbols = vec![0u16; used]; | |
| 239 | + for (symbol, &len) in lengths.iter().enumerate() { | |
| 240 | + if len > 0 { | |
| 241 | + symbols[offsets[len as usize]] = symbol as u16; | |
| 242 | + offsets[len as usize] += 1; | |
| 243 | + } | |
| 244 | + } | |
| 245 | + Ok(Huffman { | |
| 246 | + counts, | |
| 247 | + symbols, | |
| 248 | + single: None, | |
| 249 | + }) | |
| 250 | + } | |
| 251 | + | |
| 252 | + fn decode(&self, bits: &mut BitReader<'_>) -> Result<u16> { | |
| 253 | + if let Some(symbol) = self.single { | |
| 254 | + return Ok(symbol); | |
| 255 | + } | |
| 256 | + let mut code = 0i32; | |
| 257 | + let mut first = 0i32; | |
| 258 | + let mut index = 0i32; | |
| 259 | + for len in 1..=MAX_ALLOWED_CODE_LENGTH { | |
| 260 | + code |= bits.read(1) as i32; | |
| 261 | + let count = i32::from(self.counts[len]); | |
| 262 | + if code - first < count { | |
| 263 | + let at = (index + code - first) as usize; | |
| 264 | + return self | |
| 265 | + .symbols | |
| 266 | + .get(at) | |
| 267 | + .copied() | |
| 268 | + .ok_or_else(|| Error::corrupt("VP8L: symbol outside its code")); | |
| 269 | + } | |
| 270 | + index += count; | |
| 271 | + first = (first + count) << 1; | |
| 272 | + code <<= 1; | |
| 273 | + } | |
| 274 | + Err(Error::corrupt("VP8L: no prefix code matches the bits")) | |
| 275 | + } | |
| 276 | +} | |
| 277 | + | |
| 278 | +/// One prefix code group: green+length+cache, red, blue, alpha, distance. | |
| 279 | +struct Group { | |
| 280 | + green: Huffman, | |
| 281 | + red: Huffman, | |
| 282 | + blue: Huffman, | |
| 283 | + alpha: Huffman, | |
| 284 | + distance: Huffman, | |
| 285 | +} | |
| 286 | + | |
| 287 | +/// A decoded lossless image: packed ARGB, one `u32` per pixel. | |
| 288 | +pub struct Argb { | |
| 289 | + /// Width in pixels. | |
| 290 | + pub width: u32, | |
| 291 | + /// Height in pixels. | |
| 292 | + pub height: u32, | |
| 293 | + /// `a << 24 | r << 16 | g << 8 | b`, scan-line order. | |
| 294 | + pub pixels: Vec<u32>, | |
| 295 | +} | |
| 296 | + | |
| 297 | +/// Decode a complete VP8L chunk, header and all. | |
| 298 | +pub fn decode(data: &[u8], limits: crate::Limits) -> Result<Argb> { | |
| 299 | + let mut bits = BitReader::new(data); | |
| 300 | + if bits.read(8) != 0x2f { | |
| 301 | + return Err(Error::corrupt("VP8L: missing 0x2f signature")); | |
| 302 | + } | |
| 303 | + let width = bits.read(14) + 1; | |
| 304 | + let height = bits.read(14) + 1; | |
| 305 | + let _alpha_is_used = bits.read(1); | |
| 306 | + let version = bits.read(3); | |
| 307 | + if version != 0 { | |
| 308 | + return Err(Error::corrupt(format!("VP8L: version {version}"))); | |
| 309 | + } | |
| 310 | + limits.check(width, height)?; | |
| 311 | + let pixels = decode_stream(&mut bits, width, height, true)?; | |
| 312 | + Ok(Argb { | |
| 313 | + width, | |
| 314 | + height, | |
| 315 | + pixels, | |
| 316 | + }) | |
| 317 | +} | |
| 318 | + | |
| 319 | +/// Decode a headerless VP8L stream of known dimensions — how an `ALPH` chunk | |
| 320 | +/// carries a lossless alpha plane, and how a colour table is stored. | |
| 321 | +pub fn decode_implicit(data: &[u8], width: u32, height: u32) -> Result<Vec<u32>> { | |
| 322 | + let mut bits = BitReader::new(data); | |
| 323 | + decode_stream(&mut bits, width, height, true) | |
| 324 | +} | |
| 325 | + | |
| 326 | +/// The image stream proper: transforms (when allowed), then entropy-coded data. | |
| 327 | +fn decode_stream( | |
| 328 | + bits: &mut BitReader<'_>, | |
| 329 | + width: u32, | |
| 330 | + height: u32, | |
| 331 | + transforms_allowed: bool, | |
| 332 | +) -> Result<Vec<u32>> { | |
| 333 | + let mut transforms: Vec<Transform> = Vec::new(); | |
| 334 | + let mut work_width = width; | |
| 335 | + if transforms_allowed { | |
| 336 | + let mut seen = [false; 4]; | |
| 337 | + while bits.read(1) == 1 { | |
| 338 | + let kind = bits.read(2) as usize; | |
| 339 | + if seen[kind] { | |
| 340 | + return Err(Error::corrupt("VP8L: transform used twice")); | |
| 341 | + } | |
| 342 | + seen[kind] = true; | |
| 343 | + let transform = read_transform(bits, kind, work_width, height)?; | |
| 344 | + if let Transform::ColorIndexing { width_bits, .. } = &transform { | |
| 345 | + work_width = work_width.div_ceil(1 << width_bits); | |
| 346 | + } | |
| 347 | + transforms.push(transform); | |
| 348 | + } | |
| 349 | + } | |
| 350 | + | |
| 351 | + let mut pixels = decode_entropy_coded(bits, work_width, height, true)?; | |
| 352 | + // Applied last-read-first, which is the inverse of the encoder's order. | |
| 353 | + for transform in transforms.iter().rev() { | |
| 354 | + pixels = apply_transform(transform, pixels, &mut work_width, height)?; | |
| 355 | + } | |
| 356 | + if work_width != width { | |
| 357 | + return Err(Error::corrupt("VP8L: transforms left the wrong width")); | |
| 358 | + } | |
| 359 | + Ok(pixels) | |
| 360 | +} | |
| 361 | + | |
| 362 | +/// A transform, with the data needed to invert it. | |
| 363 | +enum Transform { | |
| 364 | + Predictor { bits: u32, image: Vec<u32>, tw: u32 }, | |
| 365 | + Color { bits: u32, image: Vec<u32>, tw: u32 }, | |
| 366 | + SubtractGreen, | |
| 367 | + ColorIndexing { width_bits: u32, table: Vec<u32> }, | |
| 368 | +} | |
| 369 | + | |
| 370 | +fn read_transform( | |
| 371 | + bits: &mut BitReader<'_>, | |
| 372 | + kind: usize, | |
| 373 | + width: u32, | |
| 374 | + height: u32, | |
| 375 | +) -> Result<Transform> { | |
| 376 | + match kind { | |
| 377 | + 0 | 1 => { | |
| 378 | + let size_bits = bits.read(3) + 2; | |
| 379 | + let tw = width.div_ceil(1 << size_bits); | |
| 380 | + let th = height.div_ceil(1 << size_bits); | |
| 381 | + let image = decode_entropy_coded(bits, tw, th, false)?; | |
| 382 | + Ok(if kind == 0 { | |
| 383 | + Transform::Predictor { | |
| 384 | + bits: size_bits, | |
| 385 | + image, | |
| 386 | + tw, | |
| 387 | + } | |
| 388 | + } else { | |
| 389 | + Transform::Color { | |
| 390 | + bits: size_bits, | |
| 391 | + image, | |
| 392 | + tw, | |
| 393 | + } | |
| 394 | + }) | |
| 395 | + } | |
| 396 | + 2 => Ok(Transform::SubtractGreen), | |
| 397 | + _ => { | |
| 398 | + let size = bits.read(8) + 1; | |
| 399 | + let mut table = decode_entropy_coded(bits, size, 1, false)?; | |
| 400 | + // The table is stored as deltas between successive colours. | |
| 401 | + for i in 1..table.len() { | |
| 402 | + table[i] = add_argb(table[i], table[i - 1]); | |
| 403 | + } | |
| 404 | + let width_bits = match size { | |
| 405 | + 0..=2 => 3, | |
| 406 | + 3..=4 => 2, | |
| 407 | + 5..=16 => 1, | |
| 408 | + _ => 0, | |
| 409 | + }; | |
| 410 | + Ok(Transform::ColorIndexing { width_bits, table }) | |
| 411 | + } | |
| 412 | + } | |
| 413 | +} | |
| 414 | + | |
| 415 | +fn apply_transform( | |
| 416 | + transform: &Transform, | |
| 417 | + pixels: Vec<u32>, | |
| 418 | + width: &mut u32, | |
| 419 | + height: u32, | |
| 420 | +) -> Result<Vec<u32>> { | |
| 421 | + Ok(match transform { | |
| 422 | + Transform::SubtractGreen => pixels | |
| 423 | + .into_iter() | |
| 424 | + .map(|p| { | |
| 425 | + let g = (p >> 8) & 0xff; | |
| 426 | + let r = ((p >> 16) + g) & 0xff; | |
| 427 | + let b = (p + g) & 0xff; | |
| 428 | + (p & 0xff00_ff00) | (r << 16) | b | |
| 429 | + }) | |
| 430 | + .collect(), | |
| 431 | + Transform::Color { bits, image, tw } => { | |
| 432 | + let mut out = pixels; | |
| 433 | + for y in 0..height { | |
| 434 | + for x in 0..*width { | |
| 435 | + let block = (y >> bits) * tw + (x >> bits); | |
| 436 | + let element = image.get(block as usize).copied().unwrap_or(0); | |
| 437 | + let index = (y * *width + x) as usize; | |
| 438 | + out[index] = inverse_color(out[index], element); | |
| 439 | + } | |
| 440 | + } | |
| 441 | + out | |
| 442 | + } | |
| 443 | + Transform::Predictor { bits, image, tw } => { | |
| 444 | + inverse_predictor(pixels, *width, height, *bits, image, *tw) | |
| 445 | + } | |
| 446 | + Transform::ColorIndexing { width_bits, table } => { | |
| 447 | + let out_width = *width << width_bits; | |
| 448 | + let mut out = vec![0u32; (out_width as usize) * (height as usize)]; | |
| 449 | + let per_pixel = 1u32 << width_bits; | |
| 450 | + let bits_each = 8 >> width_bits; | |
| 451 | + let mask = (1u32 << bits_each) - 1; | |
| 452 | + for y in 0..height { | |
| 453 | + for x in 0..*width { | |
| 454 | + let packed = (pixels[(y * *width + x) as usize] >> 8) & 0xff; | |
| 455 | + for sub in 0..per_pixel { | |
| 456 | + let ox = x * per_pixel + sub; | |
| 457 | + if ox >= out_width { | |
| 458 | + break; | |
| 459 | + } | |
| 460 | + let index = if *width_bits == 0 { | |
| 461 | + packed | |
| 462 | + } else { | |
| 463 | + (packed >> (bits_each * sub)) & mask | |
| 464 | + }; | |
| 465 | + out[(y * out_width + ox) as usize] = | |
| 466 | + table.get(index as usize).copied().unwrap_or(0); | |
| 467 | + } | |
| 468 | + } | |
| 469 | + } | |
| 470 | + *width = out_width; | |
| 471 | + out | |
| 472 | + } | |
| 473 | + }) | |
| 474 | +} | |
| 475 | + | |
| 476 | +fn add_argb(a: u32, b: u32) -> u32 { | |
| 477 | + let mut out = 0u32; | |
| 478 | + for shift in [0, 8, 16, 24] { | |
| 479 | + let sum = (((a >> shift) & 0xff) + ((b >> shift) & 0xff)) & 0xff; | |
| 480 | + out |= sum << shift; | |
| 481 | + } | |
| 482 | + out | |
| 483 | +} | |
| 484 | + | |
| 485 | +fn inverse_color(pixel: u32, element: u32) -> u32 { | |
| 486 | + // The element carries green_to_red in blue, green_to_blue in green and | |
| 487 | + // red_to_blue in red, as the specification lays it out. | |
| 488 | + let green_to_red = (element & 0xff) as i8; | |
| 489 | + let green_to_blue = ((element >> 8) & 0xff) as i8; | |
| 490 | + let red_to_blue = ((element >> 16) & 0xff) as i8; | |
| 491 | + let green = ((pixel >> 8) & 0xff) as u8 as i8; | |
| 492 | + let mut red = ((pixel >> 16) & 0xff) as i32; | |
| 493 | + let mut blue = (pixel & 0xff) as i32; | |
| 494 | + red += delta(green_to_red, green); | |
| 495 | + blue += delta(green_to_blue, green); | |
| 496 | + blue += delta(red_to_blue, (red & 0xff) as u8 as i8); | |
| 497 | + (pixel & 0xff00_ff00) | (((red & 0xff) as u32) << 16) | ((blue & 0xff) as u32) | |
| 498 | +} | |
| 499 | + | |
| 500 | +/// `(t * c) >> 5` in the specification's 3.5 fixed point. | |
| 501 | +fn delta(t: i8, c: i8) -> i32 { | |
| 502 | + (i32::from(t) * i32::from(c)) >> 5 | |
| 503 | +} | |
| 504 | + | |
| 505 | +fn inverse_predictor( | |
| 506 | + mut pixels: Vec<u32>, | |
| 507 | + width: u32, | |
| 508 | + height: u32, | |
| 509 | + size_bits: u32, | |
| 510 | + image: &[u32], | |
| 511 | + tw: u32, | |
| 512 | +) -> Vec<u32> { | |
| 513 | + let w = width as usize; | |
| 514 | + for y in 0..height as usize { | |
| 515 | + for x in 0..w { | |
| 516 | + let index = y * w + x; | |
| 517 | + let pred = if x == 0 && y == 0 { | |
| 518 | + 0xff00_0000 | |
| 519 | + } else if y == 0 { | |
| 520 | + pixels[index - 1] | |
| 521 | + } else if x == 0 { | |
| 522 | + pixels[index - w] | |
| 523 | + } else { | |
| 524 | + let block = ((y as u32) >> size_bits) * tw + ((x as u32) >> size_bits); | |
| 525 | + let mode = image.get(block as usize).map_or(0, |p| (p >> 8) & 0xff); | |
| 526 | + let left = pixels[index - 1]; | |
| 527 | + let top = pixels[index - w]; | |
| 528 | + let top_left = pixels[index - w - 1]; | |
| 529 | + // The rightmost column has no top-right; the leftmost pixel of | |
| 530 | + // the same row stands in, as the specification requires. | |
| 531 | + let top_right = if x + 1 == w { | |
| 532 | + pixels[y * w] | |
| 533 | + } else { | |
| 534 | + pixels[index - w + 1] | |
| 535 | + }; | |
| 536 | + predict(mode, left, top, top_left, top_right) | |
| 537 | + }; | |
| 538 | + pixels[index] = add_argb(pixels[index], pred); | |
| 539 | + } | |
| 540 | + } | |
| 541 | + pixels | |
| 542 | +} | |
| 543 | + | |
| 544 | +fn predict(mode: u32, l: u32, t: u32, tl: u32, tr: u32) -> u32 { | |
| 545 | + match mode { | |
| 546 | + 0 => 0xff00_0000, | |
| 547 | + 1 => l, | |
| 548 | + 2 => t, | |
| 549 | + 3 => tr, | |
| 550 | + 4 => tl, | |
| 551 | + 5 => average2(average2(l, tr), t), | |
| 552 | + 6 => average2(l, tl), | |
| 553 | + 7 => average2(l, t), | |
| 554 | + 8 => average2(tl, t), | |
| 555 | + 9 => average2(t, tr), | |
| 556 | + 10 => average2(average2(l, tl), average2(t, tr)), | |
| 557 | + 11 => select(l, t, tl), | |
| 558 | + 12 => clamp_add_subtract_full(l, t, tl), | |
| 559 | + 13 => clamp_add_subtract_half(average2(l, t), tl), | |
| 560 | + // Modes past 13 do not exist; a corrupt predictor image gets black | |
| 561 | + // rather than an out-of-range panic. | |
| 562 | + _ => 0xff00_0000, | |
| 563 | + } | |
| 564 | +} | |
| 565 | + | |
| 566 | +fn average2(a: u32, b: u32) -> u32 { | |
| 567 | + let mut out = 0u32; | |
| 568 | + for shift in [0, 8, 16, 24] { | |
| 569 | + let v = (((a >> shift) & 0xff) + ((b >> shift) & 0xff)) / 2; | |
| 570 | + out |= v << shift; | |
| 571 | + } | |
| 572 | + out | |
| 573 | +} | |
| 574 | + | |
| 575 | +fn select(l: u32, t: u32, tl: u32) -> u32 { | |
| 576 | + let mut pl = 0i32; | |
| 577 | + let mut pt = 0i32; | |
| 578 | + for shift in [0, 8, 16, 24] { | |
| 579 | + let (a, b, c) = ( | |
| 580 | + ((l >> shift) & 0xff) as i32, | |
| 581 | + ((t >> shift) & 0xff) as i32, | |
| 582 | + ((tl >> shift) & 0xff) as i32, | |
| 583 | + ); | |
| 584 | + let p = a + b - c; | |
| 585 | + pl += (p - a).abs(); | |
| 586 | + pt += (p - b).abs(); | |
| 587 | + } | |
| 588 | + if pl < pt { l } else { t } | |
| 589 | +} | |
| 590 | + | |
| 591 | +fn clamp_add_subtract_full(a: u32, b: u32, c: u32) -> u32 { | |
| 592 | + let mut out = 0u32; | |
| 593 | + for shift in [0, 8, 16, 24] { | |
| 594 | + let v = (((a >> shift) & 0xff) as i32 + ((b >> shift) & 0xff) as i32 | |
| 595 | + - ((c >> shift) & 0xff) as i32) | |
| 596 | + .clamp(0, 255) as u32; | |
| 597 | + out |= v << shift; | |
| 598 | + } | |
| 599 | + out | |
| 600 | +} | |
| 601 | + | |
| 602 | +fn clamp_add_subtract_half(a: u32, b: u32) -> u32 { | |
| 603 | + let mut out = 0u32; | |
| 604 | + for shift in [0, 8, 16, 24] { | |
| 605 | + let (x, y) = (((a >> shift) & 0xff) as i32, ((b >> shift) & 0xff) as i32); | |
| 606 | + let v = (x + (x - y) / 2).clamp(0, 255) as u32; | |
| 607 | + out |= v << shift; | |
| 608 | + } | |
| 609 | + out | |
| 610 | +} | |
| 611 | + | |
| 612 | +/// Read a prefix code: either the two-symbol shorthand or full code lengths. | |
| 613 | +fn read_code(bits: &mut BitReader<'_>, alphabet: usize) -> Result<Huffman> { | |
| 614 | + let mut lengths = vec![0u8; alphabet]; | |
| 615 | + if bits.read(1) == 1 { | |
| 616 | + // Simple code: one or two symbols, each one bit long. | |
| 617 | + let count = bits.read(1) + 1; | |
| 618 | + let first_is_byte = bits.read(1) == 1; | |
| 619 | + let symbol0 = bits.read(if first_is_byte { 8 } else { 1 }) as usize; | |
| 620 | + if symbol0 >= alphabet { | |
| 621 | + return Err(Error::corrupt("VP8L: simple code symbol past the alphabet")); | |
| 622 | + } | |
| 623 | + lengths[symbol0] = 1; | |
| 624 | + if count == 2 { | |
| 625 | + let symbol1 = bits.read(8) as usize; | |
| 626 | + if symbol1 >= alphabet { | |
| 627 | + return Err(Error::corrupt("VP8L: simple code symbol past the alphabet")); | |
| 628 | + } | |
| 629 | + lengths[symbol1] = 1; | |
| 630 | + } | |
| 631 | + // One symbol of length 1 is a legal single-leaf code, so build from | |
| 632 | + // the lengths rather than insisting the Kraft sum be exactly one. | |
| 633 | + return Huffman::from_lengths(&lengths); | |
| 634 | + } | |
| 635 | + | |
| 636 | + let num_lengths = 4 + bits.read(4) as usize; | |
| 637 | + let mut code_length_lengths = [0u8; 19]; | |
| 638 | + for i in 0..num_lengths { | |
| 639 | + code_length_lengths[CODE_LENGTH_ORDER[i]] = bits.read(3) as u8; | |
| 640 | + } | |
| 641 | + let code_length_code = Huffman::from_lengths(&code_length_lengths)?; | |
| 642 | + | |
| 643 | + let mut max_symbol = if bits.read(1) == 1 { | |
| 644 | + let length_bits = 2 + 2 * bits.read(3); | |
| 645 | + let max = 2 + bits.read(length_bits) as usize; | |
| 646 | + if max > alphabet { | |
| 647 | + return Err(Error::corrupt("VP8L: max_symbol past the alphabet")); | |
| 648 | + } | |
| 649 | + max | |
| 650 | + } else { | |
| 651 | + alphabet | |
| 652 | + }; | |
| 653 | + | |
| 654 | + let mut previous = 8u8; | |
| 655 | + let mut index = 0usize; | |
| 656 | + while index < alphabet { | |
| 657 | + if max_symbol == 0 { | |
| 658 | + break; | |
| 659 | + } | |
| 660 | + max_symbol -= 1; | |
| 661 | + if bits.exhausted() { | |
| 662 | + return Err(Error::corrupt("VP8L: truncated code lengths")); | |
| 663 | + } | |
| 664 | + let symbol = code_length_code.decode(bits)?; | |
| 665 | + match symbol { | |
| 666 | + 0..=15 => { | |
| 667 | + lengths[index] = symbol as u8; | |
| 668 | + index += 1; | |
| 669 | + if symbol != 0 { | |
| 670 | + previous = symbol as u8; | |
| 671 | + } | |
| 672 | + } | |
| 673 | + 16 => { | |
| 674 | + let repeat = 3 + bits.read(2) as usize; | |
| 675 | + for _ in 0..repeat.min(alphabet - index) { | |
| 676 | + lengths[index] = previous; | |
| 677 | + index += 1; | |
| 678 | + } | |
| 679 | + } | |
| 680 | + 17 => index += (3 + bits.read(3) as usize).min(alphabet - index), | |
| 681 | + 18 => index += (11 + bits.read(7) as usize).min(alphabet - index), | |
| 682 | + other => return Err(Error::corrupt(format!("VP8L: code length symbol {other}"))), | |
| 683 | + } | |
| 684 | + } | |
| 685 | + Huffman::from_lengths(&lengths) | |
| 686 | +} | |
| 687 | + | |
| 688 | +/// Read the five prefix codes of one group. | |
| 689 | +fn read_group(bits: &mut BitReader<'_>, cache_bits: u32) -> Result<Group> { | |
| 690 | + let green_alphabet = 256 + GREEN_EXTRA + if cache_bits > 0 { 1 << cache_bits } else { 0 }; | |
| 691 | + Ok(Group { | |
| 692 | + green: read_code(bits, green_alphabet)?, | |
| 693 | + red: read_code(bits, 256)?, | |
| 694 | + blue: read_code(bits, 256)?, | |
| 695 | + alpha: read_code(bits, 256)?, | |
| 696 | + distance: read_code(bits, 40)?, | |
| 697 | + }) | |
| 698 | +} | |
| 699 | + | |
| 700 | +/// Length or distance from a prefix code plus its extra bits. | |
| 701 | +fn prefix_value(bits: &mut BitReader<'_>, code: u32) -> u32 { | |
| 702 | + if code < 4 { | |
| 703 | + return code + 1; | |
| 704 | + } | |
| 705 | + let extra = (code - 2) >> 1; | |
| 706 | + let offset = (2 + (code & 1)) << extra; | |
| 707 | + offset + bits.read(extra) + 1 | |
| 708 | +} | |
| 709 | + | |
| 710 | +/// Decode an entropy-coded image: the ARGB image itself, or one of the | |
| 711 | +/// sub-resolution images a transform or the meta prefix uses. | |
| 712 | +fn decode_entropy_coded( | |
| 713 | + bits: &mut BitReader<'_>, | |
| 714 | + width: u32, | |
| 715 | + height: u32, | |
| 716 | + meta_allowed: bool, | |
| 717 | +) -> Result<Vec<u32>> { | |
| 718 | + let count = (width as usize) | |
| 719 | + .checked_mul(height as usize) | |
| 720 | + .ok_or_else(|| Error::corrupt("VP8L: image geometry overflows"))?; | |
| 721 | + | |
| 722 | + // Order matters and is easy to get backwards: the colour cache size comes | |
| 723 | + // first, then the meta prefix codes, then the prefix codes themselves. | |
| 724 | + let cache_bits = if bits.read(1) == 1 { | |
| 725 | + let n = bits.read(4); | |
| 726 | + if !(1..=11).contains(&n) { | |
| 727 | + return Err(Error::corrupt(format!("VP8L: colour cache bits {n}"))); | |
| 728 | + } | |
| 729 | + n | |
| 730 | + } else { | |
| 731 | + 0 | |
| 732 | + }; | |
| 733 | + | |
| 734 | + let mut entropy_image: Vec<u32> = Vec::new(); | |
| 735 | + let mut prefix_bits = 0u32; | |
| 736 | + let mut prefix_width = 0u32; | |
| 737 | + let mut groups = 1usize; | |
| 738 | + if meta_allowed && bits.read(1) == 1 { | |
| 739 | + prefix_bits = bits.read(3) + 2; | |
| 740 | + prefix_width = width.div_ceil(1 << prefix_bits); | |
| 741 | + let prefix_height = height.div_ceil(1 << prefix_bits); | |
| 742 | + entropy_image = decode_entropy_coded(bits, prefix_width, prefix_height, false)?; | |
| 743 | + groups = entropy_image | |
| 744 | + .iter() | |
| 745 | + .map(|p| (((p >> 8) & 0xffff) as usize) + 1) | |
| 746 | + .max() | |
| 747 | + .unwrap_or(1); | |
| 748 | + if groups > 1 << 16 { | |
| 749 | + return Err(Error::corrupt("VP8L: too many prefix code groups")); | |
| 750 | + } | |
| 751 | + } | |
| 752 | + | |
| 753 | + let mut code_groups = Vec::with_capacity(groups); | |
| 754 | + for _ in 0..groups { | |
| 755 | + code_groups.push(read_group(bits, cache_bits)?); | |
| 756 | + if bits.exhausted() { | |
| 757 | + return Err(Error::corrupt("VP8L: truncated prefix codes")); | |
| 758 | + } | |
| 759 | + } | |
| 760 | + | |
| 761 | + let mut cache = vec![0u32; if cache_bits > 0 { 1 << cache_bits } else { 0 }]; | |
| 762 | + let mut pixels = vec![0u32; count]; | |
| 763 | + let mut at = 0usize; | |
| 764 | + while at < count { | |
| 765 | + if bits.exhausted() { | |
| 766 | + return Err(Error::corrupt("VP8L: truncated image data")); | |
| 767 | + } | |
| 768 | + let group = if entropy_image.is_empty() { | |
| 769 | + &code_groups[0] | |
| 770 | + } else { | |
| 771 | + let x = (at % width as usize) as u32; | |
| 772 | + let y = (at / width as usize) as u32; | |
| 773 | + let block = (y >> prefix_bits) * prefix_width + (x >> prefix_bits); | |
| 774 | + let meta = entropy_image | |
| 775 | + .get(block as usize) | |
| 776 | + .map_or(0, |p| ((p >> 8) & 0xffff) as usize); | |
| 777 | + code_groups | |
| 778 | + .get(meta) | |
| 779 | + .ok_or_else(|| Error::corrupt("VP8L: meta prefix code past its group list"))? | |
| 780 | + }; | |
| 781 | + let symbol = u32::from(group.green.decode(bits)?); | |
| 782 | + if symbol < 256 { | |
| 783 | + let red = u32::from(group.red.decode(bits)?); | |
| 784 | + let blue = u32::from(group.blue.decode(bits)?); | |
| 785 | + let alpha = u32::from(group.alpha.decode(bits)?); | |
| 786 | + let pixel = (alpha << 24) | (red << 16) | (symbol << 8) | blue; | |
| 787 | + pixels[at] = pixel; | |
| 788 | + if cache_bits > 0 { | |
| 789 | + cache[cache_index(pixel, cache_bits)] = pixel; | |
| 790 | + } | |
| 791 | + at += 1; | |
| 792 | + } else if symbol < 256 + GREEN_EXTRA as u32 { | |
| 793 | + let length = prefix_value(bits, symbol - 256) as usize; | |
| 794 | + let distance_code = u32::from(group.distance.decode(bits)?); | |
| 795 | + let distance = prefix_value(bits, distance_code) as usize; | |
| 796 | + let distance = map_distance(distance, width); | |
| 797 | + if distance > at || length > count - at { | |
| 798 | + return Err(Error::corrupt("VP8L: backward reference outside the image")); | |
| 799 | + } | |
| 800 | + for i in 0..length { | |
| 801 | + let pixel = pixels[at - distance + i]; | |
| 802 | + pixels[at + i] = pixel; | |
| 803 | + if cache_bits > 0 { | |
| 804 | + cache[cache_index(pixel, cache_bits)] = pixel; | |
| 805 | + } | |
| 806 | + } | |
| 807 | + at += length; | |
| 808 | + } else { | |
| 809 | + let index = (symbol - 256 - GREEN_EXTRA as u32) as usize; | |
| 810 | + let pixel = *cache | |
| 811 | + .get(index) | |
| 812 | + .ok_or_else(|| Error::corrupt("VP8L: colour cache index out of range"))?; | |
| 813 | + pixels[at] = pixel; | |
| 814 | + at += 1; | |
| 815 | + } | |
| 816 | + } | |
| 817 | + Ok(pixels) | |
| 818 | +} | |
| 819 | + | |
| 820 | +fn cache_index(pixel: u32, cache_bits: u32) -> usize { | |
| 821 | + ((0x1e35_a7bd_u32.wrapping_mul(pixel)) >> (32 - cache_bits)) as usize | |
| 822 | +} | |
| 823 | + | |
| 824 | +/// Distance codes 1..=120 name a nearby pixel; anything larger is a plain | |
| 825 | +/// scan-line distance offset by 120. | |
| 826 | +fn map_distance(code: usize, width: u32) -> usize { | |
| 827 | + if code > 120 { | |
| 828 | + return code - 120; | |
| 829 | + } | |
| 830 | + let (xi, yi) = DISTANCE_MAP[code - 1]; | |
| 831 | + let distance = yi * width as i32 + xi; | |
| 832 | + distance.max(1) as usize | |
| 833 | +} | |
| 834 | + | |
| 835 | +#[cfg(test)] | |
| 836 | +mod tests { | |
| 837 | + use super::*; | |
| 838 | + | |
| 839 | + #[test] | |
| 840 | + fn bits_come_out_low_bit_first() { | |
| 841 | + let mut bits = BitReader::new(&[0b1010_0110, 0xff]); | |
| 842 | + assert_eq!(bits.read(1), 0); | |
| 843 | + assert_eq!(bits.read(2), 0b11); | |
| 844 | + assert_eq!(bits.read(5), 0b1_0100); | |
| 845 | + assert_eq!(bits.read(8), 0xff); | |
| 846 | + assert!(!bits.exhausted()); | |
| 847 | + bits.read(1); | |
| 848 | + assert!(bits.exhausted()); | |
| 849 | + } | |
| 850 | + | |
| 851 | + #[test] | |
| 852 | + fn a_canonical_code_decodes_its_own_symbols() { | |
| 853 | + // Lengths 1,2,3,3 -> codes 0, 10, 110, 111. | |
| 854 | + let code = Huffman::from_lengths(&[1, 2, 3, 3]).unwrap(); | |
| 855 | + let mut bits = BitReader::new(&[0b1101_1100, 0b0000_0001]); | |
| 856 | + // Bits low-first: 0,0,1,1,1,0,1,1 -> symbol 0, then 110 -> 2 ... | |
| 857 | + assert_eq!(code.decode(&mut bits).unwrap(), 0); | |
| 858 | + assert_eq!(code.decode(&mut bits).unwrap(), 0); | |
| 859 | + assert_eq!(code.decode(&mut bits).unwrap(), 3); | |
| 860 | + } | |
| 861 | + | |
| 862 | + #[test] | |
| 863 | + fn an_incomplete_code_is_refused() { | |
| 864 | + assert!(Huffman::from_lengths(&[1, 2, 3]).is_err()); | |
| 865 | + assert!(Huffman::from_lengths(&[1, 1, 1, 1]).is_err()); | |
| 866 | + assert!(Huffman::from_lengths(&[0, 0]).is_err()); | |
| 867 | + // A single leaf is legal and consumes no bits. | |
| 868 | + let single = Huffman::from_lengths(&[0, 1, 0]).unwrap(); | |
| 869 | + let mut bits = BitReader::new(&[]); | |
| 870 | + assert_eq!(single.decode(&mut bits).unwrap(), 1); | |
| 871 | + } | |
| 872 | + | |
| 873 | + #[test] | |
| 874 | + fn distance_codes_map_into_the_neighbourhood() { | |
| 875 | + // Code 1 is the pixel directly above; code 2 the one to the left. | |
| 876 | + assert_eq!(map_distance(1, 16), 16); | |
| 877 | + assert_eq!(map_distance(2, 16), 1); | |
| 878 | + assert_eq!(map_distance(121, 16), 1); | |
| 879 | + // Every mapped distance must be at least one pixel back. | |
| 880 | + for code in 1..=120 { | |
| 881 | + assert!(map_distance(code, 4) >= 1, "code {code}"); | |
| 882 | + } | |
| 883 | + } | |
| 884 | + | |
| 885 | + #[test] | |
| 886 | + fn the_predictors_agree_with_their_definitions() { | |
| 887 | + let l = 0xff20_4060; | |
| 888 | + let t = 0xff40_6080; | |
| 889 | + let tl = 0xff10_2030; | |
| 890 | + assert_eq!(predict(1, l, t, tl, 0), l); | |
| 891 | + assert_eq!(predict(2, l, t, tl, 0), t); | |
| 892 | + assert_eq!(predict(7, l, t, tl, 0), 0xff30_5070); | |
| 893 | + assert_eq!(predict(12, l, t, tl, 0), clamp_add_subtract_full(l, t, tl)); | |
| 894 | + assert_eq!(predict(99, l, t, tl, 0), 0xff00_0000); | |
| 895 | + } | |
| 896 | +} |
crates/ec-pgs/src/lib.rsmodified+24 -14
| @@ -386,17 +386,24 @@ pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> { | ||
| 386 | 386 | Ok(Box::new(PgsDecoder::new())) |
| 387 | 387 | } |
| 388 | 388 | |
| 389 | -/// One palette entry: BT.601 limited-range Y'CbCr with straight alpha, the way | |
| 390 | -/// a disc writes it, into RGBA. | |
| 389 | +/// One palette entry: BT.601 Y'CbCr with straight alpha, the way a disc writes | |
| 390 | +/// it, into RGBA. | |
| 391 | +/// | |
| 392 | +/// The luma is taken at its own scale — `Y' = 235` comes out 235, not the 255 | |
| 393 | +/// an expansion of the 16..235 video range would give. That is not a reading of | |
| 394 | +/// the Blu-ray spec but a measurement of what every player draws: ffmpeg's own | |
| 395 | +/// `pgssub` decoder, burning `fixtures/subs/pgs-1080p.sup` over black, tops out | |
| 396 | +/// at 235 (`scripts/pgs-white-level.sh`), and a subtitle that is brighter than | |
| 397 | +/// the one the disc is mastered against is our bug, not the world's. | |
| 391 | 398 | fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] { |
| 392 | - let y = 298 * (i32::from(y) - 16); | |
| 399 | + let y = i32::from(y) << 8; | |
| 393 | 400 | let cb = i32::from(cb) - 128; |
| 394 | 401 | let cr = i32::from(cr) - 128; |
| 395 | 402 | let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8; |
| 396 | 403 | [ |
| 397 | - clamp(y + 409 * cr), | |
| 398 | - clamp(y - 100 * cb - 208 * cr), | |
| 399 | - clamp(y + 516 * cb), | |
| 404 | + clamp(y + 359 * cr), | |
| 405 | + clamp(y - 88 * cb - 183 * cr), | |
| 406 | + clamp(y + 454 * cb), | |
| 400 | 407 | alpha, |
| 401 | 408 | ] |
| 402 | 409 | } |
| @@ -515,10 +522,11 @@ mod tests { | ||
| 515 | 522 | // Outside the object: nothing painted at all. |
| 516 | 523 | assert_eq!(pixel(0, 0), [0, 0, 0, 0]); |
| 517 | 524 | assert_eq!(pixel(1, 1), [0, 0, 0, 0]); |
| 518 | - // Row 1 of the object is white, row 2 is black, both opaque. | |
| 519 | - assert_eq!(pixel(2, 1), [255, 255, 255, 255]); | |
| 520 | - assert_eq!(pixel(9, 1), [255, 255, 255, 255]); | |
| 521 | - assert_eq!(pixel(2, 2), [0, 0, 0, 255]); | |
| 525 | + // Row 1 of the object is white, row 2 is black, both opaque. White is | |
| 526 | + // the palette's own `Y' = 235`, black its `Y' = 16` — see [`rgba`]. | |
| 527 | + assert_eq!(pixel(2, 1), [235, 235, 235, 255]); | |
| 528 | + assert_eq!(pixel(9, 1), [235, 235, 235, 255]); | |
| 529 | + assert_eq!(pixel(2, 2), [16, 16, 16, 255]); | |
| 522 | 530 | // Past the object's width again. |
| 523 | 531 | assert_eq!(pixel(10, 1), [0, 0, 0, 0]); |
| 524 | 532 | assert!(decoder.take_frame().is_none()); |
| @@ -567,10 +575,12 @@ mod tests { | ||
| 567 | 575 | } |
| 568 | 576 | |
| 569 | 577 | #[test] |
| 570 | - fn palette_entries_are_bt601_limited_range() { | |
| 571 | - // Y=235 is white, Y=16 is black, and alpha rides through untouched. | |
| 572 | - assert_eq!(rgba(235, 128, 128, 255), [255, 255, 255, 255]); | |
| 573 | - assert_eq!(rgba(16, 128, 128, 128), [0, 0, 0, 128]); | |
| 578 | + fn palette_entries_convert_at_their_own_luma_scale() { | |
| 579 | + // A disc's white and black land where ffmpeg's PGS decoder puts them — | |
| 580 | + // 235 and 16, not an expansion to 255 and 0 — and alpha rides through | |
| 581 | + // untouched. | |
| 582 | + assert_eq!(rgba(235, 128, 128, 255), [235, 235, 235, 255]); | |
| 583 | + assert_eq!(rgba(16, 128, 128, 128), [16, 16, 16, 128]); | |
| 574 | 584 | // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601. |
| 575 | 585 | let red = rgba(81, 240, 90, 255); |
| 576 | 586 | assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}"); |
scripts/pgs-white-level.shadded+38 -0
| @@ -0,0 +1,38 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# What a player draws a PGS subtitle's white as, measured rather than reasoned: | |
| 3 | +# ffmpeg burns fixtures/subs/pgs-1080p.sup over black and the brightest red | |
| 4 | +# channel in the first painted frame is printed. It is 235 -- the palette's own | |
| 5 | +# Y', not an expansion of the 16..235 video range to 255 -- which is what | |
| 6 | +# `ec_pgs::rgba` matches. | |
| 7 | +# | |
| 8 | +# scripts/pgs-white-level.sh [file.sup] | |
| 9 | +set -euo pipefail | |
| 10 | + | |
| 11 | +sup="${1:-$(dirname "$0")/../fixtures/subs/pgs-1080p.sup}" | |
| 12 | +[ -r "$sup" ] || { echo "no such .sup: $sup (fixtures are gitignored)" >&2; exit 1; } | |
| 13 | + | |
| 14 | +size=$(ffprobe -v error -select_streams s:0 -show_entries stream=width,height \ | |
| 15 | + -of csv=p=0:s=x "$sup") | |
| 16 | +raw=$(mktemp -t pgs-white.XXXXXX) | |
| 17 | +trap 'rm -f "$raw"' EXIT | |
| 18 | + | |
| 19 | +ffmpeg -v error -f lavfi -i "color=c=black:s=$size:r=1:d=60,format=rgba" -i "$sup" \ | |
| 20 | + -filter_complex "[0:v][1:s]overlay=format=rgb" -frames:v 60 \ | |
| 21 | + -pix_fmt rgba -f rawvideo -y "$raw" | |
| 22 | + | |
| 23 | +python3 - "$raw" "$size" <<'PY' | |
| 24 | +import sys | |
| 25 | +data = open(sys.argv[1], 'rb').read() | |
| 26 | +w, h = (int(v) for v in sys.argv[2].split('x')) | |
| 27 | +frame = w * h * 4 | |
| 28 | +for i in range(len(data) // frame): | |
| 29 | + reds = data[i * frame:(i + 1) * frame:4] | |
| 30 | + peak = max(reds) | |
| 31 | + if peak: | |
| 32 | + print(f"frame {i}: brightest red {peak}, " | |
| 33 | + f"{sum(1 for v in reds if v)} pixels drawn on") | |
| 34 | + break | |
| 35 | +else: | |
| 36 | + print("nothing painted in any frame", file=sys.stderr) | |
| 37 | + sys.exit(1) | |
| 38 | +PY |
shims/oxideav-ac3/src/lib.rsadded+129 -0
| @@ -0,0 +1,129 @@ | ||
| 1 | +//! `oxideav-ac3` as edith consumes it, over [`ec_ac3`]. | |
| 2 | +//! | |
| 3 | +//! A shim, not a port: it carries the incumbent's package name and version so | |
| 4 | +//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the | |
| 5 | +//! replica names — the header surface it reads a track's rate and layout out of | |
| 6 | +//! ([`syncinfo::parse`], [`bsi::parse`], [`eac3::bsi::parse`], `audio.rs:1954`, | |
| 7 | +//! `2063`) and [`register_codecs`], which is how it gets a decoder at all | |
| 8 | +//! (`audio.rs:2132`). The header modules are `ec_ac3`'s own: their signatures, | |
| 9 | +//! their entry offsets (`bsi` after the five `syncinfo()` bytes, `eac3::bsi` | |
| 10 | +//! after the 16-bit sync word) and their fields already match what the replica | |
| 11 | +//! writes, so a re-export is the whole adapter. | |
| 12 | +//! | |
| 13 | +//! Two differences are owned here rather than at the call site: | |
| 14 | +//! | |
| 15 | +//! * **Sample format.** The incumbent hands out S16 little-endian and the | |
| 16 | +//! replica reads it as such (`audio.rs:2160`, `chunks_exact(2)` over | |
| 17 | +//! `/32768.0`); `ec_ac3` decodes to `f32`. The conversion is | |
| 18 | +//! [`Ac3Decoder::receive_frame`], once, for every caller — which is why this | |
| 19 | +//! shim writes its own [`oxideav_core::Decoder`] instead of wrapping | |
| 20 | +//! `oxideav_core::EcDecoder`, whose job is the frames that need no | |
| 21 | +//! conversion. | |
| 22 | +//! * **Downmix request.** The incumbent takes the wanted channel count on | |
| 23 | +//! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the | |
| 24 | +//! factory translates. `Some(2)` is the A/52 §7.8 stereo fold the replica | |
| 25 | +//! asks for on anything wider than mono, `None` the stream's own layout. | |
| 26 | + | |
| 27 | +#![forbid(unsafe_code)] | |
| 28 | + | |
| 29 | +pub use ec_ac3::{bsi, eac3, syncinfo}; | |
| 30 | + | |
| 31 | +use ec_ac3::{Downmix, Options}; | |
| 32 | +use oxideav_core::{ | |
| 33 | + AudioFrame, CodecId, CodecInfo, CodecParameters, CodecRegistry, Decoder, Frame, Packet, Result, | |
| 34 | +}; | |
| 35 | + | |
| 36 | +/// Register this crate's codecs — `ac3` and `eac3` — into `registry`. | |
| 37 | +/// | |
| 38 | +/// Both ids reach the same decoder: it dispatches per packet on `bsid`, so the | |
| 39 | +/// id picks the capability set and not the syntax. | |
| 40 | +pub fn register_codecs(registry: &mut CodecRegistry) { | |
| 41 | + for id in ["ac3", "eac3"] { | |
| 42 | + registry.register(CodecInfo::new(CodecId::new(id)).decoder(open)); | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// A decoder for `params`, folded down to `params.channels`. | |
| 47 | +fn open(params: &CodecParameters) -> Result<Box<dyn Decoder>> { | |
| 48 | + let options = Options { | |
| 49 | + downmix: match params.channels { | |
| 50 | + Some(1) => Downmix::Mono, | |
| 51 | + Some(2) => Downmix::Stereo, | |
| 52 | + _ => Downmix::Native, | |
| 53 | + }, | |
| 54 | + ..Options::default() | |
| 55 | + }; | |
| 56 | + Ok(Box::new(Ac3Decoder { | |
| 57 | + id: params.codec_id.clone(), | |
| 58 | + inner: ec_ac3::Ac3Decoder::with_options(options), | |
| 59 | + })) | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// The family's AC-3 decoder: one syncframe in, one S16 little-endian frame | |
| 63 | +/// out. | |
| 64 | +struct Ac3Decoder { | |
| 65 | + id: CodecId, | |
| 66 | + inner: ec_ac3::Ac3Decoder, | |
| 67 | +} | |
| 68 | + | |
| 69 | +impl Decoder for Ac3Decoder { | |
| 70 | + fn codec_id(&self) -> &CodecId { | |
| 71 | + &self.id | |
| 72 | + } | |
| 73 | + | |
| 74 | + fn send_packet(&mut self, packet: &Packet) -> Result<()> { | |
| 75 | + Ok(ec_core::Decoder::send_packet(&mut self.inner, packet)?) | |
| 76 | + } | |
| 77 | + | |
| 78 | + fn receive_frame(&mut self) -> Result<Frame> { | |
| 79 | + match ec_core::Decoder::receive_frame(&mut self.inner)? { | |
| 80 | + ec_core::Frame::Audio(audio) => Ok(Frame::Audio(AudioFrame { | |
| 81 | + samples: audio.samples as u32, | |
| 82 | + pts: audio.pts.map(|ts| ts.ticks), | |
| 83 | + data: audio.data.iter().map(|plane| s16le(plane)).collect(), | |
| 84 | + })), | |
| 85 | + other => Ok(other.into()), | |
| 86 | + } | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +/// Interleaved `f32` bytes as S16 little-endian, which is what the incumbent | |
| 91 | +/// speaks. Full scale is 32768 in both directions, saturating: the replica's | |
| 92 | +/// inverse is `/32768.0`, and a sample at or past `+1.0` has to land on | |
| 93 | +/// `i16::MAX` rather than wrap to silence. | |
| 94 | +fn s16le(samples: &[u8]) -> Vec<u8> { | |
| 95 | + let mut out = Vec::with_capacity(samples.len() / 2); | |
| 96 | + for chunk in samples.chunks_exact(4) { | |
| 97 | + let v = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); | |
| 98 | + let scaled = (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16; | |
| 99 | + out.extend_from_slice(&scaled.to_le_bytes()); | |
| 100 | + } | |
| 101 | + out | |
| 102 | +} | |
| 103 | + | |
| 104 | +#[cfg(test)] | |
| 105 | +mod tests { | |
| 106 | + use super::*; | |
| 107 | + | |
| 108 | + #[test] | |
| 109 | + fn full_scale_saturates_instead_of_wrapping() { | |
| 110 | + let pcm: Vec<u8> = [-1.5f32, -1.0, 0.0, 0.5, 1.0, 1.5] | |
| 111 | + .iter() | |
| 112 | + .flat_map(|v| v.to_le_bytes()) | |
| 113 | + .collect(); | |
| 114 | + let got: Vec<i16> = s16le(&pcm) | |
| 115 | + .chunks_exact(2) | |
| 116 | + .map(|s| i16::from_le_bytes([s[0], s[1]])) | |
| 117 | + .collect(); | |
| 118 | + assert_eq!(got, [-32768, -32768, 0, 16384, 32767, 32767]); | |
| 119 | + } | |
| 120 | + | |
| 121 | + #[test] | |
| 122 | + fn both_ids_are_registered_and_a_third_is_not() { | |
| 123 | + let mut registry = CodecRegistry::new(); | |
| 124 | + register_codecs(&mut registry); | |
| 125 | + assert!(registry.has_decoder(&CodecId::new("ac3"))); | |
| 126 | + assert!(registry.has_decoder(&CodecId::new("eac3"))); | |
| 127 | + assert!(!registry.has_decoder(&CodecId::new("truehd"))); | |
| 128 | + } | |
| 129 | +} |
shims/oxideav-ac3/tests/edith_surface.rsadded+105 -0
| @@ -0,0 +1,105 @@ | ||
| 1 | +//! The AC-3 path exactly as the replica drives it: read the rate and the | |
| 2 | +//! layout out of the first syncframe's headers, ask the registry for a decoder | |
| 3 | +//! folded to that layout, decode, and read the frame back as S16 little-endian | |
| 4 | +//! (`engine/src/audio.rs:1954-2170`). | |
| 5 | +//! | |
| 6 | +//! Missing fixtures skip rather than fail, as the `ec-ac3` matrix does; | |
| 7 | +//! `scripts/gen-fixtures.sh` writes them. | |
| 8 | + | |
| 9 | +use std::path::{Path, PathBuf}; | |
| 10 | + | |
| 11 | +use oxideav_ac3::{bsi, eac3, register_codecs, syncinfo}; | |
| 12 | +use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Error, Frame, Packet, TimeBase}; | |
| 13 | + | |
| 14 | +fn fixture(name: &str) -> Option<Vec<u8>> { | |
| 15 | + let path: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")) | |
| 16 | + .join("../../fixtures/audio") | |
| 17 | + .join(name); | |
| 18 | + std::fs::read(path).ok() | |
| 19 | +} | |
| 20 | + | |
| 21 | +/// `engine/src/audio.rs:2130` — a fresh decoder out of a fresh registry. | |
| 22 | +fn ac3_decoder(codec: &str, channels: Option<u16>) -> Box<dyn Decoder> { | |
| 23 | + let mut registry = CodecRegistry::new(); | |
| 24 | + register_codecs(&mut registry); | |
| 25 | + let mut params = CodecParameters::audio(CodecId::new(codec)); | |
| 26 | + params.channels = channels; | |
| 27 | + registry.first_decoder(¶ms).expect("no AC-3 decoder") | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// `engine/src/audio.rs:2150` — one syncframe in, interleaved `f32` and the | |
| 31 | +/// frames per channel out; `None` when the decoder wants more input. | |
| 32 | +fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> Option<(Vec<f32>, u64)> { | |
| 33 | + let packet = Packet::new(0, TimeBase::new(1, 48_000), bytes.to_vec()); | |
| 34 | + decoder.send_packet(&packet).expect("AC-3 decode failed"); | |
| 35 | + match decoder.receive_frame() { | |
| 36 | + Ok(Frame::Audio(audio)) => Some(( | |
| 37 | + audio.data[0] | |
| 38 | + .chunks_exact(2) | |
| 39 | + .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) | |
| 40 | + .collect(), | |
| 41 | + u64::from(audio.samples), | |
| 42 | + )), | |
| 43 | + Ok(other) => panic!("AC-3 decoder handed back {other:?}"), | |
| 44 | + Err(Error::NeedMore) => None, | |
| 45 | + Err(e) => panic!("AC-3 decode failed: {e:?}"), | |
| 46 | + } | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// `engine/src/audio.rs:2061` — rate and `nfchans` out of the bit stream, | |
| 50 | +/// whichever syntax it is. | |
| 51 | +fn header(codec: &str, frame: &[u8]) -> (u32, usize) { | |
| 52 | + if codec == "eac3" { | |
| 53 | + let bsi = eac3::bsi::parse(frame.get(2..).unwrap_or_default()).expect("E-AC-3 bsi"); | |
| 54 | + (bsi.sample_rate, bsi.nfchans) | |
| 55 | + } else { | |
| 56 | + let sync = syncinfo::parse(frame).expect("AC-3 syncinfo"); | |
| 57 | + let bsi = bsi::parse(frame.get(5..).unwrap_or_default()).expect("AC-3 bsi"); | |
| 58 | + (sync.sample_rate, bsi.nfchans) | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +fn rms(pcm: &[f32]) -> f64 { | |
| 63 | + (pcm.iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>() / pcm.len().max(1) as f64).sqrt() | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// Every generated layout, opened the way a timeline source is opened: wider | |
| 67 | +/// than mono folds to stereo, mono stays mono, and neither decodes to silence | |
| 68 | +/// (the replica's mono `corner-cut` exists because the incumbent did). | |
| 69 | +#[test] | |
| 70 | +fn the_replicas_open_path_lands_on_audible_pcm() { | |
| 71 | + let cases = [ | |
| 72 | + ("ac3-5.1-48000.ac3", "ac3", 48_000, 5, 2), | |
| 73 | + ("ac3-stereo-48000.ac3", "ac3", 48_000, 2, 2), | |
| 74 | + ("ac3-mono-44100.ac3", "ac3", 44_100, 1, 1), | |
| 75 | + ("eac3-5.1-48000.eac3", "eac3", 48_000, 5, 2), | |
| 76 | + ("eac3-mono-48000.eac3", "eac3", 48_000, 1, 1), | |
| 77 | + ]; | |
| 78 | + let mut ran = 0; | |
| 79 | + for (name, codec, rate, nfchans_want, channels_want) in cases { | |
| 80 | + let Some(data) = fixture(name) else { continue }; | |
| 81 | + ran += 1; | |
| 82 | + | |
| 83 | + let (sample_rate, nfchans) = header(codec, &data); | |
| 84 | + assert_eq!(sample_rate, rate, "{name}: sample rate"); | |
| 85 | + assert_eq!(nfchans, nfchans_want, "{name}: nfchans"); | |
| 86 | + | |
| 87 | + let requested = (nfchans > 1).then_some(2); | |
| 88 | + let mut decoder = ac3_decoder(codec, requested); | |
| 89 | + let (pcm, samples) = decode_ac3(&mut decoder, &data).expect("the first syncframe decoded"); | |
| 90 | + let channels = (pcm.len() as u64 / samples.max(1)) as u16; | |
| 91 | + assert_eq!(channels, channels_want, "{name}: decoded channels"); | |
| 92 | + assert!(samples > 0, "{name}: no samples"); | |
| 93 | + assert!(rms(&pcm) > 1e-3, "{name}: decoded to silence, rms {}", rms(&pcm)); | |
| 94 | + | |
| 95 | + // The replica then feeds the rest of the stream frame by frame; a | |
| 96 | + // second frame proves the packet walk does not desync on the shim's | |
| 97 | + // conversion. | |
| 98 | + let size = ec_ac3::frame_size(&data).expect("frame size"); | |
| 99 | + if let Some(next) = data.get(size..).filter(|rest| rest.len() > size) { | |
| 100 | + let (pcm, samples) = decode_ac3(&mut decoder, next).expect("the second syncframe"); | |
| 101 | + assert_eq!((pcm.len() as u64 / samples.max(1)) as u16, channels_want); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + assert!(ran > 0, "no AC-3 fixtures: run scripts/gen-fixtures.sh"); | |
| 105 | +} |
shims/oxideav-core/src/lib.rsmodified+161 -7
| @@ -133,6 +133,72 @@ impl fmt::Display for CodecId { | ||
| 133 | 133 | } |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | +impl From<&str> for CodecId { | |
| 137 | + fn from(s: &str) -> CodecId { | |
| 138 | + CodecId(s.to_owned()) | |
| 139 | + } | |
| 140 | +} | |
| 141 | + | |
| 142 | +impl From<String> for CodecId { | |
| 143 | + fn from(s: String) -> CodecId { | |
| 144 | + CodecId(s) | |
| 145 | + } | |
| 146 | +} | |
| 147 | + | |
| 148 | +/// How a codec is named by a container, so a demuxer can map what it read to a | |
| 149 | +/// registration. | |
| 150 | +#[derive(Clone, Debug, PartialEq, Eq, Hash)] | |
| 151 | +pub enum CodecTag { | |
| 152 | + /// A four-character code, as mp4 sample entries and RIFF write it. | |
| 153 | + FourCc([u8; 4]), | |
| 154 | + /// An MPEG-4 `ObjectTypeIndication`. | |
| 155 | + Mp4ObjectType(u8), | |
| 156 | + /// A Matroska `CodecID` string. | |
| 157 | + Matroska(String), | |
| 158 | +} | |
| 159 | + | |
| 160 | +impl CodecTag { | |
| 161 | + /// The four-character code `code`. | |
| 162 | + pub fn fourcc(code: &[u8; 4]) -> CodecTag { | |
| 163 | + CodecTag::FourCc(*code) | |
| 164 | + } | |
| 165 | + | |
| 166 | + /// The MPEG-4 object type `oti`. | |
| 167 | + pub fn mp4_object_type(oti: u8) -> CodecTag { | |
| 168 | + CodecTag::Mp4ObjectType(oti) | |
| 169 | + } | |
| 170 | + | |
| 171 | + /// The Matroska `CodecID` `id`. | |
| 172 | + pub fn matroska(id: impl Into<String>) -> CodecTag { | |
| 173 | + CodecTag::Matroska(id.into()) | |
| 174 | + } | |
| 175 | +} | |
| 176 | + | |
| 177 | +/// How samples are laid out in a video frame. Only the format the family's own | |
| 178 | +/// encoders take and hand out is named; a caller that needs another adds it. | |
| 179 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] | |
| 180 | +pub enum PixelFormat { | |
| 181 | + /// Planar 4:2:0 8-bit. | |
| 182 | + #[default] | |
| 183 | + Yuv420P, | |
| 184 | +} | |
| 185 | + | |
| 186 | +/// A codec's string-keyed knobs, parsed by whichever codec declares them. | |
| 187 | +#[derive(Clone, Debug, Default, PartialEq, Eq)] | |
| 188 | +pub struct CodecOptions(HashMap<String, String>); | |
| 189 | + | |
| 190 | +impl CodecOptions { | |
| 191 | + /// The value set for `key`, if any. | |
| 192 | + pub fn get(&self, key: &str) -> Option<&str> { | |
| 193 | + self.0.get(key).map(String::as_str) | |
| 194 | + } | |
| 195 | + | |
| 196 | + /// Set `key` to `value`, replacing what was there. | |
| 197 | + pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) { | |
| 198 | + self.0.insert(key.into(), value.into()); | |
| 199 | + } | |
| 200 | +} | |
| 201 | + | |
| 136 | 202 | /// What kind of stream a set of parameters describes. |
| 137 | 203 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 138 | 204 | pub enum MediaType { |
| @@ -164,8 +230,12 @@ pub struct CodecParameters { | ||
| 164 | 230 | pub width: Option<u32>, |
| 165 | 231 | /// Coded height. |
| 166 | 232 | pub height: Option<u32>, |
| 233 | + /// How a video stream's samples are laid out. | |
| 234 | + pub pixel_format: Option<PixelFormat>, | |
| 167 | 235 | /// Codec setup bytes. |
| 168 | 236 | pub extradata: Vec<u8>, |
| 237 | + /// Codec-specific knobs, read by whichever codec declares them. | |
| 238 | + pub options: CodecOptions, | |
| 169 | 239 | } |
| 170 | 240 | |
| 171 | 241 | impl CodecParameters { |
| @@ -222,12 +292,13 @@ pub struct StreamInfo { | ||
| 222 | 292 | } |
| 223 | 293 | |
| 224 | 294 | /// One decoded picture. |
| 295 | +/// | |
| 296 | +/// No dimensions: the incumbent states them on the stream's | |
| 297 | +/// [`CodecParameters`] and puts only the row stride on the plane, and a codec | |
| 298 | +/// crate outside this workspace writes the literal (`oxideav-h265`'s decoder | |
| 299 | +/// does), so the field list is the incumbent's and not ours to improve. | |
| 225 | 300 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 226 | 301 | pub struct VideoFrame { |
| 227 | - /// Width in pixels. | |
| 228 | - pub width: u32, | |
| 229 | - /// Height in pixels. | |
| 230 | - pub height: u32, | |
| 231 | 302 | /// Presentation time in the stream's time base. |
| 232 | 303 | pub pts: Option<i64>, |
| 233 | 304 | /// One plane per component group; packed formats have exactly one. |
| @@ -267,8 +338,6 @@ impl From<ec_core::Frame> for Frame { | ||
| 267 | 338 | fn from(frame: ec_core::Frame) -> Frame { |
| 268 | 339 | match frame { |
| 269 | 340 | ec_core::Frame::Video(video) => Frame::Video(VideoFrame { |
| 270 | - width: video.width, | |
| 271 | - height: video.height, | |
| 272 | 341 | pts: video.pts.map(|t| t.ticks), |
| 273 | 342 | planes: video |
| 274 | 343 | .planes |
| @@ -299,6 +368,35 @@ pub trait Decoder: Send { | ||
| 299 | 368 | /// Take one frame, or [`Error::NeedMore`] when the decoder wants another |
| 300 | 369 | /// packet first. |
| 301 | 370 | fn receive_frame(&mut self) -> Result<Frame>; |
| 371 | + | |
| 372 | + /// Signal end of input, so whatever is held back becomes available through | |
| 373 | + /// [`receive_frame`](Decoder::receive_frame) and then [`Error::Eof`]. | |
| 374 | + /// | |
| 375 | + /// The default is for a decoder that holds nothing back — one packet in, | |
| 376 | + /// one frame out, which is what the AC-3 path is. | |
| 377 | + fn flush(&mut self) -> Result<()> { | |
| 378 | + Ok(()) | |
| 379 | + } | |
| 380 | +} | |
| 381 | + | |
| 382 | +/// An encoder: frames in, packets out. | |
| 383 | +pub trait Encoder: Send { | |
| 384 | + /// The codec this produces. | |
| 385 | + fn codec_id(&self) -> &CodecId; | |
| 386 | + | |
| 387 | + /// Parameters describing the stream it produces, for the muxer. | |
| 388 | + fn output_params(&self) -> &CodecParameters; | |
| 389 | + | |
| 390 | + /// Feed one uncompressed frame. | |
| 391 | + fn send_frame(&mut self, frame: &Frame) -> Result<()>; | |
| 392 | + | |
| 393 | + /// Take one packet, or [`Error::NeedMore`] when the encoder wants another | |
| 394 | + /// frame first. | |
| 395 | + fn receive_packet(&mut self) -> Result<Packet>; | |
| 396 | + | |
| 397 | + /// Signal end of input, so the lookahead drains into | |
| 398 | + /// [`receive_packet`](Encoder::receive_packet). | |
| 399 | + fn flush(&mut self) -> Result<()>; | |
| 302 | 400 | } |
| 303 | 401 | |
| 304 | 402 | /// A container writer. |
| @@ -319,6 +417,9 @@ pub trait Muxer: Send { | ||
| 319 | 417 | /// How a codec crate hands out decoders. |
| 320 | 418 | pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>; |
| 321 | 419 | |
| 420 | +/// How a codec crate hands out encoders. | |
| 421 | +pub type EncoderFactory = fn(&CodecParameters) -> Result<Box<dyn Encoder>>; | |
| 422 | + | |
| 322 | 423 | /// One codec's registration. |
| 323 | 424 | #[derive(Clone)] |
| 324 | 425 | pub struct CodecInfo { |
| @@ -326,6 +427,10 @@ pub struct CodecInfo { | ||
| 326 | 427 | pub id: CodecId, |
| 327 | 428 | /// How to build a decoder for it. |
| 328 | 429 | pub decoder_factory: Option<DecoderFactory>, |
| 430 | + /// How to build an encoder for it. | |
| 431 | + pub encoder_factory: Option<EncoderFactory>, | |
| 432 | + /// The container-level names that mean this codec. | |
| 433 | + pub tags: Vec<CodecTag>, | |
| 329 | 434 | } |
| 330 | 435 | |
| 331 | 436 | impl CodecInfo { |
| @@ -334,6 +439,8 @@ impl CodecInfo { | ||
| 334 | 439 | CodecInfo { |
| 335 | 440 | id, |
| 336 | 441 | decoder_factory: None, |
| 442 | + encoder_factory: None, | |
| 443 | + tags: Vec::new(), | |
| 337 | 444 | } |
| 338 | 445 | } |
| 339 | 446 | |
| @@ -342,6 +449,18 @@ impl CodecInfo { | ||
| 342 | 449 | self.decoder_factory = Some(factory); |
| 343 | 450 | self |
| 344 | 451 | } |
| 452 | + | |
| 453 | + /// The same registration, with an encoder. | |
| 454 | + pub fn encoder(mut self, factory: EncoderFactory) -> CodecInfo { | |
| 455 | + self.encoder_factory = Some(factory); | |
| 456 | + self | |
| 457 | + } | |
| 458 | + | |
| 459 | + /// The same registration, claiming `tags` on top of whatever it claimed. | |
| 460 | + pub fn tags(mut self, tags: impl IntoIterator<Item = CodecTag>) -> CodecInfo { | |
| 461 | + self.tags.extend(tags); | |
| 462 | + self | |
| 463 | + } | |
| 345 | 464 | } |
| 346 | 465 | |
| 347 | 466 | /// The codecs a caller has registered, in registration order per id. |
| @@ -382,6 +501,42 @@ impl CodecRegistry { | ||
| 382 | 501 | } |
| 383 | 502 | } |
| 384 | 503 | |
| 504 | +/// What a codec crate is handed to register itself into. | |
| 505 | +/// | |
| 506 | +/// The incumbent's context carries four sub-registries; this one carries the | |
| 507 | +/// codecs, because a container, source or filter crate registering into the | |
| 508 | +/// replica's build does not exist. | |
| 509 | +#[derive(Clone, Default)] | |
| 510 | +pub struct RuntimeContext { | |
| 511 | + /// Decoder and encoder factories, by codec id. | |
| 512 | + pub codecs: CodecRegistry, | |
| 513 | +} | |
| 514 | + | |
| 515 | +impl RuntimeContext { | |
| 516 | + /// An empty context. | |
| 517 | + pub fn new() -> RuntimeContext { | |
| 518 | + RuntimeContext::default() | |
| 519 | + } | |
| 520 | +} | |
| 521 | + | |
| 522 | +/// Declare a codec crate's registration entry point, as the family's crates | |
| 523 | +/// spell it: `oxideav_core::register!("h265", register);`. | |
| 524 | +/// | |
| 525 | +/// The name is carried for documentation only, exactly as the incumbent does — | |
| 526 | +/// what the generated `__oxideav_entry` runs is `$func`. | |
| 527 | +#[macro_export] | |
| 528 | +macro_rules! register { | |
| 529 | + ($name:literal, $func:path) => { | |
| 530 | + /// This crate's registration entry point, generated by | |
| 531 | + /// [`oxideav_core::register!`]. | |
| 532 | + #[doc(hidden)] | |
| 533 | + pub fn __oxideav_entry(ctx: &mut $crate::RuntimeContext) { | |
| 534 | + let _ = $name; | |
| 535 | + $func(ctx); | |
| 536 | + } | |
| 537 | + }; | |
| 538 | +} | |
| 539 | + | |
| 385 | 540 | /// A [`Decoder`] over one of the family's own, converting the frames on the way |
| 386 | 541 | /// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap. |
| 387 | 542 | pub struct EcDecoder { |
| @@ -460,7 +615,6 @@ mod tests { | ||
| 460 | 615 | let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else { |
| 461 | 616 | panic!("a video frame stays a video frame"); |
| 462 | 617 | }; |
| 463 | - assert_eq!((frame.width, frame.height), (1, 1)); | |
| 464 | 618 | assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]); |
| 465 | 619 | assert_eq!(frame.planes[0].stride, 4); |
| 466 | 620 |
shims/oxideav-sub-image/src/lib.rsmodified+5 -2
| @@ -71,10 +71,13 @@ mod tests { | ||
| 71 | 71 | let Ok(Frame::Video(frame)) = decoder.receive_frame() else { |
| 72 | 72 | panic!("a display set is a picture"); |
| 73 | 73 | }; |
| 74 | - assert_eq!((frame.width, frame.height), (4, 2)); | |
| 74 | + // A 4x2 canvas: no dimensions on the frame, so the row stride and the | |
| 75 | + // byte count are what state them. | |
| 76 | + assert_eq!(frame.planes[0].stride, 4 * 4); | |
| 75 | 77 | let data = frame.planes.into_iter().next().unwrap().data; |
| 76 | 78 | assert_eq!(data.len(), 4 * 2 * 4); |
| 77 | - assert_eq!(&data[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); | |
| 79 | + // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`). | |
| 80 | + assert_eq!(&data[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]); | |
| 78 | 81 | assert_eq!(&data[0..4], &[0, 0, 0, 0]); |
| 79 | 82 | } |
| 80 | 83 | } |
shims/oxideav-sub-image/tests/replica_call_shapes.rsmodified+2 -1
| @@ -102,7 +102,8 @@ fn a_matroska_pgs_block_decodes_the_way_the_replica_decodes_one() { | ||
| 102 | 102 | // The whole canvas, transparent where the cue paints nothing. |
| 103 | 103 | assert_eq!(rgba.len(), 4 * 2 * 4); |
| 104 | 104 | assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); |
| 105 | - assert_eq!(&rgba[4..12], &[255, 255, 255, 255, 255, 255, 255, 255]); | |
| 105 | + // The palette's own white, `Y' = 235` (see `ec_pgs`'s `rgba`). | |
| 106 | + assert_eq!(&rgba[4..12], &[235, 235, 235, 255, 235, 235, 235, 255]); | |
| 106 | 107 | |
| 107 | 108 | // The erase set after the composition must not be what gets decoded: the |
| 108 | 109 | // loop above stops at the `END` that closes the showing set. |