| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use ec_core::{Error, Result}; |
| 13 | |
| 14 | |
| 15 | |
| 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 | |
| 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 | |
| 148 | pub struct BitReader<'a> { |
| 149 | data: &'a [u8], |
| 150 | |
| 151 | pos: usize, |
| 152 | } |
| 153 | |
| 154 | impl<'a> BitReader<'a> { |
| 155 | |
| 156 | pub fn new(data: &'a [u8]) -> BitReader<'a> { |
| 157 | BitReader { data, pos: 0 } |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 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 | |
| 177 | pub fn exhausted(&self) -> bool { |
| 178 | self.pos > self.data.len() * 8 |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | |
| 183 | struct Huffman { |
| 184 | |
| 185 | counts: [u16; MAX_ALLOWED_CODE_LENGTH + 1], |
| 186 | |
| 187 | symbols: Vec<u16>, |
| 188 | |
| 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 | |
| 218 | |
| 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 | |
| 231 | |
| 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 | |
| 279 | struct Group { |
| 280 | green: Huffman, |
| 281 | red: Huffman, |
| 282 | blue: Huffman, |
| 283 | alpha: Huffman, |
| 284 | distance: Huffman, |
| 285 | } |
| 286 | |
| 287 | |
| 288 | pub struct Argb { |
| 289 | |
| 290 | pub width: u32, |
| 291 | |
| 292 | pub height: u32, |
| 293 | |
| 294 | pub pixels: Vec<u32>, |
| 295 | } |
| 296 | |
| 297 | |
| 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 | |
| 320 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 487 | |
| 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 | |
| 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 | |
| 530 | |
| 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 | |
| 561 | |
| 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 | |
| 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 | |
| 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 | |
| 632 | |
| 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 | |
| 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 | |
| 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 | |
| 711 | |
| 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 | |
| 723 | |
| 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 | |
| 825 | |
| 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 | |
| 854 | let code = Huffman::from_lengths(&[1, 2, 3, 3]).unwrap(); |
| 855 | let mut bits = BitReader::new(&[0b1101_1100, 0b0000_0001]); |
| 856 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | } |