forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

mc.rs1492 lines, 58.5 KiBHistoryRawDownload
1//! Sub-pel motion compensation, spec 7.11.3 ("Motion vector scaling process"
2//! through "Block inter predictor process"), the REGULAR (`EIGHTTAP`) filter
3//! only, 8-bit samples only.
4//!
5//! A block's inter prediction is separable: an 8-tap horizontal pass over the
6//! reference, rounded down by `InterRound0`, feeds an 8-tap vertical pass
7//! over that intermediate, rounded down by `InterRound1`. Both fractions run
8//! in 1/16-pel steps -- luma motion vectors are stored at 1/8-pel and always
9//! land on an even step; chroma vectors, once scaled for subsampling, can
10//! land on any of the 16.
11
12/// `Round2` (spec 4.7): halves round up.
13fn round2(value: i32, shift: u32) -> i32 {
14 if shift == 0 {
15 value
16 } else {
17 (value + (1 << (shift - 1))) >> shift
18 }
19}
20
21/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the
22/// horizontal pass's sum is brought down by before it is stored as the
23/// intermediate.
24const INTER_ROUND_0: u32 = 3;
25/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical
26/// pass's sum is brought down by to land back on an 8-bit sample. Composed
27/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass
28/// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)
29/// -- so an identity or DC input comes back exactly, by construction of the
30/// table rather than by a fitted constant.
31const INTER_ROUND_1: u32 = 11;
32
33/// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel
34/// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer
35/// sample (fraction 0 is the identity tap `[.., 128, ..]`).
36const SUBPEL_FILTERS: [[i32; 8]; 16] = [
37 [0, 0, 0, 128, 0, 0, 0, 0],
38 [0, 2, -6, 126, 8, -2, 0, 0],
39 [0, 2, -10, 122, 18, -4, 0, 0],
40 [0, 2, -12, 116, 28, -8, 2, 0],
41 [0, 2, -14, 110, 38, -10, 2, 0],
42 [0, 2, -14, 102, 48, -12, 2, 0],
43 [0, 2, -16, 94, 58, -12, 2, 0],
44 [0, 2, -14, 84, 66, -12, 2, 0],
45 [0, 2, -14, 76, 76, -14, 2, 0],
46 [0, 2, -12, 66, 84, -14, 2, 0],
47 [0, 2, -12, 58, 94, -16, 2, 0],
48 [0, 2, -12, 48, 102, -14, 2, 0],
49 [0, 2, -10, 38, 110, -14, 2, 0],
50 [0, 2, -8, 28, 116, -12, 2, 0],
51 [0, 0, -4, 18, 122, -10, 2, 0],
52 [0, 0, -2, 8, 126, -6, 2, 0],
53];
54
55/// `Subpel_Filters[EIGHTTAP]`'s narrow-block counterpart (spec 7.11.3.4's
56/// filter selection is per-axis: a `predict` axis whose output block
57/// dimension is 4 or less reads this table instead of [`SUBPEL_FILTERS`]),
58/// mirroring `av1_sub_pel_filters_4` (`filter.h`): the same 8-slot shape but
59/// zeroed at taps 0/1/6/7, so a 4-wide (or 4-tall) block's filter never
60/// reaches a full 3 samples past its own edge. Every 4:2:0 chroma block
61/// under an 8x8 (or smaller) luma leaf hits this on at least one axis --
62/// this is not an edge case, it is the common chroma shape.
63const SUBPEL_FILTERS_4: [[i32; 8]; 16] = [
64 [0, 0, 0, 128, 0, 0, 0, 0],
65 [0, 0, -4, 126, 8, -2, 0, 0],
66 [0, 0, -8, 122, 18, -4, 0, 0],
67 [0, 0, -10, 116, 28, -6, 0, 0],
68 [0, 0, -12, 110, 38, -8, 0, 0],
69 [0, 0, -12, 102, 48, -10, 0, 0],
70 [0, 0, -14, 94, 58, -10, 0, 0],
71 [0, 0, -12, 84, 66, -10, 0, 0],
72 [0, 0, -12, 76, 76, -12, 0, 0],
73 [0, 0, -10, 66, 84, -12, 0, 0],
74 [0, 0, -10, 58, 94, -14, 0, 0],
75 [0, 0, -10, 48, 102, -12, 0, 0],
76 [0, 0, -8, 38, 110, -12, 0, 0],
77 [0, 0, -6, 28, 116, -10, 0, 0],
78 [0, 0, -4, 18, 122, -8, 0, 0],
79 [0, 0, -2, 8, 126, -4, 0, 0],
80];
81
82/// `Subpel_Filters[EIGHTTAP_SMOOTH]` (`filter.h`'s `av1_sub_pel_filters_8smooth`).
83const SUBPEL_FILTERS_SMOOTH: [[i32; 8]; 16] = [
84 [0, 0, 0, 128, 0, 0, 0, 0],
85 [0, 2, 28, 62, 34, 2, 0, 0],
86 [0, 0, 26, 62, 36, 4, 0, 0],
87 [0, 0, 22, 62, 40, 4, 0, 0],
88 [0, 0, 20, 60, 42, 6, 0, 0],
89 [0, 0, 18, 58, 44, 8, 0, 0],
90 [0, 0, 16, 56, 46, 10, 0, 0],
91 [0, -2, 16, 54, 48, 12, 0, 0],
92 [0, -2, 14, 52, 52, 14, -2, 0],
93 [0, 0, 12, 48, 54, 16, -2, 0],
94 [0, 0, 10, 46, 56, 16, 0, 0],
95 [0, 0, 8, 44, 58, 18, 0, 0],
96 [0, 0, 6, 42, 60, 20, 0, 0],
97 [0, 0, 4, 40, 62, 22, 0, 0],
98 [0, 0, 4, 36, 62, 26, 0, 0],
99 [0, 0, 2, 34, 62, 28, 2, 0],
100];
101
102/// `SUBPEL_FILTERS_SMOOTH`'s narrow-block counterpart (`av1_sub_pel_filters_4smooth`).
103const SUBPEL_FILTERS_SMOOTH_4: [[i32; 8]; 16] = [
104 [0, 0, 0, 128, 0, 0, 0, 0],
105 [0, 0, 30, 62, 34, 2, 0, 0],
106 [0, 0, 26, 62, 36, 4, 0, 0],
107 [0, 0, 22, 62, 40, 4, 0, 0],
108 [0, 0, 20, 60, 42, 6, 0, 0],
109 [0, 0, 18, 58, 44, 8, 0, 0],
110 [0, 0, 16, 56, 46, 10, 0, 0],
111 [0, 0, 14, 54, 48, 12, 0, 0],
112 [0, 0, 12, 52, 52, 12, 0, 0],
113 [0, 0, 12, 48, 54, 14, 0, 0],
114 [0, 0, 10, 46, 56, 16, 0, 0],
115 [0, 0, 8, 44, 58, 18, 0, 0],
116 [0, 0, 6, 42, 60, 20, 0, 0],
117 [0, 0, 4, 40, 62, 22, 0, 0],
118 [0, 0, 4, 36, 62, 26, 0, 0],
119 [0, 0, 2, 34, 62, 30, 0, 0],
120];
121
122/// `Subpel_Filters[EIGHTTAP_SHARP]` (`av1_sub_pel_filters_8sharp`). A block
123/// whose dimension is 4 or less does NOT read this table: spec 7.11.3.4's
124/// `filterIdx` sends both EIGHTTAP and EIGHTTAP_SHARP to filter index 4, and
125/// libaom agrees -- `av1_interp_4tap[MULTITAP_SHARP]` is `av1_sub_pel_filters_4`,
126/// the REGULAR narrow kernel (`filter.h:243`), not a sharp one (lane-gmaffine r5).
127const SUBPEL_FILTERS_SHARP: [[i32; 8]; 16] = [
128 [0, 0, 0, 128, 0, 0, 0, 0],
129 [-2, 2, -6, 126, 8, -2, 2, 0],
130 [-2, 6, -12, 124, 16, -6, 4, -2],
131 [-2, 8, -18, 120, 26, -10, 6, -2],
132 [-4, 10, -22, 116, 38, -14, 6, -2],
133 [-4, 10, -22, 108, 48, -18, 8, -2],
134 [-4, 10, -24, 100, 60, -20, 8, -2],
135 [-4, 10, -24, 90, 70, -22, 10, -2],
136 [-4, 12, -24, 80, 80, -24, 12, -4],
137 [-2, 10, -22, 70, 90, -24, 10, -4],
138 [-2, 8, -20, 60, 100, -24, 10, -4],
139 [-2, 8, -18, 48, 108, -22, 10, -4],
140 [-2, 6, -14, 38, 116, -22, 10, -4],
141 [-2, 6, -10, 26, 120, -18, 8, -2],
142 [-2, 4, -6, 16, 124, -12, 6, -2],
143 [0, 2, -2, 8, 126, -6, 2, -2],
144];
145
146/// `Subpel_Filters[BILINEAR]` (`av1_bilinear_filters`) -- also never swapped
147/// for a narrow-block table (it is already only 2 non-zero taps).
148const SUBPEL_FILTERS_BILINEAR: [[i32; 8]; 16] = [
149 [0, 0, 0, 128, 0, 0, 0, 0],
150 [0, 0, 0, 120, 8, 0, 0, 0],
151 [0, 0, 0, 112, 16, 0, 0, 0],
152 [0, 0, 0, 104, 24, 0, 0, 0],
153 [0, 0, 0, 96, 32, 0, 0, 0],
154 [0, 0, 0, 88, 40, 0, 0, 0],
155 [0, 0, 0, 80, 48, 0, 0, 0],
156 [0, 0, 0, 72, 56, 0, 0, 0],
157 [0, 0, 0, 64, 64, 0, 0, 0],
158 [0, 0, 0, 56, 72, 0, 0, 0],
159 [0, 0, 0, 48, 80, 0, 0, 0],
160 [0, 0, 0, 40, 88, 0, 0, 0],
161 [0, 0, 0, 32, 96, 0, 0, 0],
162 [0, 0, 0, 24, 104, 0, 0, 0],
163 [0, 0, 0, 16, 112, 0, 0, 0],
164 [0, 0, 0, 8, 120, 0, 0, 0],
165];
166
167/// Which of the spec's four `interpolation_filter` kernels a block's motion
168/// compensation reads (spec 6.8.9 / `frame_header`'s `interpolation_filter`).
169/// A frame codes exactly one of these when not `Switchable`; a `Switchable`
170/// frame codes one per block per direction (spec 5.11.20's
171/// `read_interp_filter`, see `decode::decode_inter_block`), so `predict`'s
172/// callers resolve `Switchable` to a concrete pair of kinds themselves --
173/// this type only ever names the resolved kernel, never `Switchable` itself.
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub enum InterpFilterKind {
176 Regular,
177 Smooth,
178 Sharp,
179 Bilinear,
180}
181
182impl InterpFilterKind {
183 fn tables(self) -> (&'static [[i32; 8]; 16], &'static [[i32; 8]; 16]) {
184 match self {
185 InterpFilterKind::Regular => (&SUBPEL_FILTERS, &SUBPEL_FILTERS_4),
186 InterpFilterKind::Smooth => (&SUBPEL_FILTERS_SMOOTH, &SUBPEL_FILTERS_SMOOTH_4),
187 InterpFilterKind::Sharp => (&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_4),
188 InterpFilterKind::Bilinear => (&SUBPEL_FILTERS_BILINEAR, &SUBPEL_FILTERS_BILINEAR),
189 }
190 }
191
192 /// The three-symbol alphabet spec 5.11.20's `interp_filter[dir]` reads
193 /// under a `Switchable` frame decodes to (`EIGHTTAP`/`_SMOOTH`/`_SHARP`
194 /// in that order -- `BILINEAR` is never a `switchable_interp` outcome).
195 ///
196 /// # Panics
197 /// Panics when `symbol` is not `0..=2`.
198 pub fn from_switchable_symbol(symbol: usize) -> InterpFilterKind {
199 match symbol {
200 0 => InterpFilterKind::Regular,
201 1 => InterpFilterKind::Smooth,
202 2 => InterpFilterKind::Sharp,
203 _ => panic!("switchable_interp's alphabet is exactly 3 symbols"),
204 }
205 }
206
207 /// The frame header's own `interpolation_filter` (spec 6.8.9), for the
208 /// non-`Switchable` values a fixed-filter frame codes directly.
209 ///
210 /// # Panics
211 /// Panics on `Switchable`, which is not a concrete kernel -- callers
212 /// resolve it per block instead (spec 5.11.20).
213 pub fn from_header(filter: ec_av1_syntax::InterpolationFilter) -> InterpFilterKind {
214 match filter {
215 ec_av1_syntax::InterpolationFilter::Eighttap => InterpFilterKind::Regular,
216 ec_av1_syntax::InterpolationFilter::EighttapSmooth => InterpFilterKind::Smooth,
217 ec_av1_syntax::InterpolationFilter::EighttapSharp => InterpFilterKind::Sharp,
218 ec_av1_syntax::InterpolationFilter::Bilinear => InterpFilterKind::Bilinear,
219 ec_av1_syntax::InterpolationFilter::Switchable => {
220 panic!("Switchable is resolved per block, not as one frame-wide kernel")
221 }
222 }
223 }
224}
225
226/// A reference sample at `(x, y)`, clamped to the frame's true (unpadded)
227/// extent -- `true_width`/`true_height`, which can be narrower than
228/// `stride` -- rather than read out of range (spec 7.11.3.4's `Clip3`
229/// against the frame's edges): a motion vector that points past the true
230/// edge repeats the true edge's sample instead of panicking or picking up
231/// whatever this encoder's own uncoded padding columns/rows hold.
232#[allow(clippy::too_many_arguments)]
233fn sample(
234 reference: &[u16],
235 stride: usize,
236 true_width: usize,
237 true_height: usize,
238 x: i32,
239 y: i32,
240) -> i32 {
241 let cx = x.clamp(0, true_width as i32 - 1) as usize;
242 let cy = y.clamp(0, true_height as i32 - 1) as usize;
243 i32::from(reference[cy * stride + cx])
244}
245
246/// lane-perf2: one row of the separable filter's horizontal pass, dav1d
247/// style. When the row's whole 8-tap footprint (`x0-3 .. x0+block_w+4`) lies
248/// inside the reference's true extent -- the overwhelmingly common case --
249/// the row is one contiguous slice and the taps are a fixed `[i32; 8]`, so
250/// the per-sample `Clip3` and the per-tap table load both leave the inner
251/// loop and it auto-vectorises. The edge case keeps the exact spec form
252/// (`sample`'s clamp per tap); both arms compute the same sums.
253#[inline]
254fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i32]) {
255 let block_w = out.len();
256 let start = x0 - 3;
257 if start >= 0 && start as usize + block_w + 7 <= true_width {
258 let s = row_base + start as usize;
259 if let Some(src) = reference.get(s..s + block_w + 7) {
260 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the
261 // bit depth), so the products are exactly the i32 ones above but
262 // the widening multiply is one instruction per pair.
263 let t16 = [
264 taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
265 taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
266 ];
267 for (o, w) in out.iter_mut().zip(src.windows(8)) {
268 let mut sum = 0i32;
269 for t in 0..8 {
270 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
271 }
272 *o = round2(sum, INTER_ROUND_0);
273 }
274 return;
275 }
276 }
277 for (c, o) in out.iter_mut().enumerate() {
278 let mut sum = 0i32;
279 for (t, &tap) in taps.iter().enumerate() {
280 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
281 sum += tap * i32::from(reference[row_base + x]);
282 }
283 *o = round2(sum, INTER_ROUND_0);
284 }
285}
286
287/// lane-perf2: the unscaled horizontal pass, `block_h + 7` rows of
288/// [`hpass_row`] with the vertical clamp hoisted out of the row.
289#[allow(clippy::too_many_arguments)]
290fn horizontal_pass_unscaled(
291 reference: &[u16],
292 stride: usize,
293 true_width: usize,
294 true_height: usize,
295 x0: i32,
296 y0: i32,
297 taps: &[i32; 8],
298 block_w: usize,
299 rows: usize,
300 intermediate: &mut [i32],
301) {
302 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
303 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
304 // needs no filter at all -- one widened row read.
305 let identity = taps[3] == 128 && taps.iter().enumerate().all(|(i, &t)| i == 3 || t == 0);
306 for r in 0..rows {
307 let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize;
308 let out = &mut intermediate[r * block_w..(r + 1) * block_w];
309 if identity {
310 let gain = 128 >> INTER_ROUND_0;
311 if x0 >= 0 && x0 as usize + block_w <= true_width {
312 if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {
313 for (o, &s) in out.iter_mut().zip(src) {
314 *o = gain * i32::from(s);
315 }
316 continue;
317 }
318 }
319 for (c, o) in out.iter_mut().enumerate() {
320 let x = (x0 + c as i32).clamp(0, true_width as i32 - 1) as usize;
321 *o = gain * i32::from(reference[y * stride + x]);
322 }
323 continue;
324 }
325 hpass_row(reference, y * stride, true_width, x0, taps, out);
326 }
327}
328
329/// lane-perf2: one output row of the vertical pass, accumulated tap-major so
330/// the inner loop walks two contiguous `i32` slices (vectorisable) instead of
331/// striding the intermediate by `block_w` per tap. A zero tap is skipped --
332/// adding `0 * x` is exactly nothing, and the 4-tap kernels zero four of the
333/// eight slots. `acc` is left holding the unrounded sums.
334#[inline]
335fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
336 acc.fill(0);
337 for (t, &tap) in taps.iter().enumerate() {
338 if tap == 0 {
339 continue;
340 }
341 let base = (row + t) * block_w;
342 for (a, &s) in acc.iter_mut().zip(&intermediate[base..base + block_w]) {
343 *a += tap * s;
344 }
345 }
346}
347
348thread_local! {
349 /// lane-perf2: the separable filter's intermediate buffer, reused across
350 /// calls -- a 4K inter frame runs `predict*` hundreds of thousands of
351 /// times and each call used to `vec![0i32; (block_h+7) * block_w]`. The
352 /// horizontal pass writes every element it later reads, so no clearing is
353 /// needed; the tail `block_w` elements are the vertical pass's row
354 /// accumulator.
355 static MC_SCRATCH: std::cell::RefCell<Vec<i32>> = const { std::cell::RefCell::new(Vec::new()) };
356}
357
358/// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus
359/// a `block_w` accumulator (see [`MC_SCRATCH`]).
360fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i32], &mut [i32]) -> R) -> R {
361 MC_SCRATCH.with(|s| {
362 let mut buf = s.borrow_mut();
363 let need = rows * block_w + block_w;
364 if buf.len() < need {
365 buf.resize(need, 0);
366 }
367 let (inter, acc) = buf[..need].split_at_mut(rows * block_w);
368 f(inter, acc)
369 })
370}
371
372/// Predicts one `block_w * block_h` block into `dst`, row-major, from
373/// `reference` (row-major, stride `stride`, true content
374/// `true_width` x `true_height` -- a reference frame's decoded picture
375/// buffer can be wider/taller than the true frame it holds, when this
376/// encoder pads a picture to a whole number of superblocks; a spec decoder
377/// never codes syntax for those extra columns/rows, so motion compensation
378/// must clamp to the true extent, not the buffer's own stride).
379///
380/// `x_q4` / `y_q4` are the block's top-left position in the reference, in
381/// 1/16-pel units (an integer MV has its low 4 bits zero); this function
382/// splits each into its whole-sample part and its 0..16 fraction itself, so
383/// the caller need not pre-split a motion vector.
384///
385/// # Panics
386/// Panics when `dst` is not `block_w * block_h` long, or the reference is
387/// empty.
388#[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape
389pub fn predict(
390 reference: &[u16],
391 stride: usize,
392 true_width: usize,
393 true_height: usize,
394 x_q4: i32,
395 y_q4: i32,
396 block_w: usize,
397 block_h: usize,
398 dst: &mut [u16],
399) {
400 predict_with_filter(
401 reference,
402 stride,
403 true_width,
404 true_height,
405 x_q4,
406 y_q4,
407 block_w,
408 block_h,
409 InterpFilterKind::Regular,
410 dst,
411 );
412}
413
414/// [`predict`], selecting the interpolation filter kernel explicitly (spec
415/// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same
416/// kernel both directions.
417#[allow(clippy::too_many_arguments)]
418pub fn predict_with_filter(
419 reference: &[u16],
420 stride: usize,
421 true_width: usize,
422 true_height: usize,
423 x_q4: i32,
424 y_q4: i32,
425 block_w: usize,
426 block_h: usize,
427 filter_kind: InterpFilterKind,
428 dst: &mut [u16],
429) {
430 predict_with_filters(
431 reference,
432 stride,
433 true_width,
434 true_height,
435 x_q4,
436 y_q4,
437 block_w,
438 block_h,
439 filter_kind,
440 filter_kind,
441 dst,
442 );
443}
444
445/// [`predict_with_filter`], with the horizontal (`interp_filter[0]`) and
446/// vertical (`interp_filter[1]`) kernels chosen independently -- spec
447/// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),
448/// so the two passes can genuinely differ.
449#[allow(clippy::too_many_arguments)]
450pub fn predict_with_filters(
451 reference: &[u16],
452 stride: usize,
453 true_width: usize,
454 true_height: usize,
455 x_q4: i32,
456 y_q4: i32,
457 block_w: usize,
458 block_h: usize,
459 h_kind: InterpFilterKind,
460 v_kind: InterpFilterKind,
461 dst: &mut [u16],
462) {
463 predict_with_filters_kern(
464 reference, stride, true_width, true_height, x_q4, y_q4, block_w,
465 block_h, block_w, block_h, h_kind, v_kind, dst,
466 );
467}
468
469/// [`predict_with_filters`] with the 4-tap decision taken from the block's
470/// TRUE width/height (`kern_w`/`kern_h`) rather than the destination buffer's.
471/// libaom's `av1_get_interp_filter_params_with_block_size` (reconinter.h,
472/// called per axis from `inter_predictor` with `w` then `h`) picks the narrow
473/// kernel from the PREDICTION block's own dimensions; our inter path predicts
474/// a rectangular block over its enclosing square buffer, so a rect block whose
475/// chroma is 4 wide or 4 tall (luma 8x16 / 16x8 and taller kin) must still ask
476/// for the 4-tap kernel on that axis -- lane-rectchroma2 r1.
477#[allow(clippy::too_many_arguments)]
478pub fn predict_with_filters_kern(
479 reference: &[u16],
480 stride: usize,
481 true_width: usize,
482 true_height: usize,
483 x_q4: i32,
484 y_q4: i32,
485 block_w: usize,
486 block_h: usize,
487 kern_w: usize,
488 kern_h: usize,
489 h_kind: InterpFilterKind,
490 v_kind: InterpFilterKind,
491 dst: &mut [u16],
492) {
493 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
494 assert!(!reference.is_empty(), "a reference plane has samples");
495 INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
496
497 #[cfg(test)]
498 let stage_t = std::time::Instant::now();
499
500 let x0 = x_q4.div_euclid(16);
501 let xfrac = x_q4.rem_euclid(16) as usize;
502 let y0 = y_q4.div_euclid(16);
503 let yfrac = y_q4.rem_euclid(16) as usize;
504 if crate::envflags::env_flag!("EC_MC_TRACE") && block_w >= 4 {
505 eprintln!(
506 "EC_MC_CALL x_q4={x_q4} y_q4={y_q4} w={block_w} h={block_h} xfrac={xfrac} yfrac={yfrac} hk={h_kind:?} vk={v_kind:?} tw={true_width} th={true_height} stride={stride}"
507 );
508 }
509
510 // Whole-pel fast path: `SUBPEL_FILTERS[0]` is the identity tap (`128` at
511 // its centre, everything else `0`), and both rounding shifts are exactly
512 // that filter's own gain (see `INTER_ROUND_1`'s doc comment), so the two
513 // 8-tap passes reproduce the reference sample byte-for-byte here --
514 // `integer_mv_is_identity` below pins that. Skipping straight to a
515 // clamped copy is bit-identical, not an approximation: it matters
516 // because the motion search's own log/diamond stage (`motion.rs`) is
517 // whole-pel-only and calls `predict` for every candidate it prices, so
518 // this path is what most of a search's `predict` calls actually hit
519 // (measured: `stage_timing_breakdown_inter` attributed 403 of a 720p
520 // inter frame's 408ms motion-search bucket to `predict`, almost all of
521 // it whole-pel candidates from stage 1).
522 if xfrac == 0 && yfrac == 0 {
523 for row in 0..block_h {
524 let y = (y0 + row as i32).clamp(0, true_height as i32 - 1) as usize;
525 let row_base = y * stride;
526 let out = &mut dst[row * block_w..(row + 1) * block_w];
527 // lane-perf2: an interior row is one contiguous copy.
528 if x0 >= 0 && x0 as usize + block_w <= true_width {
529 if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) {
530 out.copy_from_slice(src);
531 continue;
532 }
533 }
534 for (col, o) in out.iter_mut().enumerate() {
535 let x = (x0 + col as i32).clamp(0, true_width as i32 - 1) as usize;
536 *o = reference[row_base + x];
537 }
538 }
539 #[cfg(test)]
540 crate::encode::stage_add(1, stage_t.elapsed());
541 return;
542 }
543
544 let (h_wide, h_narrow) = h_kind.tables();
545 let (v_wide, v_narrow) = v_kind.tables();
546 note_narrow_kern(block_w, block_h, kern_w, kern_h);
547 let h_filter = if kern_w <= 4 {
548 &h_narrow[xfrac]
549 } else {
550 &h_wide[xfrac]
551 };
552 let v_filter = if kern_h <= 4 {
553 &v_narrow[yfrac]
554 } else {
555 &v_wide[yfrac]
556 };
557
558 // The vertical pass reads 3 rows above and 4 below the block, so the
559 // horizontal pass must produce that many extra intermediate rows.
560 // A whole-pel vertical position needs neither the 3 rows above nor the 4
561 // below, and its vertical pass is the identity tap: `Round2(128 * a,
562 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the
563 // block's own first row where the pass would have put the 4th.
564 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
565 let max = crate::decode::sample_max();
566 with_scratch(rows, block_w, |intermediate, acc| {
567 horizontal_pass_unscaled(
568 reference, stride, true_width, true_height, x0,
569 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
570 intermediate,
571 );
572 if yfrac == 0 {
573 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
574 *d = round2(a, INTER_ROUND_1 - 7).clamp(0, max) as u16;
575 }
576 return;
577 }
578 for row in 0..block_h {
579 vpass_row(intermediate, block_w, row, v_filter, acc);
580 for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {
581 *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;
582 }
583 }
584 });
585
586 #[cfg(test)]
587 crate::encode::stage_add(1, stage_t.elapsed());
588}
589
590/// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h`
591/// `REF_NO_SCALE`): `x_scale_fp == REF_NO_SCALE` means the stored reference's
592/// luma width equals the current frame's, so [`predict_scaled`] reduces
593/// exactly to [`predict_with_filters`] (verified in
594/// `predict_scaled_at_no_scale_matches_predict_with_filters` below).
595pub const REF_NO_SCALE: i64 = 1 << 14;
596
597/// The horizontal scale ratio spec 7.11.3.3 derives from luma widths only
598/// (libaom `av1_setup_scale_factors_for_frame`, luma widths, `REF_SCALE_SHIFT
599/// == 14`): `other_width` is the stored reference picture's own luma width,
600/// `this_width` the current frame's coded luma width. AV1 superres never
601/// scales height (r8's derivation), so there is no vertical counterpart.
602pub fn scale_factor(other_width: usize, this_width: usize) -> i64 {
603 (((other_width as i64) << 14) + this_width as i64 / 2) / this_width as i64
604}
605
606thread_local! {
607 /// lane-superres r10: firing count for the bypass gate (class
608 /// `gate-blind-to-feature`) -- how many times [`predict_scaled`] itself
609 /// ran, so the gate can hard-assert the scaled MC path actually fired
610 /// rather than trust a pixel match alone (an unscaled reference would
611 /// pass the pixels and prove nothing).
612 static PREDICT_SCALED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
613}
614
615/// Current value of [`PREDICT_SCALED_HITS`].
616pub fn predict_scaled_hits() -> usize {
617 PREDICT_SCALED_HITS.with(|c| c.get())
618}
619
620thread_local! {
621 /// lane-hbdinter: how many inter predictions this thread has produced
622 /// (single-reference, scaled, and the compound intermediate entry). The
623 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
624 /// only intra blocks cannot pass it by construction (class
625 /// `gate-blind-to-feature`).
626 static INTER_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
627
628 /// lane-rectchroma2 r1: how often the 4-tap decision came out DIFFERENT
629 /// from what the destination buffer's own dimensions would have given --
630 /// i.e. how often a rectangular block predicted over its enclosing square
631 /// buffer asked for libaom's narrow kernel on an axis. Zero means a gate
632 /// never exercised the rect-chroma shape at all.
633 static RECT_NARROW_KERN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
634}
635
636/// Current value of [`RECT_NARROW_KERN_HITS`].
637pub fn rect_narrow_kern_hits() -> usize {
638 RECT_NARROW_KERN_HITS.with(|c| c.get())
639}
640
641/// Resets [`RECT_NARROW_KERN_HITS`] (per-attempt counting, class
642/// `counter-from-refused-stream`).
643pub fn reset_rect_narrow_kern_hits() {
644 RECT_NARROW_KERN_HITS.with(|c| c.set(0));
645}
646
647/// Bumps [`RECT_NARROW_KERN_HITS`] when the block's true dims pick a kernel
648/// the destination buffer's dims would not have.
649fn note_narrow_kern(block_w: usize, block_h: usize, kern_w: usize, kern_h: usize) {
650 if (kern_w <= 4) != (block_w <= 4) || (kern_h <= 4) != (block_h <= 4) {
651 RECT_NARROW_KERN_HITS.with(|c| c.set(c.get() + 1));
652 }
653}
654
655/// Current value of [`INTER_PRED_HITS`].
656pub fn inter_pred_hits() -> usize {
657 INTER_PRED_HITS.with(|c| c.get())
658}
659
660fn round_pow2_64(value: i64, shift: u32) -> i64 {
661 if shift == 0 {
662 value
663 } else {
664 (value + (1i64 << (shift - 1))) >> shift
665 }
666}
667
668/// `ROUND_POWER_OF_TWO_SIGNED` (libaom `common/common.h`): halves round away
669/// from zero's *magnitude* -- negative inputs are rounded like their
670/// negation, not truncated toward zero the way a plain arithmetic shift
671/// would.
672fn round_pow2_signed_64(value: i64, shift: u32) -> i64 {
673 if value < 0 {
674 -round_pow2_64(-value, shift)
675 } else {
676 round_pow2_64(value, shift)
677 }
678}
679
680/// Spec 7.11.3.3's horizontal pass on a (possibly) scaled reference, shared
681/// by [`predict_scaled`] and [`predict_compound_intermediate`] -- the two
682/// differ only in their VERTICAL rounding ([`INTER_ROUND_1`] vs
683/// [`INTER_ROUND_1_COMPOUND`]), never here. Each output column walks the
684/// reference by `x_step_qn` (the Q14 scale rounded down to the Q10
685/// `SCALE_SUBPEL_BITS` grid) and picks its own filter phase from the low
686/// bits, so `x_scale_fp == REF_NO_SCALE` reduces to the ordinary stride-1
687/// whole-pel walk with one fixed phase (pinned by
688/// `predict_scaled_at_no_scale_matches_predict_with_filters`).
689#[allow(clippy::too_many_arguments)]
690fn horizontal_scaled_pass(
691 reference: &[u16],
692 stride: usize,
693 true_width: usize,
694 true_height: usize,
695 x_q4: i32,
696 y0: i32,
697 x_scale_fp: i64,
698 block_w: usize,
699 kern_w: usize,
700 rows: usize,
701 h_kind: InterpFilterKind,
702 intermediate: &mut [i32],
703) {
704 let x_step_qn = round_pow2_64(x_scale_fp, 4);
705 let off = (x_scale_fp - REF_NO_SCALE) * 8;
706 let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32;
707 let (h_wide, h_narrow) = h_kind.tables();
708 for c in 0..block_w {
709 let x_qn = pos_x_q10 + c as i64 * x_step_qn;
710 let int_pel = (x_qn >> 10) as i32;
711 let filter_idx = ((x_qn & 1023) >> 6) as usize;
712 let h_filter = if kern_w <= 4 {
713 &h_narrow[filter_idx]
714 } else {
715 &h_wide[filter_idx]
716 };
717 for r in 0..rows {
718 let y = y0 - 3 + r as i32;
719 let mut sum = 0;
720 for (t, &tap) in h_filter.iter().enumerate() {
721 let x = int_pel + t as i32 - 3;
722 sum += tap * sample(reference, stride, true_width, true_height, x, y);
723 }
724 intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
725 }
726 }
727}
728
729/// lane-perf2: the horizontal pass every two-pass entry point takes.
730/// `horizontal_scaled_pass` was carrying the UNSCALED work too (every
731/// compound prediction goes through it whatever the reference's scale), and
732/// its per-column walk re-derives an integer position and a filter phase
733/// that are constant at `REF_NO_SCALE`, reads the reference column-major,
734/// and clamps per tap -- 14% of decode self time. At `REF_NO_SCALE` the
735/// scaled walk reduces algebraically to `x0 = x_q4 / 16`, phase `x_q4 % 16`
736/// (`pos_x_q10 == x_q4 * 64 + 32`, so `int_pel == x0` and
737/// `(x_qn & 1023) >> 6 == xfrac` for every column), which is exactly
738/// [`horizontal_pass_unscaled`] -- and
739/// `predict_scaled_at_no_scale_matches_predict_with_filters` pins that
740/// equality end to end. A genuinely scaled reference (superres) still takes
741/// the general path.
742#[allow(clippy::too_many_arguments)]
743fn horizontal_pass(
744 reference: &[u16],
745 stride: usize,
746 true_width: usize,
747 true_height: usize,
748 x_q4: i32,
749 y0: i32,
750 x_scale_fp: i64,
751 block_w: usize,
752 kern_w: usize,
753 rows: usize,
754 h_kind: InterpFilterKind,
755 intermediate: &mut [i32],
756) {
757 if x_scale_fp == REF_NO_SCALE {
758 let (h_wide, h_narrow) = h_kind.tables();
759 let xfrac = x_q4.rem_euclid(16) as usize;
760 let taps = if kern_w <= 4 { &h_narrow[xfrac] } else { &h_wide[xfrac] };
761 horizontal_pass_unscaled(
762 reference,
763 stride,
764 true_width,
765 true_height,
766 x_q4.div_euclid(16),
767 y0,
768 taps,
769 block_w,
770 rows,
771 intermediate,
772 );
773 return;
774 }
775 horizontal_scaled_pass(
776 reference, stride, true_width, true_height, x_q4, y0, x_scale_fp, block_w, kern_w,
777 rows, h_kind, intermediate,
778 );
779}
780
781/// [`predict_with_filters`]'s scaled-reference counterpart (spec 7.11.3.3):
782/// used only when the stored reference's luma width differs from the current
783/// frame's (`use_superres` on a non-key frame). `x_scale_fp` is
784/// [`scale_factor`]'s ratio ([`REF_NO_SCALE`] reproduces
785/// `predict_with_filters` bit-exact, pinned by
786/// `predict_scaled_at_no_scale_matches_predict_with_filters`). Per r8's
787/// derivation AV1 superres never scales height, so `y_q4`'s whole-sample /
788/// fraction split and the vertical pass are untouched -- only the horizontal
789/// pass's per-column integer position and filter phase come from a scaled
790/// walk (`x_qn`) instead of a fixed stride-1 one.
791///
792/// # Panics
793/// Panics when `dst` is not `block_w * block_h` long, or the reference is
794/// empty.
795#[allow(clippy::too_many_arguments)]
796pub fn predict_scaled(
797 reference: &[u16],
798 stride: usize,
799 true_width: usize,
800 true_height: usize,
801 x_q4: i32,
802 y_q4: i32,
803 x_scale_fp: i64,
804 block_w: usize,
805 block_h: usize,
806 h_kind: InterpFilterKind,
807 v_kind: InterpFilterKind,
808 dst: &mut [u16],
809) {
810 predict_scaled_kern(
811 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
812 block_w, block_h, block_w, block_h, h_kind, v_kind, dst,
813 );
814}
815
816/// [`predict_scaled`] with the 4-tap decision from the block's true dims
817/// (see [`predict_with_filters_kern`]).
818#[allow(clippy::too_many_arguments)]
819pub fn predict_scaled_kern(
820 reference: &[u16],
821 stride: usize,
822 true_width: usize,
823 true_height: usize,
824 x_q4: i32,
825 y_q4: i32,
826 x_scale_fp: i64,
827 block_w: usize,
828 block_h: usize,
829 kern_w: usize,
830 kern_h: usize,
831 h_kind: InterpFilterKind,
832 v_kind: InterpFilterKind,
833 dst: &mut [u16],
834) {
835 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
836 assert!(!reference.is_empty(), "a reference plane has samples");
837 INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
838 PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1));
839
840 let y0 = y_q4.div_euclid(16);
841 let yfrac = y_q4.rem_euclid(16) as usize;
842
843 // SCALE_SUBPEL_BITS == 10: x_step_qn is x_scale_fp (Q14) rounded down to
844 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
845 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
846 let (v_wide, v_narrow) = v_kind.tables();
847 note_narrow_kern(block_w, block_h, kern_w, kern_h);
848 let v_filter = if kern_h <= 4 {
849 &v_narrow[yfrac]
850 } else {
851 &v_wide[yfrac]
852 };
853
854 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
855 let max = crate::decode::sample_max();
856 with_scratch(rows, block_w, |intermediate, acc| {
857 horizontal_pass(
858 reference, stride, true_width, true_height, x_q4,
859 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
860 kern_w, rows, h_kind, intermediate,
861 );
862 if yfrac == 0 {
863 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
864 *d = round2(a, INTER_ROUND_1 - 7).clamp(0, max) as u16;
865 }
866 return;
867 }
868 for row in 0..block_h {
869 vpass_row(intermediate, block_w, row, v_filter, acc);
870 for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {
871 *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;
872 }
873 }
874 });
875}
876
877/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch,
878/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than
879/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain
880/// (still above 8-bit pixel range) instead of a finished sample --
881/// `predict_compound_intermediate` below stops there and leaves the final
882/// clip to whichever combine step (simple/distance-weighted average, or a
883/// future masked blend) runs on the pair of intermediates.
884const INTER_ROUND_1_COMPOUND: u32 = 7;
885
886/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 +
887/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) ==
888/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS`
889/// (below) into one final shift.
890const INTER_POST_ROUND: u32 = 4;
891
892/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two
893/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether
894/// they are the simple-average split (8/8) or a distance-weighted split
895/// from [`crate::compound::dist_wtd_comp_weight_assign`].
896const DIST_PRECISION_BITS: u32 = 4;
897
898/// [`predict_with_filters`]'s compound counterpart: same two-pass separable
899/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`]
900/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the
901/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two
902/// per-reference predictions in until [`combine_compound`] blends them.
903/// `dst` receives one `i32` per sample, row-major, same shape as
904/// [`predict_with_filters`]'s `u8` `dst`.
905///
906/// # Panics
907/// Panics when `dst` is not `block_w * block_h` long, or the reference is
908/// empty.
909#[allow(clippy::too_many_arguments)]
910pub fn predict_compound_intermediate(
911 reference: &[u16],
912 stride: usize,
913 true_width: usize,
914 true_height: usize,
915 x_q4: i32,
916 y_q4: i32,
917 x_scale_fp: i64,
918 block_w: usize,
919 block_h: usize,
920 h_kind: InterpFilterKind,
921 v_kind: InterpFilterKind,
922 dst: &mut [i32],
923) {
924 predict_compound_intermediate_kern(
925 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
926 block_w, block_h, block_w, block_h, h_kind, v_kind, dst,
927 );
928}
929
930/// [`predict_compound_intermediate`] with the 4-tap decision from the block's
931/// true dims (see [`predict_with_filters_kern`]).
932#[allow(clippy::too_many_arguments)]
933pub fn predict_compound_intermediate_kern(
934 reference: &[u16],
935 stride: usize,
936 true_width: usize,
937 true_height: usize,
938 x_q4: i32,
939 y_q4: i32,
940 x_scale_fp: i64,
941 block_w: usize,
942 block_h: usize,
943 kern_w: usize,
944 kern_h: usize,
945 h_kind: InterpFilterKind,
946 v_kind: InterpFilterKind,
947 dst: &mut [i32],
948) {
949 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
950 assert!(!reference.is_empty(), "a reference plane has samples");
951 INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
952
953 if x_scale_fp != REF_NO_SCALE {
954 PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1));
955 }
956
957 let y0 = y_q4.div_euclid(16);
958 let yfrac = y_q4.rem_euclid(16) as usize;
959 if crate::envflags::env_flag!("EC_MC_TRACE") {
960 eprintln!("EC_MC_COMP x_q4={x_q4} y_q4={y_q4} w={block_w} h={block_h} hk={h_kind:?} vk={v_kind:?}");
961 }
962
963 let (v_wide, v_narrow) = v_kind.tables();
964 note_narrow_kern(block_w, block_h, kern_w, kern_h);
965 let v_filter = if kern_h <= 4 {
966 &v_narrow[yfrac]
967 } else {
968 &v_wide[yfrac]
969 };
970
971 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
972 with_scratch(rows, block_w, |intermediate, acc| {
973 horizontal_pass(
974 reference, stride, true_width, true_height, x_q4,
975 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
976 kern_w, rows, h_kind, intermediate,
977 );
978 if yfrac == 0 {
979 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
980 dst.copy_from_slice(&intermediate[..dst.len()]);
981 return;
982 }
983 for row in 0..block_h {
984 vpass_row(intermediate, block_w, row, v_filter, acc);
985 for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {
986 *d = round2(a, INTER_ROUND_1_COMPOUND);
987 }
988 }
989 });
990}
991
992/// Blends two [`predict_compound_intermediate`] outputs into a finished
993/// 8-bit block (spec 7.11.3.15's weighted-average combine, the
994/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the
995/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
996/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
997/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
998/// function does not cover -- decode.rs still refuses those by name.
999pub fn combine_compound(
1000 pred0: &[i32],
1001 pred1: &[i32],
1002 fwd_weight: i32,
1003 bck_weight: i32,
1004 dst: &mut [u16],
1005) {
1006 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1007 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
1008 for i in 0..dst.len() {
1009 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
1010 // applies the two shifts SEPARATELY: a truncating `>>
1011 // DIST_PRECISION_BITS` on the weighted sum, then `ROUND_POWER_OF_TWO`
1012 // by `round_bits == INTER_POST_ROUND`. Folding them into one
1013 // `Round2(sum, 8)` is NOT the same function -- it rounds up one LSB
1014 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
1015 // dropped low 4 bits are non-zero.
1016 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
1017 dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)
1018 .clamp(0, crate::decode::sample_max()) as u16;
1019 }
1020}
1021
1022/// lane-maskcomp r2: `build_compound_diffwtd_mask` (reconinter.c) --
1023/// `DIFFWTD_38`/`DIFFWTD_38_INV` (`mask_type` bit: 0/1). Operates directly on
1024/// the two [`predict_compound_intermediate`] outputs: libaom's own
1025/// `av1_build_compound_diffwtd_mask_d16_c` runs on its CONV_BUF domain (which
1026/// carries a constant `round_offset` bias baked into every sample by its
1027/// convolve stage), but `abs(src0 - src1)` cancels an equal bias on both
1028/// sides exactly, so the unbiased `i32` intermediates this crate already
1029/// produces give the identical `diff` libaom computes. `round` is
1030/// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
1031/// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
1032pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) {
1033 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1034 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
1035 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
1036 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
1037 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
1038 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
1039 // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
1040 let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth()).saturating_sub(8);
1041 for i in 0..mask.len() {
1042 let diff = round2((pred0[i] - pred1[i]).abs(), round);
1043 let m = (38 + diff / 16).clamp(0, 64);
1044 mask[i] = if inv { (64 - m) as u8 } else { m as u8 };
1045 }
1046}
1047
1048/// lane-maskcomp r2: `aom_lowbd_blend_a64_d16_mask_c` (blend_a64_mask.c),
1049/// algebraically simplified to this crate's unbiased `i32` intermediate
1050/// domain the same way [`diffwtd_mask`]'s doc comment derives -- libaom's
1051/// `res -= round_offset` step cancels exactly against the bias `m + (64-m)
1052/// == 64` contributes equally from both inputs, leaving `(m*pred0 +
1053/// (64-m)*pred1) >> 6` (a plain, unrounded shift, matching the C `>>` on
1054/// `int32_t`) then one final [`round2`] by [`INTER_POST_ROUND`]. `mask` is
1055/// always the LUMA-resolution mask (`mask_stride` == luma block width);
1056/// `subsampled` selects the 2x2-average chroma read (spec 7.11.3.14 /
1057/// libaom's `subw == 1 && subh == 1` branch) vs. the direct luma read.
1058#[allow(clippy::too_many_arguments)]
1059pub fn blend_masked_compound(
1060 pred0: &[i32],
1061 pred1: &[i32],
1062 mask: &[u8],
1063 mask_stride: usize,
1064 w: usize,
1065 h: usize,
1066 subsampled: bool,
1067 dst: &mut [u16],
1068) {
1069 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
1070 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
1071 assert_eq!(dst.len(), w * h, "the destination is the block");
1072 for i in 0..h {
1073 for j in 0..w {
1074 let m = if subsampled {
1075 let idx = (2 * i) * mask_stride + 2 * j;
1076 round2(
1077 i32::from(mask[idx])
1078 + i32::from(mask[idx + 1])
1079 + i32::from(mask[idx + mask_stride])
1080 + i32::from(mask[idx + mask_stride + 1]),
1081 2,
1082 )
1083 } else {
1084 i32::from(mask[i * mask_stride + j])
1085 };
1086 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
1087 dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max()) as u16;
1088 }
1089 }
1090}
1091
1092/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass
1093/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a
1094/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 ==
1095/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path
1096/// keeps over [`predict`]'s 11-bit round survives untouched) --
1097/// [`combine_compound`] then divides that back out exactly with an 8/8
1098/// simple-average weight split, so a compound block whose two references
1099/// (and MVs) happen to coincide reproduces the plain source sample, not an
1100/// off-by-one from double rounding.
1101#[test]
1102fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1103 let reference = vec![100u16; 16 * 16];
1104 let mut pred0 = vec![0i32; 16];
1105 predict_compound_intermediate(
1106 &reference,
1107 16,
1108 16,
1109 16,
1110 0,
1111 0,
1112 REF_NO_SCALE,
1113 4,
1114 4,
1115 InterpFilterKind::Regular,
1116 InterpFilterKind::Regular,
1117 &mut pred0,
1118 );
1119 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
1120
1121 let pred1 = pred0.clone();
1122 let mut dst = vec![0u16; 16];
1123 combine_compound(&pred0, &pred1, 8, 8, &mut dst);
1124 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129 use super::{
1130 InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter,
1131 predict_with_filters,
1132 };
1133
1134 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
1135 /// inter block at the frame's top-left corner (mv q4 = (row 7, col 15),
1136 /// bw=bh=16) predicted the wrong value because this decoder always used
1137 /// the REGULAR filter table -- aomdec's own `av1_convolve_2d_sr_c` trace
1138 /// showed this block actually used `EIGHTTAP_SMOOTH`
1139 /// (`0 0 2 34 62 28 2 0` at xfrac=15, not REGULAR's `0 0 -2 8 126 -6 2
1140 /// 0`). Window and expected output dumped straight from an
1141 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
1142 #[test]
1143 fn smooth_filter_matches_aomdec_chroma_inter_block() {
1144 #[rustfmt::skip]
1145 let window: [[u8; 24]; 24] = [
1146 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1147 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1148 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1149 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1150 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1151 [114,114,114,114,114,114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116,115,115,115],
1152 [114,114,114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,116,116,115,115,115,115],
1153 [113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,116,116,116,116,115,115,115,115],
1154 [113,113,113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,115,115,115,115,115,115],
1155 [112,112,112,112,112,112,112,112,112,113,113,113,113,114,114,114,114,114,115,115,115,115,115,115],
1156 [111,111,111,111,111,111,111,111,112,112,112,112,113,113,113,113,114,114,114,114,115,115,115,115],
1157 [110,110,110,110,110,110,110,110,111,111,111,111,112,112,112,113,113,113,113,113,114,114,114,115],
1158 [109,109,109,109,109,109,109,110,110,110,110,111,111,111,111,112,112,112,112,113,113,114,114,114],
1159 [108,108,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111,111,111,112,112,113,113,113],
1160 [108,108,108,108,108,108,108,108,108,108,109,109,109,110,110,110,110,110,111,111,112,112,112,112],
1161 [107,107,107,107,107,107,107,107,107,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111],
1162 [106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,110,110,110],
1163 [106,106,106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,109],
1164 [105,105,105,105,105,105,105,105,106,106,106,107,107,107,107,108,108,108,108,108,108,108,108,109],
1165 [104,104,104,104,104,104,104,104,104,105,105,106,106,106,107,107,107,107,107,107,107,108,108,108],
1166 [102,102,102,102,102,103,103,103,103,104,104,105,105,105,106,106,107,107,107,107,107,107,107,107],
1167 [101,101,101,101,101,101,101,102,102,103,103,104,104,104,105,105,106,106,106,106,106,107,107,107],
1168 [100,100,100,100,100,100,100,101,101,102,102,103,103,104,104,105,105,105,106,106,106,106,106,106],
1169 [99,99,99,99,99,99,100,100,100,101,101,102,103,103,104,104,105,105,105,105,105,105,105,106],
1170 ];
1171 // The dumped window spans real cols/rows -4..19; the block itself
1172 // starts at real (0, 0), so pad the reference plane so col/row 4 of
1173 // this buffer is real col/row 0, and hand `predict_with_filter` the
1174 // real (0, 0) coordinates -- clamping then reproduces the identical
1175 // extended border the dump already captured.
1176 let stride = 24;
1177 let mut reference = vec![0u16; stride * 24];
1178 for (r, row) in window.iter().enumerate() {
1179 for (c, &v) in row.iter().enumerate() {
1180 reference[r * stride + c] = u16::from(v);
1181 }
1182 }
1183 // predict()'s own edge clamp starts at true (0,0); shift so the
1184 // dumped window's row/col 4 lands there by biasing x_q4/y_q4's
1185 // whole-pel part by -4 and reading from a plane whose true origin
1186 // is the window's row/col 4 -- simplest is to pass true_width /
1187 // true_height covering the whole dumped window and offset the
1188 // whole-pel part of x_q4/y_q4 by +4 to land on real (0,0).
1189 let x_q4 = (4 + 0) * 16 + 15; // real block x0=0, xfrac=15
1190 let y_q4 = (4 + 0) * 16 + 7; // real block y0=0, yfrac=7
1191 let mut dst = vec![0u16; 16 * 16];
1192 predict_with_filter(
1193 &reference,
1194 stride,
1195 24,
1196 24,
1197 x_q4,
1198 y_q4,
1199 16,
1200 16,
1201 InterpFilterKind::Smooth,
1202 &mut dst,
1203 );
1204 #[rustfmt::skip]
1205 let expected_row0: [u16; 16] =
1206 [114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116];
1207 assert_eq!(
1208 &dst[0..16],
1209 &expected_row0,
1210 "row0 vs aomdec's real av1_convolve_2d_sr_c output"
1211 );
1212 #[rustfmt::skip]
1213 let expected_row15: [u16; 16] =
1214 [103,103,104,104,104,105,105,106,106,106,107,107,107,107,107,107];
1215 assert_eq!(
1216 &dst[15 * 16..15 * 16 + 16],
1217 &expected_row15,
1218 "row15 vs aomdec"
1219 );
1220 }
1221
1222 /// lane-gmaffine r5 root cause: a block 4 or fewer samples wide reads
1223 /// `Subpel_Filters[4]` -- the REGULAR narrow kernel -- for BOTH
1224 /// `EIGHTTAP` and `EIGHTTAP_SHARP` (spec 7.11.3.4's `filterIdx`, libaom
1225 /// `av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`,
1226 /// `filter.h:243`). We used the 8-tap sharp kernel there, which is
1227 /// invisible above 4 samples and so only ever bit the 4x4 chroma of an
1228 /// 8x8 (or smaller) luma leaf.
1229 #[test]
1230 fn a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness() {
1231 use crate::mc::{SUBPEL_FILTERS_4, SUBPEL_FILTERS_BILINEAR, SUBPEL_FILTERS_SMOOTH_4};
1232 for kind in [
1233 InterpFilterKind::Regular,
1234 InterpFilterKind::Smooth,
1235 InterpFilterKind::Sharp,
1236 InterpFilterKind::Bilinear,
1237 ] {
1238 let (wide, narrow) = kind.tables();
1239 let want: &[[i32; 8]; 16] = match kind {
1240 InterpFilterKind::Regular | InterpFilterKind::Sharp => &SUBPEL_FILTERS_4,
1241 InterpFilterKind::Smooth => &SUBPEL_FILTERS_SMOOTH_4,
1242 InterpFilterKind::Bilinear => &SUBPEL_FILTERS_BILINEAR,
1243 };
1244 assert_eq!(narrow, want, "{kind:?}: wrong narrow-block kernel");
1245 if kind == InterpFilterKind::Sharp {
1246 assert_ne!(wide, narrow, "sharp's wide kernel is not its narrow one");
1247 }
1248 }
1249 }
1250
1251 #[test]
1252 fn integer_mv_is_identity() {
1253 let width = 12;
1254 let height = 12;
1255 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
1256 let mut dst = vec![0u16; 6 * 6];
1257 predict(
1258 &reference,
1259 width,
1260 width,
1261 height,
1262 3 * 16,
1263 4 * 16,
1264 6,
1265 6,
1266 &mut dst,
1267 );
1268 for row in 0..6 {
1269 for col in 0..6 {
1270 assert_eq!(
1271 dst[row * 6 + col],
1272 reference[(4 + row) * width + 3 + col],
1273 "integer MV must reproduce the reference block byte-for-byte"
1274 );
1275 }
1276 }
1277 }
1278
1279 #[test]
1280 fn half_pel_reproduces_the_ramp_midpoint() {
1281 // Step 2 so every half-pel position lands on an exact integer.
1282 let width = 16;
1283 let height = 16;
1284 let reference: Vec<u16> = (0..width * height)
1285 .map(|i| (2 * (i % width)) as u16)
1286 .collect();
1287 let mut dst = vec![0u16; 4 * 4];
1288 // Half-pel in x only: fraction 8/16, integer part at column 5.
1289 predict(
1290 &reference,
1291 width,
1292 width,
1293 height,
1294 5 * 16 + 8,
1295 5 * 16,
1296 4,
1297 4,
1298 &mut dst,
1299 );
1300 for row in 0..4 {
1301 for col in 0..4 {
1302 let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1
1303 assert_eq!(
1304 dst[row * 4 + col] as i32,
1305 midpoint as i32,
1306 "half-pel MV over a linear ramp must land exactly on the midpoint"
1307 );
1308 }
1309 }
1310 }
1311
1312 #[test]
1313 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
1314 let width = 20;
1315 let height = 20;
1316 let reference = vec![142u16; width * height];
1317 for yfrac in 0..16 {
1318 for xfrac in 0..16 {
1319 let mut dst = vec![0u16; 5 * 5];
1320 predict(
1321 &reference,
1322 width,
1323 width,
1324 height,
1325 5 * 16 + xfrac,
1326 5 * 16 + yfrac,
1327 5,
1328 5,
1329 &mut dst,
1330 );
1331 assert!(
1332 dst.iter().all(|&v| v == 142),
1333 "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}"
1334 );
1335 }
1336 }
1337 }
1338
1339 #[test]
1340 fn horizontal_and_vertical_only_filtering_differ() {
1341 // A plane linear in both x and y with different, even coefficients so
1342 // each axis's half-pel interpolation lands on an exact integer: this
1343 // pins the actual value each pass produces, not just that the two
1344 // differ, so swapping which pass reads which axis is caught even if
1345 // it happened to produce two merely-different numbers.
1346 let width = 10;
1347 let height = 10;
1348 let reference: Vec<u16> = (0..height)
1349 .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u16))
1350 .collect();
1351
1352 let mut horiz = vec![0u16; 4 * 4];
1353 predict(
1354 &reference,
1355 width,
1356 width,
1357 height,
1358 3 * 16 + 8,
1359 3 * 16,
1360 4,
1361 4,
1362 &mut horiz,
1363 );
1364 let mut vert = vec![0u16; 4 * 4];
1365 predict(
1366 &reference,
1367 width,
1368 width,
1369 height,
1370 3 * 16,
1371 3 * 16 + 8,
1372 4,
1373 4,
1374 &mut vert,
1375 );
1376
1377 for row in 0..4 {
1378 for col in 0..4 {
1379 // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put.
1380 assert_eq!(
1381 horiz[row * 4 + col] as i32,
1382 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32),
1383 "horizontal-only MV must interpolate along x only"
1384 );
1385 // Vertical half-pel: y interpolates to y0+row+0.5, x stays put.
1386 assert_eq!(
1387 vert[row * 4 + col] as i32,
1388 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2,
1389 "vertical-only MV must interpolate along y only"
1390 );
1391 }
1392 }
1393 assert_ne!(
1394 horiz, vert,
1395 "horizontal-only and vertical-only sub-pel MVs must give different outputs"
1396 );
1397 }
1398
1399 #[test]
1400 fn mv_past_the_edge_clamps_instead_of_panicking() {
1401 let width = 8;
1402 let height = 8;
1403 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
1404 let mut dst = vec![0u16; 4 * 4];
1405 // Whole-sample position far above and to the left of the plane, with
1406 // an odd fraction so both filter passes exercise the clamp.
1407 predict(
1408 &reference,
1409 width,
1410 width,
1411 height,
1412 -50 * 16 + 5,
1413 -50 * 16 + 5,
1414 4,
1415 4,
1416 &mut dst,
1417 );
1418 let expected = reference[0]; // the whole plane clamps to the top-left corner
1419 assert!(
1420 dst.iter().all(|&v| v == expected),
1421 "an MV past the top-left edge must clamp to the corner sample, got {dst:?}"
1422 );
1423
1424 let mut dst2 = vec![0u16; 4 * 4];
1425 predict(
1426 &reference,
1427 width,
1428 width,
1429 height,
1430 50 * 16 + 5,
1431 50 * 16 + 5,
1432 4,
1433 4,
1434 &mut dst2,
1435 );
1436 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
1437 assert!(
1438 dst2.iter().all(|&v| v == expected2),
1439 "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}"
1440 );
1441 }
1442
1443 #[test]
1444 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
1445 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
1446 // must reduce predict_scaled's per-column scaled walk to the exact
1447 // same int_pel/filter_idx sequence predict_with_filters computes from
1448 // a fixed stride-1 walk -- every subpel fraction, every block width.
1449 let width = 24;
1450 let height = 24;
1451 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
1452 for block_w in [4usize, 8, 16] {
1453 for x_frac in 0..16i32 {
1454 let x_q4 = 3 * 16 + x_frac;
1455 let y_q4 = 2 * 16 + 5;
1456 let mut expected = vec![0u16; block_w * 8];
1457 predict_with_filters(
1458 &reference,
1459 width,
1460 width,
1461 height,
1462 x_q4,
1463 y_q4,
1464 block_w,
1465 8,
1466 InterpFilterKind::Regular,
1467 InterpFilterKind::Regular,
1468 &mut expected,
1469 );
1470 let mut got = vec![0u16; block_w * 8];
1471 predict_scaled(
1472 &reference,
1473 width,
1474 width,
1475 height,
1476 x_q4,
1477 y_q4,
1478 REF_NO_SCALE,
1479 block_w,
1480 8,
1481 InterpFilterKind::Regular,
1482 InterpFilterKind::Regular,
1483 &mut got,
1484 );
1485 assert_eq!(
1486 got, expected,
1487 "block_w={block_w} x_frac={x_frac}: REF_NO_SCALE must reproduce predict_with_filters exactly"
1488 );
1489 }
1490 }
1491 }
1492}