forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

vp8.rs1617 lines, 50.3 KiBHistoryRawDownload
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
14use super::vp8_tables::{
15 AC_QLOOKUP, COEFF_BANDS, COEFF_UPDATE_PROBS, DC_QLOOKUP, DEFAULT_COEFF_PROBS, KF_BMODE_PROBS,
16 ZIGZAG,
17};
18use crate::Limits;
19use ec_core::{Error, Result};
20
21/// 16x16 luma / 8x8 chroma prediction modes.
22const DC_PRED: usize = 0;
23const V_PRED: usize = 1;
24const H_PRED: usize = 2;
25const TM_PRED: usize = 3;
26const 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).
30const KF_YMODE_TREE: [i8; 8] = [-(B_PRED as i8), 2, 4, 6, 0, -1, -2, -3];
31const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128];
32const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3];
33const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183];
34const BMODE_TREE: [i8; 18] = [
35 0, 2, -1, 4, -2, 6, 8, 12, -3, 10, -5, -6, -4, 14, -7, 16, -8, -9,
36];
37const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3];
38const 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.
43const 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.
52const CAT_BASE: [i32; 6] = [5, 7, 11, 19, 35, 67];
53
54/// Subblock modes, in the enumeration order the trees and tables use.
55const B_DC_PRED: usize = 0;
56const B_TM_PRED: usize = 1;
57const B_VE_PRED: usize = 2;
58const B_HE_PRED: usize = 3;
59
60/// The boolean entropy decoder of RFC 6386 section 7.3.
61pub struct BoolDecoder<'a> {
62 data: &'a [u8],
63 at: usize,
64 range: u32,
65 value: u32,
66 bit_count: i32,
67}
68
69impl<'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)]
162struct Dequant {
163 y: [i32; 2],
164 y2: [i32; 2],
165 uv: [i32; 2],
166}
167
168/// Everything the frame header set up.
169struct 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)]
189struct 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.
196pub 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.
214pub 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.
234pub 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.
376fn 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
482fn clamp_q(q: i32) -> usize {
483 q.clamp(0, 127) as usize
484}
485
486fn dc_q(q: i32) -> i32 {
487 DC_QLOOKUP[clamp_q(q)]
488}
489
490fn 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.
495fn 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)]
518fn 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.
585fn 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.
634fn 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
658const COS_PI8_SQRT2_MINUS1: i64 = 20091;
659const SIN_PI8_SQRT2: i64 = 35468;
660
661/// The 4x4 inverse DCT of RFC 6386 section 14.4, bit-exact as specified.
662///
663/// The arithmetic runs in i64: a hostile block's coefficients can push the second
664/// pass past i32, and a valid stream never gets near that range, so the result on
665/// every valid block is unchanged.
666fn inverse_dct(block: &[i16; 16]) -> [i32; 16] {
667 let mut tmp = [0i64; 16];
668 for i in 0..4 {
669 let ip = |k: usize| i64::from(block[k * 4 + i]);
670 let a1 = ip(0) + ip(2);
671 let b1 = ip(0) - ip(2);
672 let t1 = (ip(1) * SIN_PI8_SQRT2) >> 16;
673 let t2 = ip(3) + ((ip(3) * COS_PI8_SQRT2_MINUS1) >> 16);
674 let c1 = t1 - t2;
675 let t1 = ip(1) + ((ip(1) * COS_PI8_SQRT2_MINUS1) >> 16);
676 let t2 = (ip(3) * SIN_PI8_SQRT2) >> 16;
677 let d1 = t1 + t2;
678 tmp[i] = a1 + d1;
679 tmp[12 + i] = a1 - d1;
680 tmp[4 + i] = b1 + c1;
681 tmp[8 + i] = b1 - c1;
682 }
683 let mut out = [0i64; 16];
684 for i in 0..4 {
685 let ip = |k: usize| tmp[i * 4 + k];
686 let a1 = ip(0) + ip(2);
687 let b1 = ip(0) - ip(2);
688 let t1 = (ip(1) * SIN_PI8_SQRT2) >> 16;
689 let t2 = ip(3) + ((ip(3) * COS_PI8_SQRT2_MINUS1) >> 16);
690 let c1 = t1 - t2;
691 let t1 = ip(1) + ((ip(1) * COS_PI8_SQRT2_MINUS1) >> 16);
692 let t2 = (ip(3) * SIN_PI8_SQRT2) >> 16;
693 let d1 = t1 + t2;
694 out[i * 4] = (a1 + d1 + 4) >> 3;
695 out[i * 4 + 3] = (a1 - d1 + 4) >> 3;
696 out[i * 4 + 1] = (b1 + c1 + 4) >> 3;
697 out[i * 4 + 2] = (b1 - c1 + 4) >> 3;
698 }
699 // Every residue a valid stream produces fits in i32 after the shift.
700 out.map(|v| v as i32)
701}
702
703/// The macroblock's working buffer: one row of "above" pixels (with the four
704/// above-right ones a subblock may reach for) and one column of "left" ones,
705/// surrounding the 16x16 luma and 8x8 chroma blocks being built.
706struct Work {
707 y: [[u8; 21]; 17],
708 u: [[u8; 9]; 9],
709 v: [[u8; 9]; 9],
710}
711
712#[allow(clippy::too_many_arguments)]
713fn reconstruct(
714 frame: &mut Frame,
715 mb_x: usize,
716 mb_y: usize,
717 mb_cols: usize,
718 _mb_rows: usize,
719 y_mode: usize,
720 uv_mode: usize,
721 bmodes: &[usize; 16],
722 coeffs: &mut [[i16; 16]; 25],
723 has_y2: bool,
724) {
725 if has_y2 {
726 let y2 = coeffs[24];
727 inverse_wht(&y2, coeffs);
728 }
729 let mut work = Work {
730 y: [[0; 21]; 17],
731 u: [[0; 9]; 9],
732 v: [[0; 9]; 9],
733 };
734 load_edges(frame, &mut work, mb_x, mb_y, mb_cols);
735
736 if y_mode == B_PRED {
737 for by in 0..4 {
738 for bx in 0..4 {
739 predict_subblock(&mut work, bx, by, bmodes[by * 4 + bx]);
740 add_residual_4x4(&mut work.y, by * 4 + 1, bx * 4 + 1, &coeffs[by * 4 + bx]);
741 }
742 }
743 } else {
744 predict_luma_16x16(&mut work, y_mode, mb_x, mb_y);
745 for by in 0..4 {
746 for bx in 0..4 {
747 add_residual_4x4(&mut work.y, by * 4 + 1, bx * 4 + 1, &coeffs[by * 4 + bx]);
748 }
749 }
750 }
751 predict_chroma(&mut work, uv_mode, mb_x, mb_y);
752 for by in 0..2 {
753 for bx in 0..2 {
754 add_residual_4x4_c(
755 &mut work.u,
756 by * 4 + 1,
757 bx * 4 + 1,
758 &coeffs[16 + by * 2 + bx],
759 );
760 add_residual_4x4_c(
761 &mut work.v,
762 by * 4 + 1,
763 bx * 4 + 1,
764 &coeffs[20 + by * 2 + bx],
765 );
766 }
767 }
768 store_macroblock(frame, &work, mb_x, mb_y);
769}
770
771/// Fill the working buffer's borders from the already-reconstructed frame,
772/// using 127 above the picture and 129 to its left as the format requires.
773fn load_edges(frame: &Frame, work: &mut Work, mb_x: usize, mb_y: usize, mb_cols: usize) {
774 let sy = frame.stride_y;
775 let suv = frame.stride_uv;
776 // Luma above row plus four above-right pixels.
777 if mb_y == 0 {
778 work.y[0] = [127; 21];
779 } else {
780 let row = (mb_y * 16 - 1) * sy;
781 work.y[0][0] = if mb_x == 0 {
782 129
783 } else {
784 frame.y[row + mb_x * 16 - 1]
785 };
786 for i in 0..16 {
787 work.y[0][1 + i] = frame.y[row + mb_x * 16 + i];
788 }
789 for i in 0..4 {
790 work.y[0][17 + i] = if mb_x + 1 < mb_cols {
791 frame.y[row + mb_x * 16 + 16 + i]
792 } else {
793 // The rightmost macroblock reuses the last visible pixel of
794 // the row above, per section 12.3.
795 frame.y[row + mb_x * 16 + 15]
796 };
797 }
798 }
799 for r in 0..16 {
800 work.y[r + 1][0] = if mb_x == 0 {
801 129
802 } else {
803 frame.y[(mb_y * 16 + r) * sy + mb_x * 16 - 1]
804 };
805 }
806 // Chroma above rows and left columns.
807 for (plane, buf) in [(&frame.u, &mut work.u), (&frame.v, &mut work.v)] {
808 if mb_y == 0 {
809 buf[0] = [127; 9];
810 } else {
811 let row = (mb_y * 8 - 1) * suv;
812 buf[0][0] = if mb_x == 0 {
813 129
814 } else {
815 plane[row + mb_x * 8 - 1]
816 };
817 for i in 0..8 {
818 buf[0][1 + i] = plane[row + mb_x * 8 + i];
819 }
820 }
821 for r in 0..8 {
822 buf[r + 1][0] = if mb_x == 0 {
823 129
824 } else {
825 plane[(mb_y * 8 + r) * suv + mb_x * 8 - 1]
826 };
827 }
828 }
829}
830
831fn store_macroblock(frame: &mut Frame, work: &Work, mb_x: usize, mb_y: usize) {
832 let sy = frame.stride_y;
833 let suv = frame.stride_uv;
834 for r in 0..16 {
835 let dst = (mb_y * 16 + r) * sy + mb_x * 16;
836 frame.y[dst..dst + 16].copy_from_slice(&work.y[r + 1][1..17]);
837 }
838 for r in 0..8 {
839 let dst = (mb_y * 8 + r) * suv + mb_x * 8;
840 frame.u[dst..dst + 8].copy_from_slice(&work.u[r + 1][1..9]);
841 frame.v[dst..dst + 8].copy_from_slice(&work.v[r + 1][1..9]);
842 }
843}
844
845fn add_residual_4x4(buf: &mut [[u8; 21]; 17], row: usize, col: usize, block: &[i16; 16]) {
846 if block.iter().all(|&c| c == 0) {
847 return;
848 }
849 let residue = inverse_dct(block);
850 for r in 0..4 {
851 for c in 0..4 {
852 let v = i32::from(buf[row + r][col + c]) + residue[r * 4 + c];
853 buf[row + r][col + c] = v.clamp(0, 255) as u8;
854 }
855 }
856}
857
858fn add_residual_4x4_c(buf: &mut [[u8; 9]; 9], row: usize, col: usize, block: &[i16; 16]) {
859 if block.iter().all(|&c| c == 0) {
860 return;
861 }
862 let residue = inverse_dct(block);
863 for r in 0..4 {
864 for c in 0..4 {
865 let v = i32::from(buf[row + r][col + c]) + residue[r * 4 + c];
866 buf[row + r][col + c] = v.clamp(0, 255) as u8;
867 }
868 }
869}
870
871/// DC prediction's rounded average, over whichever edges exist.
872fn dc_value(above: &[u8], left: &[u8], have_above: bool, have_left: bool) -> u8 {
873 let mut sum = 0u32;
874 let mut count = 0u32;
875 if have_above {
876 sum += above.iter().map(|&p| u32::from(p)).sum::<u32>();
877 count += above.len() as u32;
878 }
879 if have_left {
880 sum += left.iter().map(|&p| u32::from(p)).sum::<u32>();
881 count += left.len() as u32;
882 }
883 if count == 0 {
884 return 128;
885 }
886 let shift = count.trailing_zeros();
887 ((sum + (1 << (shift - 1))) >> shift) as u8
888}
889
890fn predict_luma_16x16(work: &mut Work, mode: usize, mb_x: usize, mb_y: usize) {
891 let above: Vec<u8> = work.y[0][1..17].to_vec();
892 let left: Vec<u8> = (0..16).map(|r| work.y[r + 1][0]).collect();
893 let corner = work.y[0][0];
894 let dc = dc_value(&above, &left, mb_y > 0, mb_x > 0);
895 for r in 0..16 {
896 for c in 0..16 {
897 work.y[r + 1][c + 1] = match mode {
898 V_PRED => above[c],
899 H_PRED => left[r],
900 TM_PRED => (i32::from(left[r]) + i32::from(above[c]) - i32::from(corner))
901 .clamp(0, 255) as u8,
902 DC_PRED => dc,
903 _ => dc,
904 };
905 }
906 }
907}
908
909fn predict_chroma(work: &mut Work, mode: usize, mb_x: usize, mb_y: usize) {
910 for buf in [&mut work.u, &mut work.v] {
911 let above: Vec<u8> = buf[0][1..9].to_vec();
912 let left: Vec<u8> = (0..8).map(|r| buf[r + 1][0]).collect();
913 let corner = buf[0][0];
914 let dc = dc_value(&above, &left, mb_y > 0, mb_x > 0);
915 for r in 0..8 {
916 for c in 0..8 {
917 buf[r + 1][c + 1] = match mode {
918 V_PRED => above[c],
919 H_PRED => left[r],
920 TM_PRED => (i32::from(left[r]) + i32::from(above[c]) - i32::from(corner))
921 .clamp(0, 255) as u8,
922 DC_PRED => dc,
923 _ => dc,
924 };
925 }
926 }
927 }
928}
929
930fn avg3(x: u8, y: u8, z: u8) -> u8 {
931 ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8
932}
933
934fn avg2(x: u8, y: u8) -> u8 {
935 ((u32::from(x) + u32::from(y) + 1) >> 1) as u8
936}
937
938/// The ten 4x4 subblock predictions of section 12.3.
939fn predict_subblock(work: &mut Work, bx: usize, by: usize, mode: usize) {
940 let row = by * 4;
941 let col = bx * 4;
942 // A[-1] is P; A[0..8] the above row and its four right-hand neighbours.
943 let mut a = [0u8; 9];
944 a[0] = work.y[row][col];
945 for i in 0..8 {
946 // Subblocks on the macroblock's right edge take their above-right from
947 // row -1 whatever their own row is: the pixels to their upper right
948 // have not been reconstructed yet.
949 a[1 + i] = if bx == 3 && i >= 4 {
950 work.y[0][17 + (i - 4)]
951 } else {
952 work.y[row][col + 1 + i]
953 };
954 }
955 let l = [
956 work.y[row + 1][col],
957 work.y[row + 2][col],
958 work.y[row + 3][col],
959 work.y[row + 4][col],
960 ];
961 let p = a[0];
962 let above = &a[1..9];
963 // E[0..9]: the left column reversed, then P, then the above row.
964 let e = [
965 l[3], l[2], l[1], l[0], p, above[0], above[1], above[2], above[3],
966 ];
967 let mut b = [[0u8; 4]; 4];
968 match mode {
969 B_DC_PRED => {
970 let mut v = 4u32;
971 for i in 0..4 {
972 v += u32::from(above[i]) + u32::from(l[i]);
973 }
974 let v = (v >> 3) as u8;
975 b = [[v; 4]; 4];
976 }
977 B_TM_PRED => {
978 for r in 0..4 {
979 for c in 0..4 {
980 b[r][c] =
981 (i32::from(l[r]) + i32::from(above[c]) - i32::from(p)).clamp(0, 255) as u8;
982 }
983 }
984 }
985 B_VE_PRED => {
986 for c in 0..4 {
987 let v = avg3(
988 if c == 0 { p } else { above[c - 1] },
989 above[c],
990 above[c + 1],
991 );
992 for r in 0..4 {
993 b[r][c] = v;
994 }
995 }
996 }
997 B_HE_PRED => {
998 let values = [
999 avg3(p, l[0], l[1]),
1000 avg3(l[0], l[1], l[2]),
1001 avg3(l[1], l[2], l[3]),
1002 avg3(l[2], l[3], l[3]),
1003 ];
1004 for r in 0..4 {
1005 b[r] = [values[r]; 4];
1006 }
1007 }
1008 4 => {
1009 // B_LD_PRED: 45 degrees down-left.
1010 let d = |i: usize| avg3(above[i - 1], above[i], above[i + 1]);
1011 b[0][0] = d(1);
1012 b[0][1] = d(2);
1013 b[1][0] = d(2);
1014 b[0][2] = d(3);
1015 b[1][1] = d(3);
1016 b[2][0] = d(3);
1017 b[0][3] = d(4);
1018 b[1][2] = d(4);
1019 b[2][1] = d(4);
1020 b[3][0] = d(4);
1021 b[1][3] = d(5);
1022 b[2][2] = d(5);
1023 b[3][1] = d(5);
1024 b[2][3] = d(6);
1025 b[3][2] = d(6);
1026 b[3][3] = avg3(above[6], above[7], above[7]);
1027 }
1028 5 => {
1029 // B_RD_PRED: 45 degrees down-right.
1030 let d = |i: usize| avg3(e[i - 1], e[i], e[i + 1]);
1031 b[3][0] = d(1);
1032 b[3][1] = d(2);
1033 b[2][0] = d(2);
1034 b[3][2] = d(3);
1035 b[2][1] = d(3);
1036 b[1][0] = d(3);
1037 b[3][3] = d(4);
1038 b[2][2] = d(4);
1039 b[1][1] = d(4);
1040 b[0][0] = d(4);
1041 b[2][3] = d(5);
1042 b[1][2] = d(5);
1043 b[0][1] = d(5);
1044 b[1][3] = d(6);
1045 b[0][2] = d(6);
1046 b[0][3] = d(7);
1047 }
1048 6 => {
1049 // B_VR_PRED.
1050 let d3 = |i: usize| avg3(e[i - 1], e[i], e[i + 1]);
1051 let d2 = |i: usize| avg2(e[i], e[i + 1]);
1052 b[3][0] = d3(2);
1053 b[2][0] = d3(3);
1054 b[3][1] = d3(4);
1055 b[1][0] = d3(4);
1056 b[2][1] = d2(4);
1057 b[0][0] = d2(4);
1058 b[3][2] = d3(5);
1059 b[1][1] = d3(5);
1060 b[2][2] = d2(5);
1061 b[0][1] = d2(5);
1062 b[3][3] = d3(6);
1063 b[1][2] = d3(6);
1064 b[2][3] = d2(6);
1065 b[0][2] = d2(6);
1066 b[1][3] = d3(7);
1067 b[0][3] = d2(7);
1068 }
1069 7 => {
1070 // B_VL_PRED.
1071 let d3 = |i: usize| avg3(above[i - 1], above[i], above[i + 1]);
1072 let d2 = |i: usize| avg2(above[i], above[i + 1]);
1073 b[0][0] = d2(0);
1074 b[1][0] = d3(1);
1075 b[2][0] = d2(1);
1076 b[0][1] = d2(1);
1077 b[1][1] = d3(2);
1078 b[3][0] = d3(2);
1079 b[2][1] = d2(2);
1080 b[0][2] = d2(2);
1081 b[3][1] = d3(3);
1082 b[1][2] = d3(3);
1083 b[2][2] = d2(3);
1084 b[0][3] = d2(3);
1085 b[3][2] = d3(4);
1086 b[1][3] = d3(4);
1087 b[2][3] = d3(5);
1088 b[3][3] = d3(6);
1089 }
1090 8 => {
1091 // B_HD_PRED.
1092 let d3 = |i: usize| avg3(e[i - 1], e[i], e[i + 1]);
1093 let d2 = |i: usize| avg2(e[i], e[i + 1]);
1094 b[3][0] = d2(0);
1095 b[3][1] = d3(1);
1096 b[2][0] = d2(1);
1097 b[3][2] = d2(1);
1098 b[2][1] = d3(2);
1099 b[3][3] = d3(2);
1100 b[2][2] = d2(2);
1101 b[1][0] = d2(2);
1102 b[2][3] = d3(3);
1103 b[1][1] = d3(3);
1104 b[1][2] = d2(3);
1105 b[0][0] = d2(3);
1106 b[1][3] = d3(4);
1107 b[0][1] = d3(4);
1108 b[0][2] = d3(5);
1109 b[0][3] = d3(6);
1110 }
1111 _ => {
1112 // B_HU_PRED.
1113 b[0][0] = avg2(l[0], l[1]);
1114 b[0][1] = avg3(l[0], l[1], l[2]);
1115 b[0][2] = avg2(l[1], l[2]);
1116 b[1][0] = avg2(l[1], l[2]);
1117 b[0][3] = avg3(l[1], l[2], l[3]);
1118 b[1][1] = avg3(l[1], l[2], l[3]);
1119 b[1][2] = avg2(l[2], l[3]);
1120 b[2][0] = avg2(l[2], l[3]);
1121 b[1][3] = avg3(l[2], l[3], l[3]);
1122 b[2][1] = avg3(l[2], l[3], l[3]);
1123 b[2][2] = l[3];
1124 b[2][3] = l[3];
1125 b[3][0] = l[3];
1126 b[3][1] = l[3];
1127 b[3][2] = l[3];
1128 b[3][3] = l[3];
1129 }
1130 }
1131 for r in 0..4 {
1132 for c in 0..4 {
1133 work.y[row + 1 + r][col + 1 + c] = b[r][c];
1134 }
1135 }
1136}
1137
1138// ---- Loop filter (section 15) --------------------------------------------
1139
1140fn c8(v: i32) -> i32 {
1141 v.clamp(-128, 127)
1142}
1143
1144fn u2s(v: u8) -> i32 {
1145 i32::from(v) - 128
1146}
1147
1148fn s2u(v: i32) -> u8 {
1149 (c8(v) + 128) as u8
1150}
1151
1152/// The shared 2-or-4-tap adjustment; returns the value the wider filters need.
1153fn common_adjust(use_outer: bool, plane: &mut [u8], q0: usize, step: usize) -> i32 {
1154 let p1 = u2s(plane[q0 - 2 * step]);
1155 let p0 = u2s(plane[q0 - step]);
1156 let q0v = u2s(plane[q0]);
1157 let q1 = u2s(plane[q0 + step]);
1158 let a = c8((if use_outer { c8(p1 - q1) } else { 0 }) + 3 * (q0v - p0));
1159 let b = c8(a + 3) >> 3;
1160 let a = c8(a + 4) >> 3;
1161 plane[q0] = s2u(q0v - a);
1162 plane[q0 - step] = s2u(p0 + b);
1163 a
1164}
1165
1166fn simple_segment(edge_limit: i32, plane: &mut [u8], q0: usize, step: usize) {
1167 let p1 = i32::from(plane[q0 - 2 * step]);
1168 let p0 = i32::from(plane[q0 - step]);
1169 let q0v = i32::from(plane[q0]);
1170 let q1 = i32::from(plane[q0 + step]);
1171 if (p0 - q0v).abs() * 2 + (p1 - q1).abs() / 2 <= edge_limit {
1172 common_adjust(true, plane, q0, step);
1173 }
1174}
1175
1176fn filter_yes(interior: i32, edge: i32, plane: &[u8], q0: usize, step: usize) -> bool {
1177 let at = |k: i32| i32::from(plane[(q0 as i32 + k * step as i32) as usize]);
1178 let (p3, p2, p1, p0) = (at(-4), at(-3), at(-2), at(-1));
1179 let (q0v, q1, q2, q3) = (at(0), at(1), at(2), at(3));
1180 (p0 - q0v).abs() * 2 + (p1 - q1).abs() / 2 <= edge
1181 && (p3 - p2).abs() <= interior
1182 && (p2 - p1).abs() <= interior
1183 && (p1 - p0).abs() <= interior
1184 && (q3 - q2).abs() <= interior
1185 && (q2 - q1).abs() <= interior
1186 && (q1 - q0v).abs() <= interior
1187}
1188
1189fn hev(threshold: i32, plane: &[u8], q0: usize, step: usize) -> bool {
1190 let at = |k: i32| i32::from(plane[(q0 as i32 + k * step as i32) as usize]);
1191 (at(-2) - at(-1)).abs() > threshold || (at(1) - at(0)).abs() > threshold
1192}
1193
1194fn subblock_filter(
1195 hev_threshold: i32,
1196 interior: i32,
1197 edge: i32,
1198 plane: &mut [u8],
1199 q0: usize,
1200 step: usize,
1201) {
1202 if !filter_yes(interior, edge, plane, q0, step) {
1203 return;
1204 }
1205 let high = hev(hev_threshold, plane, q0, step);
1206 let a = (common_adjust(high, plane, q0, step) + 1) >> 1;
1207 if !high {
1208 let q1 = u2s(plane[q0 + step]);
1209 let p1 = u2s(plane[q0 - 2 * step]);
1210 plane[q0 + step] = s2u(q1 - a);
1211 plane[q0 - 2 * step] = s2u(p1 + a);
1212 }
1213}
1214
1215fn mb_filter(
1216 hev_threshold: i32,
1217 interior: i32,
1218 edge: i32,
1219 plane: &mut [u8],
1220 q0: usize,
1221 step: usize,
1222) {
1223 if !filter_yes(interior, edge, plane, q0, step) {
1224 return;
1225 }
1226 if hev(hev_threshold, plane, q0, step) {
1227 common_adjust(true, plane, q0, step);
1228 return;
1229 }
1230 let p2 = u2s(plane[q0 - 3 * step]);
1231 let p1 = u2s(plane[q0 - 2 * step]);
1232 let p0 = u2s(plane[q0 - step]);
1233 let q0v = u2s(plane[q0]);
1234 let q1 = u2s(plane[q0 + step]);
1235 let q2 = u2s(plane[q0 + 2 * step]);
1236 let w = c8(c8(p1 - q1) + 3 * (q0v - p0));
1237 let a = c8((27 * w + 63) >> 7);
1238 plane[q0] = s2u(q0v - a);
1239 plane[q0 - step] = s2u(p0 + a);
1240 let a = c8((18 * w + 63) >> 7);
1241 plane[q0 + step] = s2u(q1 - a);
1242 plane[q0 - 2 * step] = s2u(p1 + a);
1243 let a = c8((9 * w + 63) >> 7);
1244 plane[q0 + 2 * step] = s2u(q2 - a);
1245 plane[q0 - 3 * step] = s2u(p2 + a);
1246}
1247
1248/// Per-macroblock filter strength, exactly as section 15.4 derives it.
1249fn filter_parameters(header: &Header, info: &MbInfo) -> (i32, i32, i32) {
1250 let mut level = header.filter_level;
1251 if header.segmentation {
1252 level = if header.segment_lf_absolute {
1253 header.segment_lf[info.segment]
1254 } else {
1255 level + header.segment_lf[info.segment]
1256 };
1257 }
1258 level = level.clamp(0, 63);
1259 if header.delta_enabled {
1260 // A key frame's every macroblock references the current frame, so the
1261 // reference delta is always index 0 and the mode delta only applies to
1262 // B_PRED.
1263 level += header.ref_delta[0];
1264 if info.y_mode == B_PRED {
1265 level += header.mode_delta[0];
1266 }
1267 }
1268 let level = level.clamp(0, 63);
1269 let mut interior = level;
1270 if header.sharpness > 0 {
1271 interior >>= if header.sharpness > 4 { 2 } else { 1 };
1272 interior = interior.min(9 - header.sharpness);
1273 }
1274 interior = interior.max(1);
1275 let mut hev_threshold = i32::from(level >= 15);
1276 if level >= 40 {
1277 hev_threshold += 1;
1278 }
1279 (level, interior, hev_threshold)
1280}
1281
1282fn loop_filter(
1283 frame: &mut Frame,
1284 header: &Header,
1285 infos: &[MbInfo],
1286 mb_cols: usize,
1287 mb_rows: usize,
1288) {
1289 let sy = frame.stride_y;
1290 let suv = frame.stride_uv;
1291 for mb_y in 0..mb_rows {
1292 for mb_x in 0..mb_cols {
1293 let info = infos[mb_y * mb_cols + mb_x];
1294 let (level, interior, hev_threshold) = filter_parameters(header, &info);
1295 if level == 0 {
1296 continue;
1297 }
1298 let mb_edge = (level + 2) * 2 + interior;
1299 let sub_edge = level * 2 + interior;
1300 // Interior edges are skipped where the macroblock has no residue
1301 // and predicts as a whole; nothing there can have a block edge.
1302 let skip_interior = !info.has_coeffs && info.y_mode != B_PRED;
1303 let (yx, yy) = (mb_x * 16, mb_y * 16);
1304 let (cx, cy) = (mb_x * 8, mb_y * 8);
1305
1306 if header.filter_simple {
1307 if mb_x > 0 {
1308 for r in 0..16 {
1309 simple_segment(mb_edge, &mut frame.y, (yy + r) * sy + yx, 1);
1310 }
1311 }
1312 if !skip_interior {
1313 for c in [4, 8, 12] {
1314 for r in 0..16 {
1315 simple_segment(sub_edge, &mut frame.y, (yy + r) * sy + yx + c, 1);
1316 }
1317 }
1318 }
1319 if mb_y > 0 {
1320 for c in 0..16 {
1321 simple_segment(mb_edge, &mut frame.y, yy * sy + yx + c, sy);
1322 }
1323 }
1324 if !skip_interior {
1325 for r in [4, 8, 12] {
1326 for c in 0..16 {
1327 simple_segment(sub_edge, &mut frame.y, (yy + r) * sy + yx + c, sy);
1328 }
1329 }
1330 }
1331 continue;
1332 }
1333
1334 if mb_x > 0 {
1335 for r in 0..16 {
1336 mb_filter(
1337 hev_threshold,
1338 interior,
1339 mb_edge,
1340 &mut frame.y,
1341 (yy + r) * sy + yx,
1342 1,
1343 );
1344 }
1345 for r in 0..8 {
1346 mb_filter(
1347 hev_threshold,
1348 interior,
1349 mb_edge,
1350 &mut frame.u,
1351 (cy + r) * suv + cx,
1352 1,
1353 );
1354 mb_filter(
1355 hev_threshold,
1356 interior,
1357 mb_edge,
1358 &mut frame.v,
1359 (cy + r) * suv + cx,
1360 1,
1361 );
1362 }
1363 }
1364 if !skip_interior {
1365 for c in [4, 8, 12] {
1366 for r in 0..16 {
1367 subblock_filter(
1368 hev_threshold,
1369 interior,
1370 sub_edge,
1371 &mut frame.y,
1372 (yy + r) * sy + yx + c,
1373 1,
1374 );
1375 }
1376 }
1377 for r in 0..8 {
1378 subblock_filter(
1379 hev_threshold,
1380 interior,
1381 sub_edge,
1382 &mut frame.u,
1383 (cy + r) * suv + cx + 4,
1384 1,
1385 );
1386 subblock_filter(
1387 hev_threshold,
1388 interior,
1389 sub_edge,
1390 &mut frame.v,
1391 (cy + r) * suv + cx + 4,
1392 1,
1393 );
1394 }
1395 }
1396 if mb_y > 0 {
1397 for c in 0..16 {
1398 mb_filter(
1399 hev_threshold,
1400 interior,
1401 mb_edge,
1402 &mut frame.y,
1403 yy * sy + yx + c,
1404 sy,
1405 );
1406 }
1407 for c in 0..8 {
1408 mb_filter(
1409 hev_threshold,
1410 interior,
1411 mb_edge,
1412 &mut frame.u,
1413 cy * suv + cx + c,
1414 suv,
1415 );
1416 mb_filter(
1417 hev_threshold,
1418 interior,
1419 mb_edge,
1420 &mut frame.v,
1421 cy * suv + cx + c,
1422 suv,
1423 );
1424 }
1425 }
1426 if !skip_interior {
1427 for r in [4, 8, 12] {
1428 for c in 0..16 {
1429 subblock_filter(
1430 hev_threshold,
1431 interior,
1432 sub_edge,
1433 &mut frame.y,
1434 (yy + r) * sy + yx + c,
1435 sy,
1436 );
1437 }
1438 }
1439 for c in 0..8 {
1440 subblock_filter(
1441 hev_threshold,
1442 interior,
1443 sub_edge,
1444 &mut frame.u,
1445 (cy + 4) * suv + cx + c,
1446 suv,
1447 );
1448 subblock_filter(
1449 hev_threshold,
1450 interior,
1451 sub_edge,
1452 &mut frame.v,
1453 (cy + 4) * suv + cx + c,
1454 suv,
1455 );
1456 }
1457 }
1458 }
1459 }
1460}
1461
1462#[cfg(test)]
1463mod tests {
1464 use super::*;
1465
1466 /// The encoder of RFC 6386 section 7.3, so the decoder can be checked
1467 /// against the thing it has to invert rather than against an assumption
1468 /// about what the bits look like.
1469 struct BoolEncoder {
1470 out: Vec<u8>,
1471 range: u32,
1472 bottom: u32,
1473 bit_count: i32,
1474 }
1475
1476 impl BoolEncoder {
1477 fn new() -> BoolEncoder {
1478 BoolEncoder {
1479 out: Vec::new(),
1480 range: 255,
1481 bottom: 0,
1482 bit_count: 24,
1483 }
1484 }
1485
1486 fn carry(&mut self) {
1487 let mut i = self.out.len();
1488 while i > 0 {
1489 i -= 1;
1490 if self.out[i] == 255 {
1491 self.out[i] = 0;
1492 } else {
1493 self.out[i] += 1;
1494 return;
1495 }
1496 }
1497 }
1498
1499 fn write(&mut self, prob: u8, value: u32) {
1500 let split = 1 + (((self.range - 1) * u32::from(prob)) >> 8);
1501 if value != 0 {
1502 self.bottom += split;
1503 self.range -= split;
1504 } else {
1505 self.range = split;
1506 }
1507 while self.range < 128 {
1508 self.range <<= 1;
1509 if self.bottom & (1 << 31) != 0 {
1510 self.carry();
1511 }
1512 self.bottom <<= 1;
1513 self.bit_count -= 1;
1514 if self.bit_count == 0 {
1515 self.out.push((self.bottom >> 24) as u8);
1516 self.bottom &= (1 << 24) - 1;
1517 self.bit_count = 8;
1518 }
1519 }
1520 }
1521
1522 fn literal(&mut self, n: u32, value: u32) {
1523 for i in (0..n).rev() {
1524 self.write(128, (value >> i) & 1);
1525 }
1526 }
1527
1528 fn finish(mut self) -> Vec<u8> {
1529 let mut c = self.bit_count;
1530 let mut v = self.bottom;
1531 if v & (1u32 << (32 - c)) != 0 {
1532 self.carry();
1533 }
1534 v <<= c & 7;
1535 c >>= 3;
1536 while c > 0 {
1537 v <<= 8;
1538 c -= 1;
1539 }
1540 for _ in 0..4 {
1541 self.out.push((v >> 24) as u8);
1542 v <<= 8;
1543 }
1544 self.out
1545 }
1546 }
1547
1548 #[test]
1549 fn the_bool_decoder_inverts_the_specification_encoder() {
1550 let probs = [128u8, 1, 255, 200, 32, 145];
1551 let bits: Vec<u32> = (0..600)
1552 .map(|i: u32| (i.wrapping_mul(2_654_435_761)) >> 31)
1553 .collect();
1554 let mut encoder = BoolEncoder::new();
1555 for (i, &bit) in bits.iter().enumerate() {
1556 encoder.write(probs[i % probs.len()], bit);
1557 }
1558 encoder.literal(8, 0xb2);
1559 encoder.literal(12, 0x4d3);
1560 let data = encoder.finish();
1561
1562 let mut bd = BoolDecoder::new(&data);
1563 for (i, &bit) in bits.iter().enumerate() {
1564 assert_eq!(bd.bool(probs[i % probs.len()]), bit, "bool {i}");
1565 }
1566 assert_eq!(bd.literal(8), 0xb2);
1567 assert_eq!(bd.literal(12), 0x4d3);
1568 }
1569
1570 #[test]
1571 fn trees_decode_their_leaves() {
1572 // A stream of zero bits walks the leftmost branch of each tree.
1573 let data = [0u8; 8];
1574 let mut bd = BoolDecoder::new(&data);
1575 assert_eq!(bd.tree(&KF_YMODE_TREE, &KF_YMODE_PROBS, 0), B_PRED);
1576 let mut bd = BoolDecoder::new(&data);
1577 assert_eq!(bd.tree(&UV_MODE_TREE, &KF_UV_MODE_PROBS, 0), DC_PRED);
1578 let mut bd = BoolDecoder::new(&data);
1579 assert_eq!(bd.tree(&BMODE_TREE, &KF_BMODE_PROBS[0][0], 0), B_DC_PRED);
1580 let mut bd = BoolDecoder::new(&data);
1581 assert_eq!(
1582 bd.tree(&COEFF_TREE, &[128; 11], 0),
1583 11,
1584 "eob is the 0 branch"
1585 );
1586 }
1587
1588 #[test]
1589 fn the_inverse_dct_of_a_dc_only_block_is_flat() {
1590 let mut block = [0i16; 16];
1591 block[0] = 80;
1592 let out = inverse_dct(&block);
1593 for v in out {
1594 assert_eq!(v, 10, "DC 80 spreads to (80 + 4) >> 3 everywhere");
1595 }
1596 }
1597
1598 #[test]
1599 fn the_inverse_wht_matches_its_specification() {
1600 let mut input = [0i16; 16];
1601 input[0] = 64;
1602 let mut coeffs = [[0i16; 16]; 25];
1603 inverse_wht(&input, &mut coeffs);
1604 for block in coeffs.iter().take(16) {
1605 assert_eq!(block[0], 8, "a flat WHT spreads its DC over the 16 blocks");
1606 }
1607 }
1608
1609 #[test]
1610 fn dequant_factors_follow_the_scaling_rules() {
1611 assert_eq!(dc_q(0), 4);
1612 assert_eq!(ac_q(127), 284);
1613 // Y2 AC is scaled by 155/100 with a floor of 8, chroma DC caps at 132.
1614 assert_eq!((ac_q(0) * 155 / 100).max(8), 8);
1615 assert_eq!(dc_q(127).min(132), 132);
1616 }
1617}