forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

intra.rs1207 lines, 45.4 KiBHistoryRawDownload
1//! Intra prediction, the half of spec 7.11.2 a key frame needs.
2//!
3//! All thirteen key-frame intra modes: the seven that read no further than the
4//! row above and the column to the left of the block, and the six that steer
5//! along an angle and reach past the block's own width into the samples above
6//! its right and below its left. Whether those further samples are decoded is
7//! not this module's business -- the caller passes the samples it has, and the
8//! edge is extended by repeating the last one, which is what the decoder does
9//! with its own `BlockDecoded` bookkeeping (spec 7.11.2.2).
10
11/// The average of the neighbours (spec 7.11.2.5).
12pub const DC_PRED: u8 = 0;
13/// The row above, repeated down the block.
14pub const V_PRED: u8 = 1;
15/// The column to the left, repeated across the block.
16pub const H_PRED: u8 = 2;
17/// The two smooth predictions crossed (spec 7.11.2.6).
18pub const SMOOTH_PRED: u8 = 9;
19/// Smooth down from the row above to the bottom-left sample.
20pub const SMOOTH_V_PRED: u8 = 10;
21/// Smooth across from the column left to the top-right sample.
22pub const SMOOTH_H_PRED: u8 = 11;
23/// Whichever of above, left and the corner is nearest their gradient.
24pub const PAETH_PRED: u8 = 12;
25/// Down-left along 45 degrees.
26pub const D45_PRED: u8 = 3;
27/// Down-right along 135 degrees.
28pub const D135_PRED: u8 = 4;
29/// Down-right, steeper: 113 degrees.
30pub const D113_PRED: u8 = 5;
31/// Down-right, shallower: 157 degrees.
32pub const D157_PRED: u8 = 6;
33/// Up-right along 203 degrees.
34pub const D203_PRED: u8 = 7;
35/// Down-left, steeper: 67 degrees.
36pub const D67_PRED: u8 = 8;
37
38/// Every mode a key frame's luma block can be coded with, in the order a
39/// search should try them: the cheap ones first, so an early one is likely to
40/// be the one that survives.
41pub const KEY_FRAME_MODES: [u8; 13] = [
42 DC_PRED,
43 V_PRED,
44 H_PRED,
45 SMOOTH_PRED,
46 SMOOTH_V_PRED,
47 SMOOTH_H_PRED,
48 PAETH_PRED,
49 D45_PRED,
50 D67_PRED,
51 D113_PRED,
52 D135_PRED,
53 D157_PRED,
54 D203_PRED,
55];
56
57/// The modes that read no further than the row above and the column to the
58/// left, in the order a search should try them.
59pub const NON_DIRECTIONAL: [u8; 7] = [
60 DC_PRED,
61 V_PRED,
62 H_PRED,
63 SMOOTH_PRED,
64 SMOOTH_V_PRED,
65 SMOOTH_H_PRED,
66 PAETH_PRED,
67];
68
69/// `Sm_Weights` (spec 9.3), the blocks of the table for sides 4 to 64 laid end
70/// to end so that the weights for a side start at that side's own index.
71const SM_WEIGHTS: [u16; 128] = [
72 0, 0, // unused: a side is at least 2
73 255, 128, // 2
74 255, 149, 85, 64, // 4
75 255, 197, 146, 105, 73, 50, 37, 32, // 8
76 255, 225, 196, 170, 145, 123, 102, 84, 68, 54, 43, 33, 26, 20, 17, 16, // 16
77 255, 240, 225, 210, 196, 182, 169, 157, 145, 133, 122, 111, 101, 92, 83, 74, 66, 59, 52, 45,
78 39, 34, 29, 25, 21, 17, 14, 12, 10, 9, 8, 8, // 32
79 255, 248, 240, 233, 225, 218, 210, 203, 196, 189, 182, 176, 169, 163, 156, 150, 144, 138, 133,
80 127, 121, 116, 111, 106, 101, 96, 91, 86, 82, 77, 73, 69, 65, 61, 57, 54, 50, 47, 44, 41, 38,
81 35, 32, 29, 27, 25, 22, 20, 18, 16, 15, 13, 12, 10, 9, 8, 7, 6, 6, 5, 5, 4, 4, 4, // 64
82];
83
84/// `Round2` (spec 4.7): halves round up.
85fn round2(value: i32, shift: u32) -> i32 {
86 (value + (1 << (shift - 1))) >> shift
87}
88
89/// `Dr_Intra_Derivative` (spec 9.3): how far along the edge one row of the
90/// block moves, in 64ths of a sample, for the angles a delta can reach.
91fn dr_intra_derivative(angle: u16) -> i32 {
92 match angle {
93 3 => 1023,
94 6 => 547,
95 9 => 372,
96 14 => 273,
97 17 => 215,
98 20 => 178,
99 23 => 151,
100 26 => 132,
101 29 => 116,
102 32 => 102,
103 36 => 90,
104 39 => 80,
105 42 => 71,
106 45 => 64,
107 48 => 57,
108 51 => 51,
109 54 => 45,
110 58 => 40,
111 61 => 35,
112 64 => 31,
113 67 => 27,
114 70 => 23,
115 73 => 19,
116 76 => 15,
117 81 => 11,
118 84 => 7,
119 87 => 3,
120 other => panic!("no derivative is tabulated for {other} degrees"),
121 }
122}
123
124/// `Mode_To_Angle` (spec 9.3), zero for the modes that have no angle.
125const MODE_TO_ANGLE: [u16; 13] = [0, 90, 180, 45, 135, 113, 157, 203, 67, 0, 0, 0, 0];
126
127/// `ANGLE_STEP` (spec 9.3): degrees per unit of `angle_delta`, whose own
128/// range is `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA` (`MAX_ANGLE_DELTA == 3`).
129const ANGLE_STEP: i32 = 3;
130
131/// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2):
132/// a side that does not exist is filled from the side that does, a side that
133/// runs out is extended by repeating its last sample, and the corner falls back
134/// the same way.
135///
136/// Both arrays hold the corner first, so the spec's index `-1` is index 0 here
137/// and they run out to the spec's `w + h - 1`.
138struct Edges {
139 above: Vec<i32>,
140 left: Vec<i32>,
141}
142
143impl Edges {
144 /// `bw + bh` is the reach both `av1_dr_prediction_z1_c`'s `max_base_x`
145 /// and `z3_c`'s `max_base_y` use (libaom `reconintra.c`) -- above and
146 /// left both extend that far regardless of which of `bw`/`bh` is larger.
147 fn build(
148 above: Option<&[u16]>,
149 left: Option<&[u16]>,
150 corner: Option<u16>,
151 bw: usize,
152 bh: usize,
153 ) -> Self {
154 let want = bw + bh;
155 let extend = |samples: &[u16]| {
156 let mut row: Vec<i32> = samples.iter().map(|&s| i32::from(s)).collect();
157 let last = *row.last().expect("an edge that exists has samples");
158 row.resize(want, last);
159 row
160 };
161 // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)`
162 // (128 at 8-bit): `base - 1` above, `base + 1` left, `base` corner
163 // (libaom `reconintra.c`'s own diagram: the shared top-left corner
164 // cell is literally `base`, distinct from either row's own
165 // replicated value -- confirmed against `av1_highbd_build_intra_predictors`'s
166 // comment block, lane-tiny r1; an earlier attempt at this fix used
167 // 127/129 for the corner instead and made a passing 16x16 fixture
168 // regress, which is what caught the misreading).
169 let base = 1i32 << (crate::decode::bit_depth() - 1);
170 let above_row = match (above, left) {
171 (Some(a), _) => extend(a),
172 (None, Some(l)) => vec![i32::from(l[0]); want],
173 (None, None) => vec![base - 1; want],
174 };
175 let left_col = match (left, above) {
176 (Some(l), _) => extend(l),
177 (None, Some(a)) => vec![i32::from(a[0]); want],
178 (None, None) => vec![base + 1; want],
179 };
180 let corner = match (corner, above, left) {
181 (Some(c), Some(_), Some(_)) => i32::from(c),
182 (_, Some(a), _) => i32::from(a[0]),
183 (_, None, Some(l)) => i32::from(l[0]),
184 (_, None, None) => base,
185 };
186 let with_corner = |edge: Vec<i32>| {
187 let mut v = Vec::with_capacity(want + 1);
188 v.push(corner);
189 v.extend(edge);
190 v
191 };
192 Self {
193 above: with_corner(above_row),
194 left: with_corner(left_col),
195 }
196 }
197
198 /// `AboveRow[i]`, where `i` may be the spec's `-1`.
199 fn above(&self, i: i32) -> i32 {
200 self.above[usize::try_from(i + 1).expect("an edge is read no further back than the corner")]
201 }
202
203 /// `LeftCol[i]`, where `i` may be the spec's `-1`.
204 fn left(&self, i: i32) -> i32 {
205 self.left[usize::try_from(i + 1).expect("an edge is read no further back than the corner")]
206 }
207}
208
209/// Predicts one `bw`-wide, `bh`-tall block into `dst`, row-major and
210/// `bw * bh` long; `bw == bh` for a square block, the only shape every
211/// caller outside this lane's own tests passes.
212///
213/// `above` is the reconstructed row above the block and `left` its
214/// reconstructed left column, each at least `bw`/`bh` samples long
215/// respectively, and `corner` the sample diagonally above-left; `None` where
216/// the block sits against an edge of the frame. A directional mode reads out
217/// to `bw + bh`: pass the samples above-right and below-left where the
218/// decoder has them decoded, and the edge is extended by repetition where it
219/// does not, which is what the decoder's own clamp to `aboveLimit` and
220/// `leftLimit` comes to.
221///
222/// `angle_delta` (spec `AngleDeltaY`/`AngleDeltaUV`, `-MAX_ANGLE_DELTA` to
223/// `MAX_ANGLE_DELTA`) steers every one of `V_PRED`, `H_PRED` and the six
224/// diagonal modes off their base angle by `ANGLE_STEP` degrees per unit (spec
225/// 7.11.2.1's `pAngle = Mode_To_Angle[mode] + angleDelta * ANGLE_STEP`);
226/// ignored (must be `0`) for the seven modes that carry no angle at all.
227///
228/// `enable_edge_filter` is the sequence header's `enable_intra_edge_filter`
229/// (spec 7.11.2.4's own gate on the whole filter/upsample step); `smooth_neighbor`
230/// is `get_intra_edge_filter_type` (spec 7.11.2.9, libaom `reconintra.c`) --
231/// whether the block above or to the left predicted with one of the three
232/// smooth modes, which steers [`intra_edge_filter_strength`]'s threshold
233/// table. Ignored outside the directional modes.
234///
235/// # Panics
236/// Panics on a mode this module does not predict, or when `dst` is not
237/// `bw * bh` long.
238// lane-hbdgates r1: per-tool firing counters for the 10-bit gates. Each tool
239// the coverage table tracks needs its OWN counter -- `smooth_uv_hits` lumps
240// SMOOTH..=PAETH together, so a paeth-only stream would have "proved" smooth
241// intra ([[gate-blind-to-feature]]).
242thread_local! {
243 static SMOOTH_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
244 static PAETH_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
245 static EDGE_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
246}
247
248/// How many blocks were predicted with SMOOTH/SMOOTH_V/SMOOTH_H on this thread.
249pub(crate) fn smooth_pred_hits() -> usize {
250 SMOOTH_PRED_HITS.with(|c| c.get())
251}
252
253/// How many blocks were predicted with PAETH_PRED on this thread.
254pub(crate) fn paeth_pred_hits() -> usize {
255 PAETH_PRED_HITS.with(|c| c.get())
256}
257
258/// How many directional edges [`filter_intra_edge`] actually smoothed
259/// (strength != 0) on this thread -- the `--enable-intra-edge-filter` proof.
260pub(crate) fn intra_edge_filter_hits() -> usize {
261 EDGE_FILTER_HITS.with(|c| c.get())
262}
263
264#[allow(clippy::too_many_arguments)]
265pub fn predict(
266 mode: u8,
267 angle_delta: i32,
268 above: Option<&[u16]>,
269 left: Option<&[u16]>,
270 corner: Option<u16>,
271 bw: usize,
272 bh: usize,
273 enable_edge_filter: bool,
274 smooth_neighbor: bool,
275 dst: &mut [u16],
276) {
277 assert_eq!(dst.len(), bw * bh, "the destination is the block");
278 match mode {
279 SMOOTH_PRED | SMOOTH_V_PRED | SMOOTH_H_PRED => {
280 SMOOTH_PRED_HITS.with(|c| c.set(c.get() + 1));
281 }
282 PAETH_PRED => PAETH_PRED_HITS.with(|c| c.set(c.get() + 1)),
283 _ => {}
284 }
285 let edges = Edges::build(above, left, corner, bw, bh);
286 let is_directional = matches!(
287 mode,
288 V_PRED | H_PRED | D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
289 );
290 if is_directional {
291 let angle = i32::from(MODE_TO_ANGLE[usize::from(mode)]) + angle_delta * ANGLE_STEP;
292 // `pAngle == 90`/`180` is `V_PRED`/`H_PRED` at zero delta: a plain
293 // edge copy, no walk -- and the only two angles `dr_intra_derivative`
294 // has no table entry for, since libaom special-cases them the same
295 // way (`av1_is_directional_mode`'s callers never call the z1/z2/z3
296 // walk there either).
297 if angle != 90 && angle != 180 {
298 let n_top = above.map_or(0, |a| a.len().min(bw));
299 let n_left = left.map_or(0, |a| a.len().min(bh));
300 directional(
301 angle as u16,
302 &edges,
303 bw,
304 bh,
305 enable_edge_filter,
306 smooth_neighbor,
307 n_top,
308 n_left,
309 dst,
310 );
311 return;
312 }
313 }
314 // `smooth_predictor` (libaom `intrapred.c`) indexes its width and height
315 // weight rows separately (`smooth_weights + bw - 4` / `+ bh - 4`) -- a
316 // square block reads the same row for both, which is why this collapsed
317 // to one `weights` slice before.
318 let weights_w = &SM_WEIGHTS[bw..bw * 2];
319 let weights_h = &SM_WEIGHTS[bh..bh * 2];
320 for row in 0..bh {
321 for col in 0..bw {
322 let (r, c) = (row as i32, col as i32);
323 let last_w = bw as i32 - 1;
324 let last_h = bh as i32 - 1;
325 let value = match mode {
326 DC_PRED => dc(above, left, bw, bh),
327 V_PRED => edges.above(c),
328 H_PRED => edges.left(r),
329 SMOOTH_PRED => round2(
330 i32::from(weights_h[row]) * edges.above(c)
331 + (256 - i32::from(weights_h[row])) * edges.left(last_h)
332 + i32::from(weights_w[col]) * edges.left(r)
333 + (256 - i32::from(weights_w[col])) * edges.above(last_w),
334 9,
335 ),
336 SMOOTH_V_PRED => round2(
337 i32::from(weights_h[row]) * edges.above(c)
338 + (256 - i32::from(weights_h[row])) * edges.left(last_h),
339 8,
340 ),
341 SMOOTH_H_PRED => round2(
342 i32::from(weights_w[col]) * edges.left(r)
343 + (256 - i32::from(weights_w[col])) * edges.above(last_w),
344 8,
345 ),
346 PAETH_PRED => paeth(edges.above(c), edges.left(r), edges.above(-1)),
347 other => panic!("intra mode {other} is not one this module predicts"),
348 };
349 dst[row * bw + col] = value.clamp(0, crate::decode::sample_max()) as u16;
350 }
351 }
352}
353
354/// `intra_edge_filter_strength` (spec 7.11.2.9, libaom `reconintra.c`): the
355/// filter kernel index (`0`..=`3`) for a gap of `delta` degrees against a
356/// `bs0 + bs1`-wide block, split by `smooth_neighbor`'s two threshold tables.
357fn intra_edge_filter_strength(bs0: i32, bs1: i32, delta: i32, smooth_neighbor: bool) -> i32 {
358 let d = delta.abs();
359 let blk_wh = bs0 + bs1;
360 let mut strength = 0;
361 if !smooth_neighbor {
362 if blk_wh <= 8 {
363 if d >= 56 {
364 strength = 1;
365 }
366 } else if blk_wh <= 12 {
367 // Only reachable by a rect block (e.g. 4x8's blk_wh == 12): no
368 // square side sum ever lands in 9..=12, which is why this branch
369 // was silently absent before this lane.
370 if d >= 40 {
371 strength = 1;
372 }
373 } else if blk_wh <= 16 {
374 if d >= 40 {
375 strength = 1;
376 }
377 } else if blk_wh <= 24 {
378 if d >= 8 {
379 strength = 1;
380 }
381 if d >= 16 {
382 strength = 2;
383 }
384 if d >= 32 {
385 strength = 3;
386 }
387 } else if blk_wh <= 32 {
388 if d >= 1 {
389 strength = 1;
390 }
391 if d >= 4 {
392 strength = 2;
393 }
394 if d >= 32 {
395 strength = 3;
396 }
397 } else if d >= 1 {
398 strength = 3;
399 }
400 } else if blk_wh <= 8 {
401 if d >= 40 {
402 strength = 1;
403 }
404 if d >= 64 {
405 strength = 2;
406 }
407 } else if blk_wh <= 16 {
408 if d >= 20 {
409 strength = 1;
410 }
411 if d >= 48 {
412 strength = 2;
413 }
414 } else if blk_wh <= 24 {
415 if d >= 4 {
416 strength = 3;
417 }
418 } else if d >= 1 {
419 strength = 3;
420 }
421 strength
422}
423
424/// `av1_use_intra_edge_upsample` (spec 7.11.2.9): whether the edge doubles in
425/// density before the walk reads it.
426fn use_intra_edge_upsample(bs0: i32, bs1: i32, delta: i32, smooth_neighbor: bool) -> bool {
427 let d = delta.abs();
428 let blk_wh = bs0 + bs1;
429 if d == 0 || d >= 40 {
430 return false;
431 }
432 if smooth_neighbor {
433 blk_wh <= 8
434 } else {
435 blk_wh <= 16
436 }
437}
438
439/// `av1_filter_intra_edge_c` (spec 7.11.2.8): a 5-tap smoothing pass over
440/// `buf` in place, `buf[0]` (the corner) held fixed as every tap's clamp
441/// floor/ceiling.
442fn filter_intra_edge(buf: &mut [i32], strength: i32) {
443 if strength == 0 {
444 return;
445 }
446 EDGE_FILTER_HITS.with(|c| c.set(c.get() + 1));
447 const KERNEL: [[i32; 5]; 3] = [[0, 4, 8, 4, 0], [0, 5, 6, 5, 0], [2, 4, 4, 4, 2]];
448 let filt = usize::try_from(strength - 1).expect("a filter strength is never negative");
449 let sz = buf.len() as i32;
450 let edge = buf.to_vec();
451 for i in 1..buf.len() {
452 let mut s = 0;
453 for (j, &tap) in KERNEL[filt].iter().enumerate() {
454 let k = (i as i32 - 2 + j as i32).clamp(0, sz - 1);
455 s += edge[k as usize] * tap;
456 }
457 buf[i] = (s + 8) >> 4;
458 }
459}
460
461/// `av1_upsample_intra_edge_c` (spec 7.11.2.8): doubles `buf`'s density.
462/// `buf[0]` is spec position `-1` and `buf[buf.len() - 1]` is `sz - 1`; the
463/// result's `[0]` is spec position `-2`, `[2*i + 1]` the half-sample between
464/// `i - 1` and `i`, `[2*i + 2]` the original sample `i` moved to its doubled
465/// slot.
466fn upsample_intra_edge(buf: &[i32]) -> Vec<i32> {
467 let sz = buf.len() - 1;
468 let mut inp = vec![0i32; sz + 3];
469 inp[0] = buf[0];
470 inp[1] = buf[0];
471 inp[2..sz + 2].copy_from_slice(&buf[1..]);
472 inp[sz + 2] = buf[sz];
473 let mut out = vec![0i32; 2 * sz + 1];
474 out[0] = inp[0];
475 for i in 0..sz {
476 let s = -inp[i] + 9 * inp[i + 1] + 9 * inp[i + 2] - inp[i + 3];
477 out[2 * i + 1] = ((s + 8) >> 4).clamp(0, crate::decode::sample_max());
478 out[2 * i + 2] = inp[i + 2];
479 }
480 out
481}
482
483/// Directional intra prediction (spec 7.11.2.4): the edge filter/upsample
484/// steps (spec 7.11.2.7-2.9) run first when `enable_edge_filter` (the
485/// sequence header's own gate) says to, then the z1/z2/z3 walk (libaom
486/// `av1_dr_prediction_z{1,2,3}_c`) reads whichever of the two -- filtered,
487/// upsampled, or neither -- it ends with.
488#[allow(clippy::too_many_arguments)]
489fn directional(
490 angle: u16,
491 edges: &Edges,
492 bw: usize,
493 bh: usize,
494 enable_edge_filter: bool,
495 smooth_neighbor: bool,
496 n_top: usize,
497 n_left: usize,
498 dst: &mut [u16],
499) {
500 let (w, h) = (bw as i32, bh as i32);
501 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.
502 let need_above = angle < 180;
503 let need_left = angle > 90;
504 let need_right = angle < 90;
505 let need_bottom = angle > 180;
506
507 // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner.
508 let mut above: Vec<i32> = (-1..reach).map(|p| edges.above(p)).collect();
509 let mut left: Vec<i32> = (-1..reach).map(|p| edges.left(p)).collect();
510
511 if enable_edge_filter && angle != 90 && angle != 180 {
512 if need_above && need_left && reach >= 24 {
513 let s = round2(left[1] * 5 + above[0] * 6 + above[1] * 5, 4);
514 above[0] = s;
515 left[0] = s;
516 }
517 // `intra_edge_filter_strength(txwpx, txhpx, ...)` for above and
518 // `(txhpx, txwpx, ...)` for left (`reconintra.c`) -- the strength
519 // itself is symmetric in its first two args (only their sum
520 // matters), but the pixel counts filtered below are NOT: above's
521 // run-past-`n_top` extension is `txhpx` (the CROSS axis), left's is
522 // `txwpx`.
523 if need_above && n_top > 0 {
524 let strength = intra_edge_filter_strength(w, h, i32::from(angle) - 90, smooth_neighbor);
525 let n_px = n_top as i32 + 1 + if need_right { h } else { 0 };
526 filter_intra_edge(&mut above[..n_px as usize], strength);
527 }
528 if need_left && n_left > 0 {
529 let strength =
530 intra_edge_filter_strength(h, w, i32::from(angle) - 180, smooth_neighbor);
531 let n_px = n_left as i32 + 1 + if need_bottom { w } else { 0 };
532 filter_intra_edge(&mut left[..n_px as usize], strength);
533 }
534 }
535
536 let upsample_above =
537 enable_edge_filter && use_intra_edge_upsample(w, h, i32::from(angle) - 90, smooth_neighbor);
538 let upsample_left = enable_edge_filter
539 && use_intra_edge_upsample(h, w, i32::from(angle) - 180, smooth_neighbor);
540
541 let above_up;
542 let (above_buf, above_off): (&[i32], i32) = if need_above && upsample_above {
543 let n_px = (w + if need_right { h } else { 0 }) as usize;
544 above_up = upsample_intra_edge(&above[..=n_px]);
545 (&above_up, 2)
546 } else {
547 (&above, 1)
548 };
549 let left_up;
550 let (left_buf, left_off): (&[i32], i32) = if need_left && upsample_left {
551 let n_px = (h + if need_bottom { w } else { 0 }) as usize;
552 left_up = upsample_intra_edge(&left[..=n_px]);
553 (&left_up, 2)
554 } else {
555 (&left, 1)
556 };
557 let above_at = |p: i32| above_buf[(p + above_off) as usize];
558 let left_at = |p: i32| left_buf[(p + left_off) as usize];
559 let up_a = i32::from(upsample_above);
560 let up_l = i32::from(upsample_left);
561 let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| {
562 round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5)
563 };
564
565 for row in 0..h {
566 for col in 0..w {
567 let value = if angle < 90 {
568 let dx = dr_intra_derivative(angle);
569 let max_base = (reach - 1) << up_a;
570 let frac_bits = 6 - up_a;
571 let x = dx * (row + 1);
572 let base = (x >> frac_bits) + (col << up_a);
573 let shift = ((x << up_a) & 0x3F) >> 1;
574 if base < max_base {
575 blend(&above_at, base, shift)
576 } else {
577 above_at(max_base)
578 }
579 } else if angle > 180 {
580 let dy = dr_intra_derivative(270 - angle);
581 let max_base = (reach - 1) << up_l;
582 let frac_bits = 6 - up_l;
583 let y = dy * (col + 1);
584 let base = (y >> frac_bits) + (row << up_l);
585 let shift = ((y << up_l) & 0x3F) >> 1;
586 if base < max_base {
587 blend(&left_at, base, shift)
588 } else {
589 left_at(max_base)
590 }
591 } else {
592 // The two zones meet here: a ray that leaves through the row
593 // above is read there, and one that leaves through the column
594 // to the left is read there instead.
595 let dx = dr_intra_derivative(180 - angle);
596 let min_base = -(1 << up_a);
597 let frac_bits_x = 6 - up_a;
598 let y = row + 1;
599 let x = (col << 6) - y * dx;
600 let base = x >> frac_bits_x;
601 if base >= min_base {
602 blend(&above_at, base, ((x << up_a) & 0x3F) >> 1)
603 } else {
604 let dy = dr_intra_derivative(angle - 90);
605 let frac_bits_y = 6 - up_l;
606 let x2 = col + 1;
607 let y2 = (row << 6) - x2 * dy;
608 blend(&left_at, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1)
609 }
610 };
611 dst[(row * w + col) as usize] = value.clamp(0, crate::decode::sample_max()) as u16;
612 }
613 }
614}
615
616/// `dc_predict` (spec 7.11.2.5): the average of whichever neighbours exist.
617///
618/// Only the block's own `side` samples of each edge count: what a directional
619/// mode reaches past them is no part of the average. But `side` samples it
620/// always is: libaom's `build_intra_predictors` (`av1/common/reconintra.c`)
621/// replicates the last real sample out to the full transform width/height
622/// before `dc_predictor` averages, so a slice truncated short by the true
623/// frame edge must be extended by repetition here too, not averaged over its
624/// own shorter length.
625fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize) -> i32 {
626 let extend = |samples: &[u16], want: usize| -> Vec<u16> {
627 if samples.len() >= want {
628 samples[..want].to_vec()
629 } else {
630 let last = *samples.last().expect("an edge that exists has samples");
631 let mut v = samples.to_vec();
632 v.resize(want, last);
633 v
634 }
635 };
636 let above = above.map(|a| extend(a, bw));
637 let left = left.map(|l| extend(l, bh));
638 let average = |samples: &[u16]| {
639 let sum: u32 = samples.iter().map(|&s| u32::from(s)).sum();
640 ((sum + (samples.len() as u32 >> 1)) / samples.len() as u32) as i32
641 };
642 match (&above, &left) {
643 (None, None) => 1i32 << (crate::decode::bit_depth() - 1),
644 (Some(a), None) => average(a),
645 (None, Some(l)) => average(l),
646 (Some(a), Some(l)) if bw == bh => {
647 // `dc_predictor` (libaom `intrapred.c`): exact division, the
648 // square path this whole lane must leave bit-identical.
649 let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum();
650 let count = (a.len() + l.len()) as u32;
651 ((sum + (count >> 1)) / count) as i32
652 }
653 (Some(a), Some(l)) => {
654 // `dc_predictor_rect`: AV1 never divides by `bw + bh` exactly for
655 // a rect block -- it approximates with a multiply-shift whose
656 // constants are derived from `bw + bh`'s odd factor (`d == 3` for
657 // every 1:2 ratio, `d == 5` for every 1:4 one; libaom comments
658 // this exact derivation in `intrapred.c` rather than tabulating
659 // it, so this ports the derivation, not a lookup).
660 let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum();
661 let (shift1, multiplier) = dc_rect_multiplier(bw, bh);
662 let num = u64::from(sum + ((bw + bh) as u32 >> 1));
663 (((num >> shift1) * multiplier) >> 16) as i32
664 }
665 }
666}
667
668/// `dc_predictor_rect`'s per-call `(shift1, multiplier)` (libaom
669/// `intrapred.c`, `DC_MULTIPLIER_1X2`/`DC_MULTIPLIER_1X4`): shift `bw + bh`
670/// right until it is odd; AV1's only rect ratios (1:2, 1:4) leave that odd
671/// remainder at exactly 3 or 5.
672fn dc_rect_multiplier(bw: usize, bh: usize) -> (u32, u64) {
673 let mut d = (bw + bh) as u32;
674 let mut shift1 = 0;
675 while d & 1 == 0 {
676 d >>= 1;
677 shift1 += 1;
678 }
679 let multiplier = match d {
680 3 => 0x5556,
681 5 => 0x3334,
682 _ => panic!("AV1 rect blocks are only 1:2 or 1:4 (bw={bw} bh={bh})"),
683 };
684 (shift1, multiplier)
685}
686
687/// `Intra_Filter_Taps` (spec 7.11.2.3 / libaom `av1_filter_intra_taps`,
688/// `av1/common/reconintra.c`): five recursive-filter modes (DC/V/H/D157/Paeth
689/// variants, in that order), each predicting an 8-tap block of eight output
690/// samples from seven already-known neighbours.
691const FILTER_INTRA_TAPS: [[[i32; 7]; 8]; 5] = [
692 [
693 [-6, 10, 0, 0, 0, 12, 0],
694 [-5, 2, 10, 0, 0, 9, 0],
695 [-3, 1, 1, 10, 0, 7, 0],
696 [-3, 1, 1, 2, 10, 5, 0],
697 [-4, 6, 0, 0, 0, 2, 12],
698 [-3, 2, 6, 0, 0, 2, 9],
699 [-3, 2, 2, 6, 0, 2, 7],
700 [-3, 1, 2, 2, 6, 3, 5],
701 ],
702 [
703 [-10, 16, 0, 0, 0, 10, 0],
704 [-6, 0, 16, 0, 0, 6, 0],
705 [-4, 0, 0, 16, 0, 4, 0],
706 [-2, 0, 0, 0, 16, 2, 0],
707 [-10, 16, 0, 0, 0, 0, 10],
708 [-6, 0, 16, 0, 0, 0, 6],
709 [-4, 0, 0, 16, 0, 0, 4],
710 [-2, 0, 0, 0, 16, 0, 2],
711 ],
712 [
713 [-8, 8, 0, 0, 0, 16, 0],
714 [-8, 0, 8, 0, 0, 16, 0],
715 [-8, 0, 0, 8, 0, 16, 0],
716 [-8, 0, 0, 0, 8, 16, 0],
717 [-4, 4, 0, 0, 0, 0, 16],
718 [-4, 0, 4, 0, 0, 0, 16],
719 [-4, 0, 0, 4, 0, 0, 16],
720 [-4, 0, 0, 0, 4, 0, 16],
721 ],
722 [
723 [-2, 8, 0, 0, 0, 10, 0],
724 [-1, 3, 8, 0, 0, 6, 0],
725 [-1, 2, 3, 8, 0, 4, 0],
726 [0, 1, 2, 3, 8, 2, 0],
727 [-1, 4, 0, 0, 0, 3, 10],
728 [-1, 3, 4, 0, 0, 4, 6],
729 [-1, 2, 3, 4, 0, 4, 4],
730 [-1, 2, 2, 3, 4, 3, 3],
731 ],
732 [
733 [-12, 14, 0, 0, 0, 14, 0],
734 [-10, 0, 14, 0, 0, 12, 0],
735 [-9, 0, 0, 14, 0, 11, 0],
736 [-8, 0, 0, 0, 14, 10, 0],
737 [-10, 12, 0, 0, 0, 0, 14],
738 [-9, 1, 12, 0, 0, 0, 12],
739 [-8, 0, 0, 12, 0, 1, 11],
740 [-7, 0, 0, 1, 12, 1, 9],
741 ],
742];
743
744/// `FILTER_INTRA_SCALE_BITS` (libaom `reconintra.h`): the taps' fixed-point
745/// shift.
746const FILTER_INTRA_SCALE_BITS: u32 = 4;
747
748/// Recursive filter-intra prediction (spec 7.11.2.3, libaom
749/// `av1_filter_intra_predictor_c`): walks 4x2 sub-blocks left-to-right,
750/// top-to-bottom, each of the eight output samples a linear combination of
751/// seven already-decoded or already-predicted neighbours (never past the
752/// block's own top row / left column -- unlike the directional modes, this
753/// one never reaches beyond `side` samples of either edge).
754///
755/// `mode` is `0..=4`, indexing [`FILTER_INTRA_TAPS`]/`FILTER_DC_PRED`
756/// through `FILTER_PAETH_PRED`. `above`/`left`/`corner` are exactly
757/// [`predict`]'s edge arguments -- a side that does not exist is filled from
758/// the side that does and a side that runs out is extended by repeating its
759/// last sample, the same [`Edges::build`] rule every other mode uses, even
760/// though this mode itself never reaches past its own `side` samples of
761/// either edge.
762///
763/// `bw`x`bh` is the block, not necessarily square (lane-rectsplit r1):
764/// `av1_filter_intra_predictor_c` walks the same 4x2 patches over a
765/// rectangular block, and `av1_filter_intra_allowed_bsize` genuinely offers
766/// this mode on every HORZ/VERT strip whose sides are both <= 32 (16x8,
767/// 8x16, 32x16, 16x32, ...), which the square-only assert refused before.
768///
769/// # Panics
770/// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4
771/// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never
772/// offers this mode past 32x32).
773pub fn predict_filter_intra(
774 mode: usize,
775 above: Option<&[u16]>,
776 left: Option<&[u16]>,
777 corner: Option<u16>,
778 bw: usize,
779 bh: usize,
780 dst: &mut [u16],
781) {
782 assert_eq!(dst.len(), bw * bh, "the destination is the block");
783 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
784 assert_eq!(bh % 2, 0, "filter intra patches are 2 high");
785 let edges = Edges::build(above, left, corner, bw, bh);
786 let taps = &FILTER_INTRA_TAPS[mode];
787 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the
788 // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c).
789 let mut buffer = vec![0i32; (bh + 1) * (bw + 1)];
790 let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (bw + 1) + c];
791 buffer[0] = edges.above(-1);
792 for c in 0..bw {
793 buffer[c + 1] = edges.above(c as i32);
794 }
795 for r in 0..bh {
796 buffer[(r + 1) * (bw + 1)] = edges.left(r as i32);
797 }
798 let mut r = 1;
799 while r < bh + 1 {
800 let mut c = 1;
801 while c < bw + 1 {
802 let p0 = at(&buffer, r - 1, c - 1);
803 let p1 = at(&buffer, r - 1, c);
804 let p2 = at(&buffer, r - 1, c + 1);
805 let p3 = at(&buffer, r - 1, c + 2);
806 let p4 = at(&buffer, r - 1, c + 3);
807 let p5 = at(&buffer, r, c - 1);
808 let p6 = at(&buffer, r + 1, c - 1);
809 let p = [p0, p1, p2, p3, p4, p5, p6];
810 for k in 0..8 {
811 let (r_off, c_off) = (k >> 2, k & 3);
812 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();
813 let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max());
814 let idx = (r + r_off) * (bw + 1) + c + c_off;
815 buffer[idx] = value;
816 }
817 c += 4;
818 }
819 r += 2;
820 }
821 for row in 0..bh {
822 for col in 0..bw {
823 dst[row * bw + col] = at(&buffer, row + 1, col + 1) as u16;
824 }
825 }
826}
827
828/// `paeth_predict` (spec 7.11.2.2): of the three neighbours, the one nearest
829/// the gradient they describe.
830fn paeth(above: i32, left: i32, corner: i32) -> i32 {
831 let base = above + left - corner;
832 let (d_left, d_above, d_corner) = (
833 (base - left).abs(),
834 (base - above).abs(),
835 (base - corner).abs(),
836 );
837 if d_left <= d_above && d_left <= d_corner {
838 left
839 } else if d_above <= d_corner {
840 above
841 } else {
842 corner
843 }
844}
845
846#[cfg(test)]
847mod tests {
848 use super::*;
849 use std::collections::HashMap;
850
851 /// Same deterministic synthetic ramp `lanes/intrarect_dump.c`'s `fill`
852 /// generates.
853 fn fill(n: usize, seed: i32) -> Vec<u16> {
854 (0..n)
855 .map(|i| ((i as i32 * 7 + seed * 13 + (i as i32 % 5) * 3).rem_euclid(256)) as u16)
856 .collect()
857 }
858
859 /// `lanes/intrarect_dump.c`'s `checksum`: a position-weighted sum so a
860 /// wrong value anywhere in the block, not just at index 0, moves it.
861 fn checksum(dst: &[u16]) -> u64 {
862 dst.iter()
863 .enumerate()
864 .map(|(i, &v)| u64::from(v) * (i as u64 + 1))
865 .sum()
866 }
867
868 /// libaom `av1_filter_intra_taps` (reconintra.c:807-858), transcribed
869 /// here INDEPENDENTLY of [`FILTER_INTRA_TAPS`] -- the point of the test
870 /// below is that two transcriptions of the reference agree, so it must
871 /// not read the table it is checking. (libaom's rows are 8 wide with the
872 /// 8th tap always 0; only seven are used.)
873 const LIBAOM_FILTER_INTRA_TAPS: [[[i32; 7]; 8]; 5] = [
874 [
875 [-6, 10, 0, 0, 0, 12, 0],
876 [-5, 2, 10, 0, 0, 9, 0],
877 [-3, 1, 1, 10, 0, 7, 0],
878 [-3, 1, 1, 2, 10, 5, 0],
879 [-4, 6, 0, 0, 0, 2, 12],
880 [-3, 2, 6, 0, 0, 2, 9],
881 [-3, 2, 2, 6, 0, 2, 7],
882 [-3, 1, 2, 2, 6, 3, 5],
883 ],
884 [
885 [-10, 16, 0, 0, 0, 10, 0],
886 [-6, 0, 16, 0, 0, 6, 0],
887 [-4, 0, 0, 16, 0, 4, 0],
888 [-2, 0, 0, 0, 16, 2, 0],
889 [-10, 16, 0, 0, 0, 0, 10],
890 [-6, 0, 16, 0, 0, 0, 6],
891 [-4, 0, 0, 16, 0, 0, 4],
892 [-2, 0, 0, 0, 16, 0, 2],
893 ],
894 [
895 [-8, 8, 0, 0, 0, 16, 0],
896 [-8, 0, 8, 0, 0, 16, 0],
897 [-8, 0, 0, 8, 0, 16, 0],
898 [-8, 0, 0, 0, 8, 16, 0],
899 [-4, 4, 0, 0, 0, 0, 16],
900 [-4, 0, 4, 0, 0, 0, 16],
901 [-4, 0, 0, 4, 0, 0, 16],
902 [-4, 0, 0, 0, 4, 0, 16],
903 ],
904 [
905 [-2, 8, 0, 0, 0, 10, 0],
906 [-1, 3, 8, 0, 0, 6, 0],
907 [-1, 2, 3, 8, 0, 4, 0],
908 [0, 1, 2, 3, 8, 2, 0],
909 [-1, 4, 0, 0, 0, 3, 10],
910 [-1, 3, 4, 0, 0, 4, 6],
911 [-1, 2, 3, 4, 0, 4, 4],
912 [-1, 2, 2, 3, 4, 3, 3],
913 ],
914 [
915 [-12, 14, 0, 0, 0, 14, 0],
916 [-10, 0, 14, 0, 0, 12, 0],
917 [-9, 0, 0, 14, 0, 11, 0],
918 [-8, 0, 0, 0, 14, 10, 0],
919 [-10, 12, 0, 0, 0, 0, 14],
920 [-9, 1, 12, 0, 0, 0, 12],
921 [-8, 0, 0, 12, 0, 1, 11],
922 [-7, 0, 0, 1, 12, 1, 9],
923 ],
924 ];
925
926 /// A straight port of `av1_filter_intra_predictor_c` /
927 /// `highbd_filter_intra_predictor` (reconintra.c:860-905 / 908-955 --
928 /// identical except for the clip), written from the C rather than from
929 /// [`predict_filter_intra`]. `above` is the C `&above[-1]`, i.e. the
930 /// corner followed by `bw` samples; `left` is `bh` samples.
931 fn libaom_filter_intra_predictor(
932 dst: &mut [u16],
933 bw: usize,
934 bh: usize,
935 above: &[u16],
936 left: &[u16],
937 mode: usize,
938 bd: u32,
939 ) {
940 assert!(bw <= 32 && bh <= 32);
941 let mut buffer = [[0i32; 33]; 33];
942 for r in 0..bh {
943 buffer[r + 1][0] = i32::from(left[r]);
944 }
945 for c in 0..bw + 1 {
946 buffer[0][c] = i32::from(above[c]);
947 }
948 let max = (1i32 << bd) - 1;
949 let mut r = 1;
950 while r < bh + 1 {
951 let mut c = 1;
952 while c < bw + 1 {
953 let p = [
954 buffer[r - 1][c - 1],
955 buffer[r - 1][c],
956 buffer[r - 1][c + 1],
957 buffer[r - 1][c + 2],
958 buffer[r - 1][c + 3],
959 buffer[r][c - 1],
960 buffer[r + 1][c - 1],
961 ];
962 for k in 0..8 {
963 let mut pr = 0i32;
964 for t in 0..7 {
965 pr += LIBAOM_FILTER_INTRA_TAPS[mode][k][t] * p[t];
966 }
967 // ROUND_POWER_OF_TWO(pr, 4) then clip_pixel[_highbd].
968 let v = ((pr + 8) >> 4).clamp(0, max);
969 buffer[r + (k >> 2)][c + (k & 3)] = v;
970 }
971 c += 4;
972 }
973 r += 2;
974 }
975 for row in 0..bh {
976 for col in 0..bw {
977 dst[row * bw + col] = buffer[row + 1][col + 1] as u16;
978 }
979 }
980 }
981
982 /// lane-fistrip r2: [`predict_filter_intra`] had NO unit test at all --
983 /// the 8x16/16x8 strips r1 unblocked read their `use_filter_intra` flag
984 /// with zero pixel evidence behind it (every firing strip is `skip=0`
985 /// and refuses, see `stream.rs`'s ignored gate). This compares it
986 /// bit-exact against the independent C port above for every filter-intra
987 /// mode, every shape `av1_filter_intra_allowed_bsize` allows (both sides
988 /// <= 32, squares and both orientations of 1:2 and 1:4), 8- and 10-bit,
989 /// on three seeded random edges.
990 #[test]
991 fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() {
992 // xorshift64*: a seeded stream, so a failure names one (shape, mode,
993 // seed) triple that reproduces.
994 let mut rng = |state: &mut u64| {
995 *state ^= *state << 13;
996 *state ^= *state >> 7;
997 *state ^= *state << 17;
998 *state
999 };
1000 let shapes = [
1001 (4usize, 4usize),
1002 (8, 8),
1003 (16, 16),
1004 (32, 32),
1005 (4, 8),
1006 (8, 4),
1007 (8, 16),
1008 (16, 8),
1009 (16, 32),
1010 (32, 16),
1011 (4, 16),
1012 (16, 4),
1013 (8, 32),
1014 (32, 8),
1015 ];
1016 let mut compared = 0u32;
1017 for bd in [8u32, 10] {
1018 crate::decode::set_bit_depth(bd as u8);
1019 let max = (1u32 << bd) - 1;
1020 for &(bw, bh) in &shapes {
1021 for mode in 0..5usize {
1022 for seed in [1u64, 0x5eed_5eed, 0xdead_beef_cafe] {
1023 let mut state = seed
1024 .wrapping_mul(0x9E37_79B9_7F4A_7C15)
1025 .wrapping_add((bw * 97 + bh * 7 + mode) as u64)
1026 | 1;
1027 let sample = |state: &mut u64| (rng(state) % u64::from(max + 1)) as u16;
1028 let corner = sample(&mut state);
1029 let above: Vec<u16> = (0..bw).map(|_| sample(&mut state)).collect();
1030 let left: Vec<u16> = (0..bh).map(|_| sample(&mut state)).collect();
1031 let mut want = vec![0u16; bw * bh];
1032 let mut c_above = vec![corner];
1033 c_above.extend_from_slice(&above);
1034 libaom_filter_intra_predictor(
1035 &mut want, bw, bh, &c_above, &left, mode, bd,
1036 );
1037 let mut got = vec![0u16; bw * bh];
1038 predict_filter_intra(
1039 mode,
1040 Some(&above),
1041 Some(&left),
1042 Some(corner),
1043 bw,
1044 bh,
1045 &mut got,
1046 );
1047 assert_eq!(
1048 got, want,
1049 "filter intra mode {mode}, {bw}x{bh}, {bd}-bit, seed {seed:#x}"
1050 );
1051 compared += 1;
1052 }
1053 }
1054 }
1055 }
1056 crate::decode::set_bit_depth(8);
1057 assert_eq!(compared, 2 * 14 * 5 * 3, "every shape/mode/seed was compared");
1058 }
1059
1060 /// lane-intrarect r1: checksum-verify DC/SMOOTH/PAETH and a directional
1061 /// sweep across all three zones, `enable_edge_filter`/`smooth_neighbor`
1062 /// on and off, for eight rect shapes (both 1:2 and 1:4, both
1063 /// orientations), against `lanes/intrarect_dump.c`'s independent C
1064 /// transcription (`lanes/intrarect_dump.expected.txt`, generated by
1065 /// `gcc -O2 lanes/intrarect_dump.c -o /tmp/intrarect_dump &&
1066 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).
1067 #[test]
1068 fn rect_predictors_match_c_dump() {
1069 let expected_txt = std::fs::read_to_string(concat!(
1070 env!("CARGO_MANIFEST_DIR"),
1071 "/../../lanes/intrarect_dump.expected.txt"
1072 ))
1073 .expect(
1074 "run gcc -O2 lanes/intrarect_dump.c -o /tmp/intrarect_dump && \
1075 /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt first",
1076 );
1077 // Keys: ("DC"|"SMOOTH"|"PAETH", bw, bh, angle, ef, sn) -> value.
1078 // Non-directional entries use angle=0, ef=2, sn=2 (never matched by
1079 // the directional lookups below, which always pass 0 or 1).
1080 let mut expected: HashMap<(&str, usize, usize, i32, i32, i32), u64> = HashMap::new();
1081 for line in expected_txt.lines() {
1082 let parts: Vec<&str> = line.split_whitespace().collect();
1083 let (bw, bh) = parts[0].split_once('x').unwrap();
1084 let (bw, bh): (usize, usize) = (bw.parse().unwrap(), bh.parse().unwrap());
1085 match parts[1] {
1086 "DC" => {
1087 let v: u64 = parts[2]["value=".len()..].parse().unwrap();
1088 expected.insert(("DC", bw, bh, 0, 2, 2), v);
1089 }
1090 "SMOOTH" | "PAETH" => {
1091 let cs: u64 = parts[2]["checksum=".len()..].parse().unwrap();
1092 expected.insert((parts[1], bw, bh, 0, 2, 2), cs);
1093 }
1094 "DR" => {
1095 let angle: i32 = parts[2]["angle=".len()..].parse().unwrap();
1096 let ef: i32 = parts[3]["ef=".len()..].parse().unwrap();
1097 let sn: i32 = parts[4]["sn=".len()..].parse().unwrap();
1098 let cs: u64 = parts[5]["checksum=".len()..].parse().unwrap();
1099 expected.insert(("DR", bw, bh, angle, ef, sn), cs);
1100 }
1101 other => panic!("unrecognised dump line kind {other}"),
1102 }
1103 }
1104
1105 let shapes = [
1106 (8, 4),
1107 (4, 8),
1108 (16, 8),
1109 (8, 16),
1110 (4, 16),
1111 (16, 4),
1112 (32, 16),
1113 (16, 32),
1114 ];
1115 // (angle, mode, angle_delta) for every angle `intrarect_dump.c`
1116 // sweeps -- the same reachable `Mode_To_Angle + delta * ANGLE_STEP`
1117 // combinations the dump had to stay inside of.
1118 let directional_cases: [(i32, u8, i32); 17] = [
1119 (45, D45_PRED, 0),
1120 (48, D45_PRED, 1),
1121 (64, D67_PRED, -1),
1122 (67, D67_PRED, 0),
1123 (84, V_PRED, -2),
1124 (87, V_PRED, -1),
1125 (113, D113_PRED, 0),
1126 (116, D113_PRED, 1),
1127 (135, D135_PRED, 0),
1128 (138, D135_PRED, 1),
1129 (157, D157_PRED, 0),
1130 (160, D157_PRED, 1),
1131 (171, H_PRED, -3),
1132 (183, H_PRED, 1),
1133 (186, H_PRED, 2),
1134 (203, D203_PRED, 0),
1135 (206, D203_PRED, 1),
1136 ];
1137
1138 let mut checked = 0;
1139 for &(bw, bh) in &shapes {
1140 let reach = bw + bh;
1141 let above = fill(reach, 1);
1142 let left = fill(reach, 2);
1143 let corner = ((bw * 3 + bh * 5) % 256) as u16;
1144
1145 for (name, mode) in [("DC", DC_PRED), ("SMOOTH", SMOOTH_PRED), ("PAETH", PAETH_PRED)] {
1146 let mut dst = vec![0u16; bw * bh];
1147 predict(
1148 mode,
1149 0,
1150 Some(&above),
1151 Some(&left),
1152 Some(corner),
1153 bw,
1154 bh,
1155 false,
1156 false,
1157 &mut dst,
1158 );
1159 let got = if name == "DC" {
1160 u64::from(dst[0])
1161 } else {
1162 checksum(&dst)
1163 };
1164 let want = *expected
1165 .get(&(name, bw, bh, 0, 2, 2))
1166 .unwrap_or_else(|| panic!("missing {name} {bw}x{bh} in the C dump"));
1167 assert_eq!(got, want, "{name} {bw}x{bh}: rust {got} != C dump {want}");
1168 checked += 1;
1169 }
1170
1171 for &(angle, mode, delta) in &directional_cases {
1172 for ef in [false, true] {
1173 for sn in [false, true] {
1174 let mut dst = vec![0u16; bw * bh];
1175 predict(
1176 mode,
1177 delta,
1178 Some(&above),
1179 Some(&left),
1180 Some(corner),
1181 bw,
1182 bh,
1183 ef,
1184 sn,
1185 &mut dst,
1186 );
1187 let got = checksum(&dst);
1188 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));
1189 let want = *expected.get(&key).unwrap_or_else(|| {
1190 panic!("missing DR {bw}x{bh} angle={angle} ef={ef} sn={sn} in the C dump")
1191 });
1192 assert_eq!(
1193 got, want,
1194 "DR {bw}x{bh} angle={angle} ef={ef} sn={sn}: rust {got} != C dump {want}"
1195 );
1196 checked += 1;
1197 }
1198 }
1199 }
1200 }
1201 assert_eq!(
1202 checked,
1203 shapes.len() * (3 + directional_cases.len() * 4),
1204 "checked every (shape, mode/angle, ef, sn) combination"
1205 );
1206 }
1207}