forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

vp8l.rs897 lines, 27.7 KiBHistoryRawDownload
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
12use 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.
16const 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.
140const 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
144const GREEN_EXTRA: usize = 24;
145const MAX_ALLOWED_CODE_LENGTH: usize = 15;
146
147/// Least-significant-bit-first bit reader, as VP8L reads its stream.
148pub struct BitReader<'a> {
149 data: &'a [u8],
150 /// Bit position from the start of `data`.
151 pos: usize,
152}
153
154impl<'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.
183struct 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
192impl 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.
279struct 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.
288pub 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.
298pub 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 // Every VP8L picture comes out as RGBA, four bytes a pixel.
311 limits.check_output(width, height, 4)?;
312 let pixels = decode_stream(&mut bits, width, height, true)?;
313 Ok(Argb {
314 width,
315 height,
316 pixels,
317 })
318}
319
320/// Decode a headerless VP8L stream of known dimensions — how an `ALPH` chunk
321/// carries a lossless alpha plane, and how a colour table is stored.
322pub fn decode_implicit(data: &[u8], width: u32, height: u32) -> Result<Vec<u32>> {
323 let mut bits = BitReader::new(data);
324 decode_stream(&mut bits, width, height, true)
325}
326
327/// The image stream proper: transforms (when allowed), then entropy-coded data.
328fn decode_stream(
329 bits: &mut BitReader<'_>,
330 width: u32,
331 height: u32,
332 transforms_allowed: bool,
333) -> Result<Vec<u32>> {
334 let mut transforms: Vec<Transform> = Vec::new();
335 let mut work_width = width;
336 if transforms_allowed {
337 let mut seen = [false; 4];
338 while bits.read(1) == 1 {
339 let kind = bits.read(2) as usize;
340 if seen[kind] {
341 return Err(Error::corrupt("VP8L: transform used twice"));
342 }
343 seen[kind] = true;
344 let transform = read_transform(bits, kind, work_width, height)?;
345 if let Transform::ColorIndexing { width_bits, .. } = &transform {
346 work_width = work_width.div_ceil(1 << width_bits);
347 }
348 transforms.push(transform);
349 }
350 }
351
352 let mut pixels = decode_entropy_coded(bits, work_width, height, true)?;
353 // Applied last-read-first, which is the inverse of the encoder's order.
354 for transform in transforms.iter().rev() {
355 pixels = apply_transform(transform, pixels, &mut work_width, height)?;
356 }
357 if work_width != width {
358 return Err(Error::corrupt("VP8L: transforms left the wrong width"));
359 }
360 Ok(pixels)
361}
362
363/// A transform, with the data needed to invert it.
364enum Transform {
365 Predictor { bits: u32, image: Vec<u32>, tw: u32 },
366 Color { bits: u32, image: Vec<u32>, tw: u32 },
367 SubtractGreen,
368 ColorIndexing { width_bits: u32, table: Vec<u32> },
369}
370
371fn read_transform(
372 bits: &mut BitReader<'_>,
373 kind: usize,
374 width: u32,
375 height: u32,
376) -> Result<Transform> {
377 match kind {
378 0 | 1 => {
379 let size_bits = bits.read(3) + 2;
380 let tw = width.div_ceil(1 << size_bits);
381 let th = height.div_ceil(1 << size_bits);
382 let image = decode_entropy_coded(bits, tw, th, false)?;
383 Ok(if kind == 0 {
384 Transform::Predictor {
385 bits: size_bits,
386 image,
387 tw,
388 }
389 } else {
390 Transform::Color {
391 bits: size_bits,
392 image,
393 tw,
394 }
395 })
396 }
397 2 => Ok(Transform::SubtractGreen),
398 _ => {
399 let size = bits.read(8) + 1;
400 let mut table = decode_entropy_coded(bits, size, 1, false)?;
401 // The table is stored as deltas between successive colours.
402 for i in 1..table.len() {
403 table[i] = add_argb(table[i], table[i - 1]);
404 }
405 let width_bits = match size {
406 0..=2 => 3,
407 3..=4 => 2,
408 5..=16 => 1,
409 _ => 0,
410 };
411 Ok(Transform::ColorIndexing { width_bits, table })
412 }
413 }
414}
415
416fn apply_transform(
417 transform: &Transform,
418 pixels: Vec<u32>,
419 width: &mut u32,
420 height: u32,
421) -> Result<Vec<u32>> {
422 Ok(match transform {
423 Transform::SubtractGreen => pixels
424 .into_iter()
425 .map(|p| {
426 let g = (p >> 8) & 0xff;
427 let r = ((p >> 16) + g) & 0xff;
428 let b = (p + g) & 0xff;
429 (p & 0xff00_ff00) | (r << 16) | b
430 })
431 .collect(),
432 Transform::Color { bits, image, tw } => {
433 let mut out = pixels;
434 for y in 0..height {
435 for x in 0..*width {
436 let block = (y >> bits) * tw + (x >> bits);
437 let element = image.get(block as usize).copied().unwrap_or(0);
438 let index = (y * *width + x) as usize;
439 out[index] = inverse_color(out[index], element);
440 }
441 }
442 out
443 }
444 Transform::Predictor { bits, image, tw } => {
445 inverse_predictor(pixels, *width, height, *bits, image, *tw)
446 }
447 Transform::ColorIndexing { width_bits, table } => {
448 let out_width = *width << width_bits;
449 let mut out = vec![0u32; (out_width as usize) * (height as usize)];
450 let per_pixel = 1u32 << width_bits;
451 let bits_each = 8 >> width_bits;
452 let mask = (1u32 << bits_each) - 1;
453 for y in 0..height {
454 for x in 0..*width {
455 let packed = (pixels[(y * *width + x) as usize] >> 8) & 0xff;
456 for sub in 0..per_pixel {
457 let ox = x * per_pixel + sub;
458 if ox >= out_width {
459 break;
460 }
461 let index = if *width_bits == 0 {
462 packed
463 } else {
464 (packed >> (bits_each * sub)) & mask
465 };
466 out[(y * out_width + ox) as usize] =
467 table.get(index as usize).copied().unwrap_or(0);
468 }
469 }
470 }
471 *width = out_width;
472 out
473 }
474 })
475}
476
477fn add_argb(a: u32, b: u32) -> u32 {
478 let mut out = 0u32;
479 for shift in [0, 8, 16, 24] {
480 let sum = (((a >> shift) & 0xff) + ((b >> shift) & 0xff)) & 0xff;
481 out |= sum << shift;
482 }
483 out
484}
485
486fn inverse_color(pixel: u32, element: u32) -> u32 {
487 // The element carries green_to_red in blue, green_to_blue in green and
488 // red_to_blue in red, as the specification lays it out.
489 let green_to_red = (element & 0xff) as i8;
490 let green_to_blue = ((element >> 8) & 0xff) as i8;
491 let red_to_blue = ((element >> 16) & 0xff) as i8;
492 let green = ((pixel >> 8) & 0xff) as u8 as i8;
493 let mut red = ((pixel >> 16) & 0xff) as i32;
494 let mut blue = (pixel & 0xff) as i32;
495 red += delta(green_to_red, green);
496 blue += delta(green_to_blue, green);
497 blue += delta(red_to_blue, (red & 0xff) as u8 as i8);
498 (pixel & 0xff00_ff00) | (((red & 0xff) as u32) << 16) | ((blue & 0xff) as u32)
499}
500
501/// `(t * c) >> 5` in the specification's 3.5 fixed point.
502fn delta(t: i8, c: i8) -> i32 {
503 (i32::from(t) * i32::from(c)) >> 5
504}
505
506fn inverse_predictor(
507 mut pixels: Vec<u32>,
508 width: u32,
509 height: u32,
510 size_bits: u32,
511 image: &[u32],
512 tw: u32,
513) -> Vec<u32> {
514 let w = width as usize;
515 for y in 0..height as usize {
516 for x in 0..w {
517 let index = y * w + x;
518 let pred = if x == 0 && y == 0 {
519 0xff00_0000
520 } else if y == 0 {
521 pixels[index - 1]
522 } else if x == 0 {
523 pixels[index - w]
524 } else {
525 let block = ((y as u32) >> size_bits) * tw + ((x as u32) >> size_bits);
526 let mode = image.get(block as usize).map_or(0, |p| (p >> 8) & 0xff);
527 let left = pixels[index - 1];
528 let top = pixels[index - w];
529 let top_left = pixels[index - w - 1];
530 // The rightmost column has no top-right; the leftmost pixel of
531 // the same row stands in, as the specification requires.
532 let top_right = if x + 1 == w {
533 pixels[y * w]
534 } else {
535 pixels[index - w + 1]
536 };
537 predict(mode, left, top, top_left, top_right)
538 };
539 pixels[index] = add_argb(pixels[index], pred);
540 }
541 }
542 pixels
543}
544
545fn predict(mode: u32, l: u32, t: u32, tl: u32, tr: u32) -> u32 {
546 match mode {
547 0 => 0xff00_0000,
548 1 => l,
549 2 => t,
550 3 => tr,
551 4 => tl,
552 5 => average2(average2(l, tr), t),
553 6 => average2(l, tl),
554 7 => average2(l, t),
555 8 => average2(tl, t),
556 9 => average2(t, tr),
557 10 => average2(average2(l, tl), average2(t, tr)),
558 11 => select(l, t, tl),
559 12 => clamp_add_subtract_full(l, t, tl),
560 13 => clamp_add_subtract_half(average2(l, t), tl),
561 // Modes past 13 do not exist; a corrupt predictor image gets black
562 // rather than an out-of-range panic.
563 _ => 0xff00_0000,
564 }
565}
566
567fn average2(a: u32, b: u32) -> u32 {
568 let mut out = 0u32;
569 for shift in [0, 8, 16, 24] {
570 let v = (((a >> shift) & 0xff) + ((b >> shift) & 0xff)) / 2;
571 out |= v << shift;
572 }
573 out
574}
575
576fn select(l: u32, t: u32, tl: u32) -> u32 {
577 let mut pl = 0i32;
578 let mut pt = 0i32;
579 for shift in [0, 8, 16, 24] {
580 let (a, b, c) = (
581 ((l >> shift) & 0xff) as i32,
582 ((t >> shift) & 0xff) as i32,
583 ((tl >> shift) & 0xff) as i32,
584 );
585 let p = a + b - c;
586 pl += (p - a).abs();
587 pt += (p - b).abs();
588 }
589 if pl < pt { l } else { t }
590}
591
592fn clamp_add_subtract_full(a: u32, b: u32, c: u32) -> u32 {
593 let mut out = 0u32;
594 for shift in [0, 8, 16, 24] {
595 let v = (((a >> shift) & 0xff) as i32 + ((b >> shift) & 0xff) as i32
596 - ((c >> shift) & 0xff) as i32)
597 .clamp(0, 255) as u32;
598 out |= v << shift;
599 }
600 out
601}
602
603fn clamp_add_subtract_half(a: u32, b: u32) -> u32 {
604 let mut out = 0u32;
605 for shift in [0, 8, 16, 24] {
606 let (x, y) = (((a >> shift) & 0xff) as i32, ((b >> shift) & 0xff) as i32);
607 let v = (x + (x - y) / 2).clamp(0, 255) as u32;
608 out |= v << shift;
609 }
610 out
611}
612
613/// Read a prefix code: either the two-symbol shorthand or full code lengths.
614fn read_code(bits: &mut BitReader<'_>, alphabet: usize) -> Result<Huffman> {
615 let mut lengths = vec![0u8; alphabet];
616 if bits.read(1) == 1 {
617 // Simple code: one or two symbols, each one bit long.
618 let count = bits.read(1) + 1;
619 let first_is_byte = bits.read(1) == 1;
620 let symbol0 = bits.read(if first_is_byte { 8 } else { 1 }) as usize;
621 if symbol0 >= alphabet {
622 return Err(Error::corrupt("VP8L: simple code symbol past the alphabet"));
623 }
624 lengths[symbol0] = 1;
625 if count == 2 {
626 let symbol1 = bits.read(8) as usize;
627 if symbol1 >= alphabet {
628 return Err(Error::corrupt("VP8L: simple code symbol past the alphabet"));
629 }
630 lengths[symbol1] = 1;
631 }
632 // One symbol of length 1 is a legal single-leaf code, so build from
633 // the lengths rather than insisting the Kraft sum be exactly one.
634 return Huffman::from_lengths(&lengths);
635 }
636
637 let num_lengths = 4 + bits.read(4) as usize;
638 let mut code_length_lengths = [0u8; 19];
639 for i in 0..num_lengths {
640 code_length_lengths[CODE_LENGTH_ORDER[i]] = bits.read(3) as u8;
641 }
642 let code_length_code = Huffman::from_lengths(&code_length_lengths)?;
643
644 let mut max_symbol = if bits.read(1) == 1 {
645 let length_bits = 2 + 2 * bits.read(3);
646 let max = 2 + bits.read(length_bits) as usize;
647 if max > alphabet {
648 return Err(Error::corrupt("VP8L: max_symbol past the alphabet"));
649 }
650 max
651 } else {
652 alphabet
653 };
654
655 let mut previous = 8u8;
656 let mut index = 0usize;
657 while index < alphabet {
658 if max_symbol == 0 {
659 break;
660 }
661 max_symbol -= 1;
662 if bits.exhausted() {
663 return Err(Error::corrupt("VP8L: truncated code lengths"));
664 }
665 let symbol = code_length_code.decode(bits)?;
666 match symbol {
667 0..=15 => {
668 lengths[index] = symbol as u8;
669 index += 1;
670 if symbol != 0 {
671 previous = symbol as u8;
672 }
673 }
674 16 => {
675 let repeat = 3 + bits.read(2) as usize;
676 for _ in 0..repeat.min(alphabet - index) {
677 lengths[index] = previous;
678 index += 1;
679 }
680 }
681 17 => index += (3 + bits.read(3) as usize).min(alphabet - index),
682 18 => index += (11 + bits.read(7) as usize).min(alphabet - index),
683 other => return Err(Error::corrupt(format!("VP8L: code length symbol {other}"))),
684 }
685 }
686 Huffman::from_lengths(&lengths)
687}
688
689/// Read the five prefix codes of one group.
690fn read_group(bits: &mut BitReader<'_>, cache_bits: u32) -> Result<Group> {
691 let green_alphabet = 256 + GREEN_EXTRA + if cache_bits > 0 { 1 << cache_bits } else { 0 };
692 Ok(Group {
693 green: read_code(bits, green_alphabet)?,
694 red: read_code(bits, 256)?,
695 blue: read_code(bits, 256)?,
696 alpha: read_code(bits, 256)?,
697 distance: read_code(bits, 40)?,
698 })
699}
700
701/// Length or distance from a prefix code plus its extra bits.
702fn prefix_value(bits: &mut BitReader<'_>, code: u32) -> u32 {
703 if code < 4 {
704 return code + 1;
705 }
706 let extra = (code - 2) >> 1;
707 let offset = (2 + (code & 1)) << extra;
708 offset + bits.read(extra) + 1
709}
710
711/// Decode an entropy-coded image: the ARGB image itself, or one of the
712/// sub-resolution images a transform or the meta prefix uses.
713fn decode_entropy_coded(
714 bits: &mut BitReader<'_>,
715 width: u32,
716 height: u32,
717 meta_allowed: bool,
718) -> Result<Vec<u32>> {
719 let count = (width as usize)
720 .checked_mul(height as usize)
721 .ok_or_else(|| Error::corrupt("VP8L: image geometry overflows"))?;
722
723 // Order matters and is easy to get backwards: the colour cache size comes
724 // first, then the meta prefix codes, then the prefix codes themselves.
725 let cache_bits = if bits.read(1) == 1 {
726 let n = bits.read(4);
727 if !(1..=11).contains(&n) {
728 return Err(Error::corrupt(format!("VP8L: colour cache bits {n}")));
729 }
730 n
731 } else {
732 0
733 };
734
735 let mut entropy_image: Vec<u32> = Vec::new();
736 let mut prefix_bits = 0u32;
737 let mut prefix_width = 0u32;
738 let mut groups = 1usize;
739 if meta_allowed && bits.read(1) == 1 {
740 prefix_bits = bits.read(3) + 2;
741 prefix_width = width.div_ceil(1 << prefix_bits);
742 let prefix_height = height.div_ceil(1 << prefix_bits);
743 entropy_image = decode_entropy_coded(bits, prefix_width, prefix_height, false)?;
744 groups = entropy_image
745 .iter()
746 .map(|p| (((p >> 8) & 0xffff) as usize) + 1)
747 .max()
748 .unwrap_or(1);
749 if groups > 1 << 16 {
750 return Err(Error::corrupt("VP8L: too many prefix code groups"));
751 }
752 }
753
754 let mut code_groups = Vec::with_capacity(groups);
755 for _ in 0..groups {
756 code_groups.push(read_group(bits, cache_bits)?);
757 if bits.exhausted() {
758 return Err(Error::corrupt("VP8L: truncated prefix codes"));
759 }
760 }
761
762 let mut cache = vec![0u32; if cache_bits > 0 { 1 << cache_bits } else { 0 }];
763 let mut pixels = vec![0u32; count];
764 let mut at = 0usize;
765 while at < count {
766 if bits.exhausted() {
767 return Err(Error::corrupt("VP8L: truncated image data"));
768 }
769 let group = if entropy_image.is_empty() {
770 &code_groups[0]
771 } else {
772 let x = (at % width as usize) as u32;
773 let y = (at / width as usize) as u32;
774 let block = (y >> prefix_bits) * prefix_width + (x >> prefix_bits);
775 let meta = entropy_image
776 .get(block as usize)
777 .map_or(0, |p| ((p >> 8) & 0xffff) as usize);
778 code_groups
779 .get(meta)
780 .ok_or_else(|| Error::corrupt("VP8L: meta prefix code past its group list"))?
781 };
782 let symbol = u32::from(group.green.decode(bits)?);
783 if symbol < 256 {
784 let red = u32::from(group.red.decode(bits)?);
785 let blue = u32::from(group.blue.decode(bits)?);
786 let alpha = u32::from(group.alpha.decode(bits)?);
787 let pixel = (alpha << 24) | (red << 16) | (symbol << 8) | blue;
788 pixels[at] = pixel;
789 if cache_bits > 0 {
790 cache[cache_index(pixel, cache_bits)] = pixel;
791 }
792 at += 1;
793 } else if symbol < 256 + GREEN_EXTRA as u32 {
794 let length = prefix_value(bits, symbol - 256) as usize;
795 let distance_code = u32::from(group.distance.decode(bits)?);
796 let distance = prefix_value(bits, distance_code) as usize;
797 let distance = map_distance(distance, width);
798 if distance > at || length > count - at {
799 return Err(Error::corrupt("VP8L: backward reference outside the image"));
800 }
801 for i in 0..length {
802 let pixel = pixels[at - distance + i];
803 pixels[at + i] = pixel;
804 if cache_bits > 0 {
805 cache[cache_index(pixel, cache_bits)] = pixel;
806 }
807 }
808 at += length;
809 } else {
810 let index = (symbol - 256 - GREEN_EXTRA as u32) as usize;
811 let pixel = *cache
812 .get(index)
813 .ok_or_else(|| Error::corrupt("VP8L: colour cache index out of range"))?;
814 pixels[at] = pixel;
815 at += 1;
816 }
817 }
818 Ok(pixels)
819}
820
821fn cache_index(pixel: u32, cache_bits: u32) -> usize {
822 ((0x1e35_a7bd_u32.wrapping_mul(pixel)) >> (32 - cache_bits)) as usize
823}
824
825/// Distance codes 1..=120 name a nearby pixel; anything larger is a plain
826/// scan-line distance offset by 120.
827fn map_distance(code: usize, width: u32) -> usize {
828 if code > 120 {
829 return code - 120;
830 }
831 let (xi, yi) = DISTANCE_MAP[code - 1];
832 let distance = yi * width as i32 + xi;
833 distance.max(1) as usize
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839
840 #[test]
841 fn bits_come_out_low_bit_first() {
842 let mut bits = BitReader::new(&[0b1010_0110, 0xff]);
843 assert_eq!(bits.read(1), 0);
844 assert_eq!(bits.read(2), 0b11);
845 assert_eq!(bits.read(5), 0b1_0100);
846 assert_eq!(bits.read(8), 0xff);
847 assert!(!bits.exhausted());
848 bits.read(1);
849 assert!(bits.exhausted());
850 }
851
852 #[test]
853 fn a_canonical_code_decodes_its_own_symbols() {
854 // Lengths 1,2,3,3 -> codes 0, 10, 110, 111.
855 let code = Huffman::from_lengths(&[1, 2, 3, 3]).unwrap();
856 let mut bits = BitReader::new(&[0b1101_1100, 0b0000_0001]);
857 // Bits low-first: 0,0,1,1,1,0,1,1 -> symbol 0, then 110 -> 2 ...
858 assert_eq!(code.decode(&mut bits).unwrap(), 0);
859 assert_eq!(code.decode(&mut bits).unwrap(), 0);
860 assert_eq!(code.decode(&mut bits).unwrap(), 3);
861 }
862
863 #[test]
864 fn an_incomplete_code_is_refused() {
865 assert!(Huffman::from_lengths(&[1, 2, 3]).is_err());
866 assert!(Huffman::from_lengths(&[1, 1, 1, 1]).is_err());
867 assert!(Huffman::from_lengths(&[0, 0]).is_err());
868 // A single leaf is legal and consumes no bits.
869 let single = Huffman::from_lengths(&[0, 1, 0]).unwrap();
870 let mut bits = BitReader::new(&[]);
871 assert_eq!(single.decode(&mut bits).unwrap(), 1);
872 }
873
874 #[test]
875 fn distance_codes_map_into_the_neighbourhood() {
876 // Code 1 is the pixel directly above; code 2 the one to the left.
877 assert_eq!(map_distance(1, 16), 16);
878 assert_eq!(map_distance(2, 16), 1);
879 assert_eq!(map_distance(121, 16), 1);
880 // Every mapped distance must be at least one pixel back.
881 for code in 1..=120 {
882 assert!(map_distance(code, 4) >= 1, "code {code}");
883 }
884 }
885
886 #[test]
887 fn the_predictors_agree_with_their_definitions() {
888 let l = 0xff20_4060;
889 let t = 0xff40_6080;
890 let tl = 0xff10_2030;
891 assert_eq!(predict(1, l, t, tl, 0), l);
892 assert_eq!(predict(2, l, t, tl, 0), t);
893 assert_eq!(predict(7, l, t, tl, 0), 0xff30_5070);
894 assert_eq!(predict(12, l, t, tl, 0), clamp_add_subtract_full(l, t, tl));
895 assert_eq!(predict(99, l, t, tl, 0), 0xff00_0000);
896 }
897}