forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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