forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB231663eTahinli3 months ago1475 commits

mc.rs1197 lines, 46.1 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/// Predicts one `block_w * block_h` block into `dst`, row-major, from
247/// `reference` (row-major, stride `stride`, true content
248/// `true_width` x `true_height` -- a reference frame's decoded picture
249/// buffer can be wider/taller than the true frame it holds, when this
250/// encoder pads a picture to a whole number of superblocks; a spec decoder
251/// never codes syntax for those extra columns/rows, so motion compensation
252/// must clamp to the true extent, not the buffer's own stride).
253///
254/// `x_q4` / `y_q4` are the block's top-left position in the reference, in
255/// 1/16-pel units (an integer MV has its low 4 bits zero); this function
256/// splits each into its whole-sample part and its 0..16 fraction itself, so
257/// the caller need not pre-split a motion vector.
258///
259/// # Panics
260/// Panics when `dst` is not `block_w * block_h` long, or the reference is
261/// empty.
262#[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape
263pub fn predict(
264 reference: &[u16],
265 stride: usize,
266 true_width: usize,
267 true_height: usize,
268 x_q4: i32,
269 y_q4: i32,
270 block_w: usize,
271 block_h: usize,
272 dst: &mut [u16],
273) {
274 predict_with_filter(
275 reference,
276 stride,
277 true_width,
278 true_height,
279 x_q4,
280 y_q4,
281 block_w,
282 block_h,
283 InterpFilterKind::Regular,
284 dst,
285 );
286}
287
288/// [`predict`], selecting the interpolation filter kernel explicitly (spec
289/// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same
290/// kernel both directions.
291#[allow(clippy::too_many_arguments)]
292pub fn predict_with_filter(
293 reference: &[u16],
294 stride: usize,
295 true_width: usize,
296 true_height: usize,
297 x_q4: i32,
298 y_q4: i32,
299 block_w: usize,
300 block_h: usize,
301 filter_kind: InterpFilterKind,
302 dst: &mut [u16],
303) {
304 predict_with_filters(
305 reference,
306 stride,
307 true_width,
308 true_height,
309 x_q4,
310 y_q4,
311 block_w,
312 block_h,
313 filter_kind,
314 filter_kind,
315 dst,
316 );
317}
318
319/// [`predict_with_filter`], with the horizontal (`interp_filter[0]`) and
320/// vertical (`interp_filter[1]`) kernels chosen independently -- spec
321/// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),
322/// so the two passes can genuinely differ.
323#[allow(clippy::too_many_arguments)]
324pub fn predict_with_filters(
325 reference: &[u16],
326 stride: usize,
327 true_width: usize,
328 true_height: usize,
329 x_q4: i32,
330 y_q4: i32,
331 block_w: usize,
332 block_h: usize,
333 h_kind: InterpFilterKind,
334 v_kind: InterpFilterKind,
335 dst: &mut [u16],
336) {
337 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
338 assert!(!reference.is_empty(), "a reference plane has samples");
339 INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
340
341 #[cfg(test)]
342 let stage_t = std::time::Instant::now();
343
344 let x0 = x_q4.div_euclid(16);
345 let xfrac = x_q4.rem_euclid(16) as usize;
346 let y0 = y_q4.div_euclid(16);
347 let yfrac = y_q4.rem_euclid(16) as usize;
348
349 // Whole-pel fast path: `SUBPEL_FILTERS[0]` is the identity tap (`128` at
350 // its centre, everything else `0`), and both rounding shifts are exactly
351 // that filter's own gain (see `INTER_ROUND_1`'s doc comment), so the two
352 // 8-tap passes reproduce the reference sample byte-for-byte here --
353 // `integer_mv_is_identity` below pins that. Skipping straight to a
354 // clamped copy is bit-identical, not an approximation: it matters
355 // because the motion search's own log/diamond stage (`motion.rs`) is
356 // whole-pel-only and calls `predict` for every candidate it prices, so
357 // this path is what most of a search's `predict` calls actually hit
358 // (measured: `stage_timing_breakdown_inter` attributed 403 of a 720p
359 // inter frame's 408ms motion-search bucket to `predict`, almost all of
360 // it whole-pel candidates from stage 1).
361 if xfrac == 0 && yfrac == 0 {
362 for row in 0..block_h {
363 let y = y0 + row as i32;
364 for col in 0..block_w {
365 let x = x0 + col as i32;
366 dst[row * block_w + col] =
367 sample(reference, stride, true_width, true_height, x, y) as u16;
368 }
369 }
370 #[cfg(test)]
371 crate::encode::stage_add(1, stage_t.elapsed());
372 return;
373 }
374
375 let (h_wide, h_narrow) = h_kind.tables();
376 let (v_wide, v_narrow) = v_kind.tables();
377 let h_filter = if block_w <= 4 {
378 &h_narrow[xfrac]
379 } else {
380 &h_wide[xfrac]
381 };
382 let v_filter = if block_h <= 4 {
383 &v_narrow[yfrac]
384 } else {
385 &v_wide[yfrac]
386 };
387
388 // The vertical pass reads 3 rows above and 4 below the block, so the
389 // horizontal pass must produce that many extra intermediate rows.
390 let rows = block_h + 7;
391 let mut intermediate = vec![0i32; rows * block_w];
392 for r in 0..rows {
393 let y = y0 - 3 + r as i32;
394 for c in 0..block_w {
395 let mut sum = 0;
396 for (t, &tap) in h_filter.iter().enumerate() {
397 let x = x0 + c as i32 + t as i32 - 3;
398 sum += tap * sample(reference, stride, true_width, true_height, x, y);
399 }
400 intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
401 }
402 }
403
404 for row in 0..block_h {
405 for col in 0..block_w {
406 let mut sum = 0;
407 for (t, &tap) in v_filter.iter().enumerate() {
408 sum += tap * intermediate[(row + t) * block_w + col];
409 }
410 dst[row * block_w + col] = round2(sum, INTER_ROUND_1).clamp(0, crate::decode::sample_max()) as u16;
411 }
412 }
413
414 #[cfg(test)]
415 crate::encode::stage_add(1, stage_t.elapsed());
416}
417
418/// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h`
419/// `REF_NO_SCALE`): `x_scale_fp == REF_NO_SCALE` means the stored reference's
420/// luma width equals the current frame's, so [`predict_scaled`] reduces
421/// exactly to [`predict_with_filters`] (verified in
422/// `predict_scaled_at_no_scale_matches_predict_with_filters` below).
423pub const REF_NO_SCALE: i64 = 1 << 14;
424
425/// The horizontal scale ratio spec 7.11.3.3 derives from luma widths only
426/// (libaom `av1_setup_scale_factors_for_frame`, luma widths, `REF_SCALE_SHIFT
427/// == 14`): `other_width` is the stored reference picture's own luma width,
428/// `this_width` the current frame's coded luma width. AV1 superres never
429/// scales height (r8's derivation), so there is no vertical counterpart.
430pub fn scale_factor(other_width: usize, this_width: usize) -> i64 {
431 (((other_width as i64) << 14) + this_width as i64 / 2) / this_width as i64
432}
433
434thread_local! {
435 /// lane-superres r10: firing count for the bypass gate (class
436 /// `gate-blind-to-feature`) -- how many times [`predict_scaled`] itself
437 /// ran, so the gate can hard-assert the scaled MC path actually fired
438 /// rather than trust a pixel match alone (an unscaled reference would
439 /// pass the pixels and prove nothing).
440 static PREDICT_SCALED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
441}
442
443/// Current value of [`PREDICT_SCALED_HITS`].
444pub fn predict_scaled_hits() -> usize {
445 PREDICT_SCALED_HITS.with(|c| c.get())
446}
447
448thread_local! {
449 /// lane-hbdinter: how many inter predictions this thread has produced
450 /// (single-reference, scaled, and the compound intermediate entry). The
451 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
452 /// only intra blocks cannot pass it by construction (class
453 /// `gate-blind-to-feature`).
454 static INTER_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
455}
456
457/// Current value of [`INTER_PRED_HITS`].
458pub fn inter_pred_hits() -> usize {
459 INTER_PRED_HITS.with(|c| c.get())
460}
461
462fn round_pow2_64(value: i64, shift: u32) -> i64 {
463 if shift == 0 {
464 value
465 } else {
466 (value + (1i64 << (shift - 1))) >> shift
467 }
468}
469
470/// `ROUND_POWER_OF_TWO_SIGNED` (libaom `common/common.h`): halves round away
471/// from zero's *magnitude* -- negative inputs are rounded like their
472/// negation, not truncated toward zero the way a plain arithmetic shift
473/// would.
474fn round_pow2_signed_64(value: i64, shift: u32) -> i64 {
475 if value < 0 {
476 -round_pow2_64(-value, shift)
477 } else {
478 round_pow2_64(value, shift)
479 }
480}
481
482/// Spec 7.11.3.3's horizontal pass on a (possibly) scaled reference, shared
483/// by [`predict_scaled`] and [`predict_compound_intermediate`] -- the two
484/// differ only in their VERTICAL rounding ([`INTER_ROUND_1`] vs
485/// [`INTER_ROUND_1_COMPOUND`]), never here. Each output column walks the
486/// reference by `x_step_qn` (the Q14 scale rounded down to the Q10
487/// `SCALE_SUBPEL_BITS` grid) and picks its own filter phase from the low
488/// bits, so `x_scale_fp == REF_NO_SCALE` reduces to the ordinary stride-1
489/// whole-pel walk with one fixed phase (pinned by
490/// `predict_scaled_at_no_scale_matches_predict_with_filters`).
491#[allow(clippy::too_many_arguments)]
492fn horizontal_scaled_pass(
493 reference: &[u16],
494 stride: usize,
495 true_width: usize,
496 true_height: usize,
497 x_q4: i32,
498 y0: i32,
499 x_scale_fp: i64,
500 block_w: usize,
501 rows: usize,
502 h_kind: InterpFilterKind,
503 intermediate: &mut [i32],
504) {
505 let x_step_qn = round_pow2_64(x_scale_fp, 4);
506 let off = (x_scale_fp - REF_NO_SCALE) * 8;
507 let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32;
508 let (h_wide, h_narrow) = h_kind.tables();
509 for c in 0..block_w {
510 let x_qn = pos_x_q10 + c as i64 * x_step_qn;
511 let int_pel = (x_qn >> 10) as i32;
512 let filter_idx = ((x_qn & 1023) >> 6) as usize;
513 let h_filter = if block_w <= 4 {
514 &h_narrow[filter_idx]
515 } else {
516 &h_wide[filter_idx]
517 };
518 for r in 0..rows {
519 let y = y0 - 3 + r as i32;
520 let mut sum = 0;
521 for (t, &tap) in h_filter.iter().enumerate() {
522 let x = int_pel + t as i32 - 3;
523 sum += tap * sample(reference, stride, true_width, true_height, x, y);
524 }
525 intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
526 }
527 }
528}
529
530/// [`predict_with_filters`]'s scaled-reference counterpart (spec 7.11.3.3):
531/// used only when the stored reference's luma width differs from the current
532/// frame's (`use_superres` on a non-key frame). `x_scale_fp` is
533/// [`scale_factor`]'s ratio ([`REF_NO_SCALE`] reproduces
534/// `predict_with_filters` bit-exact, pinned by
535/// `predict_scaled_at_no_scale_matches_predict_with_filters`). Per r8's
536/// derivation AV1 superres never scales height, so `y_q4`'s whole-sample /
537/// fraction split and the vertical pass are untouched -- only the horizontal
538/// pass's per-column integer position and filter phase come from a scaled
539/// walk (`x_qn`) instead of a fixed stride-1 one.
540///
541/// # Panics
542/// Panics when `dst` is not `block_w * block_h` long, or the reference is
543/// empty.
544#[allow(clippy::too_many_arguments)]
545pub fn predict_scaled(
546 reference: &[u16],
547 stride: usize,
548 true_width: usize,
549 true_height: usize,
550 x_q4: i32,
551 y_q4: i32,
552 x_scale_fp: i64,
553 block_w: usize,
554 block_h: usize,
555 h_kind: InterpFilterKind,
556 v_kind: InterpFilterKind,
557 dst: &mut [u16],
558) {
559 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
560 assert!(!reference.is_empty(), "a reference plane has samples");
561 INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
562 PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1));
563
564 let y0 = y_q4.div_euclid(16);
565 let yfrac = y_q4.rem_euclid(16) as usize;
566
567 // SCALE_SUBPEL_BITS == 10: x_step_qn is x_scale_fp (Q14) rounded down to
568 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
569 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
570 let (v_wide, v_narrow) = v_kind.tables();
571 let v_filter = if block_h <= 4 {
572 &v_narrow[yfrac]
573 } else {
574 &v_wide[yfrac]
575 };
576
577 let rows = block_h + 7;
578 let mut intermediate = vec![0i32; rows * block_w];
579 horizontal_scaled_pass(
580 reference,
581 stride,
582 true_width,
583 true_height,
584 x_q4,
585 y0,
586 x_scale_fp,
587 block_w,
588 rows,
589 h_kind,
590 &mut intermediate,
591 );
592
593 for row in 0..block_h {
594 for col in 0..block_w {
595 let mut sum = 0;
596 for (t, &tap) in v_filter.iter().enumerate() {
597 sum += tap * intermediate[(row + t) * block_w + col];
598 }
599 dst[row * block_w + col] =
600 round2(sum, INTER_ROUND_1).clamp(0, crate::decode::sample_max()) as u16;
601 }
602 }
603}
604
605/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch,
606/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than
607/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain
608/// (still above 8-bit pixel range) instead of a finished sample --
609/// `predict_compound_intermediate` below stops there and leaves the final
610/// clip to whichever combine step (simple/distance-weighted average, or a
611/// future masked blend) runs on the pair of intermediates.
612const INTER_ROUND_1_COMPOUND: u32 = 7;
613
614/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 +
615/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) ==
616/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS`
617/// (below) into one final shift.
618const INTER_POST_ROUND: u32 = 4;
619
620/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two
621/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether
622/// they are the simple-average split (8/8) or a distance-weighted split
623/// from [`crate::compound::dist_wtd_comp_weight_assign`].
624const DIST_PRECISION_BITS: u32 = 4;
625
626/// [`predict_with_filters`]'s compound counterpart: same two-pass separable
627/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`]
628/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the
629/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two
630/// per-reference predictions in until [`combine_compound`] blends them.
631/// `dst` receives one `i32` per sample, row-major, same shape as
632/// [`predict_with_filters`]'s `u8` `dst`.
633///
634/// # Panics
635/// Panics when `dst` is not `block_w * block_h` long, or the reference is
636/// empty.
637#[allow(clippy::too_many_arguments)]
638pub fn predict_compound_intermediate(
639 reference: &[u16],
640 stride: usize,
641 true_width: usize,
642 true_height: usize,
643 x_q4: i32,
644 y_q4: i32,
645 x_scale_fp: i64,
646 block_w: usize,
647 block_h: usize,
648 h_kind: InterpFilterKind,
649 v_kind: InterpFilterKind,
650 dst: &mut [i32],
651) {
652 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
653 assert!(!reference.is_empty(), "a reference plane has samples");
654 INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
655
656 if x_scale_fp != REF_NO_SCALE {
657 PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1));
658 }
659
660 let y0 = y_q4.div_euclid(16);
661 let yfrac = y_q4.rem_euclid(16) as usize;
662
663 let (v_wide, v_narrow) = v_kind.tables();
664 let v_filter = if block_h <= 4 {
665 &v_narrow[yfrac]
666 } else {
667 &v_wide[yfrac]
668 };
669
670 let rows = block_h + 7;
671 let mut intermediate = vec![0i32; rows * block_w];
672 horizontal_scaled_pass(
673 reference,
674 stride,
675 true_width,
676 true_height,
677 x_q4,
678 y0,
679 x_scale_fp,
680 block_w,
681 rows,
682 h_kind,
683 &mut intermediate,
684 );
685
686 for row in 0..block_h {
687 for col in 0..block_w {
688 let mut sum = 0;
689 for (t, &tap) in v_filter.iter().enumerate() {
690 sum += tap * intermediate[(row + t) * block_w + col];
691 }
692 dst[row * block_w + col] = round2(sum, INTER_ROUND_1_COMPOUND);
693 }
694 }
695}
696
697/// Blends two [`predict_compound_intermediate`] outputs into a finished
698/// 8-bit block (spec 7.11.3.15's weighted-average combine, the
699/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the
700/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
701/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
702/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
703/// function does not cover -- decode.rs still refuses those by name.
704pub fn combine_compound(
705 pred0: &[i32],
706 pred1: &[i32],
707 fwd_weight: i32,
708 bck_weight: i32,
709 dst: &mut [u16],
710) {
711 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
712 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
713 for i in 0..dst.len() {
714 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
715 // applies the two shifts SEPARATELY: a truncating `>>
716 // DIST_PRECISION_BITS` on the weighted sum, then `ROUND_POWER_OF_TWO`
717 // by `round_bits == INTER_POST_ROUND`. Folding them into one
718 // `Round2(sum, 8)` is NOT the same function -- it rounds up one LSB
719 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
720 // dropped low 4 bits are non-zero.
721 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
722 dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)
723 .clamp(0, crate::decode::sample_max()) as u16;
724 }
725}
726
727/// lane-maskcomp r2: `build_compound_diffwtd_mask` (reconinter.c) --
728/// `DIFFWTD_38`/`DIFFWTD_38_INV` (`mask_type` bit: 0/1). Operates directly on
729/// the two [`predict_compound_intermediate`] outputs: libaom's own
730/// `av1_build_compound_diffwtd_mask_d16_c` runs on its CONV_BUF domain (which
731/// carries a constant `round_offset` bias baked into every sample by its
732/// convolve stage), but `abs(src0 - src1)` cancels an equal bias on both
733/// sides exactly, so the unbiased `i32` intermediates this crate already
734/// produces give the identical `diff` libaom computes. `round` is
735/// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
736/// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
737pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) {
738 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
739 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
740 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
741 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
742 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
743 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
744 // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
745 let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth()).saturating_sub(8);
746 for i in 0..mask.len() {
747 let diff = round2((pred0[i] - pred1[i]).abs(), round);
748 let m = (38 + diff / 16).clamp(0, 64);
749 mask[i] = if inv { (64 - m) as u8 } else { m as u8 };
750 }
751}
752
753/// lane-maskcomp r2: `aom_lowbd_blend_a64_d16_mask_c` (blend_a64_mask.c),
754/// algebraically simplified to this crate's unbiased `i32` intermediate
755/// domain the same way [`diffwtd_mask`]'s doc comment derives -- libaom's
756/// `res -= round_offset` step cancels exactly against the bias `m + (64-m)
757/// == 64` contributes equally from both inputs, leaving `(m*pred0 +
758/// (64-m)*pred1) >> 6` (a plain, unrounded shift, matching the C `>>` on
759/// `int32_t`) then one final [`round2`] by [`INTER_POST_ROUND`]. `mask` is
760/// always the LUMA-resolution mask (`mask_stride` == luma block width);
761/// `subsampled` selects the 2x2-average chroma read (spec 7.11.3.14 /
762/// libaom's `subw == 1 && subh == 1` branch) vs. the direct luma read.
763#[allow(clippy::too_many_arguments)]
764pub fn blend_masked_compound(
765 pred0: &[i32],
766 pred1: &[i32],
767 mask: &[u8],
768 mask_stride: usize,
769 w: usize,
770 h: usize,
771 subsampled: bool,
772 dst: &mut [u16],
773) {
774 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
775 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
776 assert_eq!(dst.len(), w * h, "the destination is the block");
777 for i in 0..h {
778 for j in 0..w {
779 let m = if subsampled {
780 let idx = (2 * i) * mask_stride + 2 * j;
781 round2(
782 i32::from(mask[idx])
783 + i32::from(mask[idx + 1])
784 + i32::from(mask[idx + mask_stride])
785 + i32::from(mask[idx + mask_stride + 1]),
786 2,
787 )
788 } else {
789 i32::from(mask[i * mask_stride + j])
790 };
791 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
792 dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max()) as u16;
793 }
794 }
795}
796
797/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass
798/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a
799/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 ==
800/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path
801/// keeps over [`predict`]'s 11-bit round survives untouched) --
802/// [`combine_compound`] then divides that back out exactly with an 8/8
803/// simple-average weight split, so a compound block whose two references
804/// (and MVs) happen to coincide reproduces the plain source sample, not an
805/// off-by-one from double rounding.
806#[test]
807fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
808 let reference = vec![100u16; 16 * 16];
809 let mut pred0 = vec![0i32; 16];
810 predict_compound_intermediate(
811 &reference,
812 16,
813 16,
814 16,
815 0,
816 0,
817 REF_NO_SCALE,
818 4,
819 4,
820 InterpFilterKind::Regular,
821 InterpFilterKind::Regular,
822 &mut pred0,
823 );
824 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
825
826 let pred1 = pred0.clone();
827 let mut dst = vec![0u16; 16];
828 combine_compound(&pred0, &pred1, 8, 8, &mut dst);
829 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
830}
831
832#[cfg(test)]
833mod tests {
834 use super::{
835 InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter,
836 predict_with_filters,
837 };
838
839 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
840 /// inter block at the frame's top-left corner (mv q4 = (row 7, col 15),
841 /// bw=bh=16) predicted the wrong value because this decoder always used
842 /// the REGULAR filter table -- aomdec's own `av1_convolve_2d_sr_c` trace
843 /// showed this block actually used `EIGHTTAP_SMOOTH`
844 /// (`0 0 2 34 62 28 2 0` at xfrac=15, not REGULAR's `0 0 -2 8 126 -6 2
845 /// 0`). Window and expected output dumped straight from an
846 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
847 #[test]
848 fn smooth_filter_matches_aomdec_chroma_inter_block() {
849 #[rustfmt::skip]
850 let window: [[u8; 24]; 24] = [
851 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
852 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
853 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
854 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
855 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
856 [114,114,114,114,114,114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116,115,115,115],
857 [114,114,114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,116,116,115,115,115,115],
858 [113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,116,116,116,116,115,115,115,115],
859 [113,113,113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,115,115,115,115,115,115],
860 [112,112,112,112,112,112,112,112,112,113,113,113,113,114,114,114,114,114,115,115,115,115,115,115],
861 [111,111,111,111,111,111,111,111,112,112,112,112,113,113,113,113,114,114,114,114,115,115,115,115],
862 [110,110,110,110,110,110,110,110,111,111,111,111,112,112,112,113,113,113,113,113,114,114,114,115],
863 [109,109,109,109,109,109,109,110,110,110,110,111,111,111,111,112,112,112,112,113,113,114,114,114],
864 [108,108,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111,111,111,112,112,113,113,113],
865 [108,108,108,108,108,108,108,108,108,108,109,109,109,110,110,110,110,110,111,111,112,112,112,112],
866 [107,107,107,107,107,107,107,107,107,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111],
867 [106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,110,110,110],
868 [106,106,106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,109],
869 [105,105,105,105,105,105,105,105,106,106,106,107,107,107,107,108,108,108,108,108,108,108,108,109],
870 [104,104,104,104,104,104,104,104,104,105,105,106,106,106,107,107,107,107,107,107,107,108,108,108],
871 [102,102,102,102,102,103,103,103,103,104,104,105,105,105,106,106,107,107,107,107,107,107,107,107],
872 [101,101,101,101,101,101,101,102,102,103,103,104,104,104,105,105,106,106,106,106,106,107,107,107],
873 [100,100,100,100,100,100,100,101,101,102,102,103,103,104,104,105,105,105,106,106,106,106,106,106],
874 [99,99,99,99,99,99,100,100,100,101,101,102,103,103,104,104,105,105,105,105,105,105,105,106],
875 ];
876 // The dumped window spans real cols/rows -4..19; the block itself
877 // starts at real (0, 0), so pad the reference plane so col/row 4 of
878 // this buffer is real col/row 0, and hand `predict_with_filter` the
879 // real (0, 0) coordinates -- clamping then reproduces the identical
880 // extended border the dump already captured.
881 let stride = 24;
882 let mut reference = vec![0u16; stride * 24];
883 for (r, row) in window.iter().enumerate() {
884 for (c, &v) in row.iter().enumerate() {
885 reference[r * stride + c] = u16::from(v);
886 }
887 }
888 // predict()'s own edge clamp starts at true (0,0); shift so the
889 // dumped window's row/col 4 lands there by biasing x_q4/y_q4's
890 // whole-pel part by -4 and reading from a plane whose true origin
891 // is the window's row/col 4 -- simplest is to pass true_width /
892 // true_height covering the whole dumped window and offset the
893 // whole-pel part of x_q4/y_q4 by +4 to land on real (0,0).
894 let x_q4 = (4 + 0) * 16 + 15; // real block x0=0, xfrac=15
895 let y_q4 = (4 + 0) * 16 + 7; // real block y0=0, yfrac=7
896 let mut dst = vec![0u16; 16 * 16];
897 predict_with_filter(
898 &reference,
899 stride,
900 24,
901 24,
902 x_q4,
903 y_q4,
904 16,
905 16,
906 InterpFilterKind::Smooth,
907 &mut dst,
908 );
909 #[rustfmt::skip]
910 let expected_row0: [u16; 16] =
911 [114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116];
912 assert_eq!(
913 &dst[0..16],
914 &expected_row0,
915 "row0 vs aomdec's real av1_convolve_2d_sr_c output"
916 );
917 #[rustfmt::skip]
918 let expected_row15: [u16; 16] =
919 [103,103,104,104,104,105,105,106,106,106,107,107,107,107,107,107];
920 assert_eq!(
921 &dst[15 * 16..15 * 16 + 16],
922 &expected_row15,
923 "row15 vs aomdec"
924 );
925 }
926
927 /// lane-gmaffine r5 root cause: a block 4 or fewer samples wide reads
928 /// `Subpel_Filters[4]` -- the REGULAR narrow kernel -- for BOTH
929 /// `EIGHTTAP` and `EIGHTTAP_SHARP` (spec 7.11.3.4's `filterIdx`, libaom
930 /// `av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`,
931 /// `filter.h:243`). We used the 8-tap sharp kernel there, which is
932 /// invisible above 4 samples and so only ever bit the 4x4 chroma of an
933 /// 8x8 (or smaller) luma leaf.
934 #[test]
935 fn a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness() {
936 use crate::mc::{SUBPEL_FILTERS_4, SUBPEL_FILTERS_BILINEAR, SUBPEL_FILTERS_SMOOTH_4};
937 for kind in [
938 InterpFilterKind::Regular,
939 InterpFilterKind::Smooth,
940 InterpFilterKind::Sharp,
941 InterpFilterKind::Bilinear,
942 ] {
943 let (wide, narrow) = kind.tables();
944 let want: &[[i32; 8]; 16] = match kind {
945 InterpFilterKind::Regular | InterpFilterKind::Sharp => &SUBPEL_FILTERS_4,
946 InterpFilterKind::Smooth => &SUBPEL_FILTERS_SMOOTH_4,
947 InterpFilterKind::Bilinear => &SUBPEL_FILTERS_BILINEAR,
948 };
949 assert_eq!(narrow, want, "{kind:?}: wrong narrow-block kernel");
950 if kind == InterpFilterKind::Sharp {
951 assert_ne!(wide, narrow, "sharp's wide kernel is not its narrow one");
952 }
953 }
954 }
955
956 #[test]
957 fn integer_mv_is_identity() {
958 let width = 12;
959 let height = 12;
960 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
961 let mut dst = vec![0u16; 6 * 6];
962 predict(
963 &reference,
964 width,
965 width,
966 height,
967 3 * 16,
968 4 * 16,
969 6,
970 6,
971 &mut dst,
972 );
973 for row in 0..6 {
974 for col in 0..6 {
975 assert_eq!(
976 dst[row * 6 + col],
977 reference[(4 + row) * width + 3 + col],
978 "integer MV must reproduce the reference block byte-for-byte"
979 );
980 }
981 }
982 }
983
984 #[test]
985 fn half_pel_reproduces_the_ramp_midpoint() {
986 // Step 2 so every half-pel position lands on an exact integer.
987 let width = 16;
988 let height = 16;
989 let reference: Vec<u16> = (0..width * height)
990 .map(|i| (2 * (i % width)) as u16)
991 .collect();
992 let mut dst = vec![0u16; 4 * 4];
993 // Half-pel in x only: fraction 8/16, integer part at column 5.
994 predict(
995 &reference,
996 width,
997 width,
998 height,
999 5 * 16 + 8,
1000 5 * 16,
1001 4,
1002 4,
1003 &mut dst,
1004 );
1005 for row in 0..4 {
1006 for col in 0..4 {
1007 let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1
1008 assert_eq!(
1009 dst[row * 4 + col] as i32,
1010 midpoint as i32,
1011 "half-pel MV over a linear ramp must land exactly on the midpoint"
1012 );
1013 }
1014 }
1015 }
1016
1017 #[test]
1018 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
1019 let width = 20;
1020 let height = 20;
1021 let reference = vec![142u16; width * height];
1022 for yfrac in 0..16 {
1023 for xfrac in 0..16 {
1024 let mut dst = vec![0u16; 5 * 5];
1025 predict(
1026 &reference,
1027 width,
1028 width,
1029 height,
1030 5 * 16 + xfrac,
1031 5 * 16 + yfrac,
1032 5,
1033 5,
1034 &mut dst,
1035 );
1036 assert!(
1037 dst.iter().all(|&v| v == 142),
1038 "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}"
1039 );
1040 }
1041 }
1042 }
1043
1044 #[test]
1045 fn horizontal_and_vertical_only_filtering_differ() {
1046 // A plane linear in both x and y with different, even coefficients so
1047 // each axis's half-pel interpolation lands on an exact integer: this
1048 // pins the actual value each pass produces, not just that the two
1049 // differ, so swapping which pass reads which axis is caught even if
1050 // it happened to produce two merely-different numbers.
1051 let width = 10;
1052 let height = 10;
1053 let reference: Vec<u16> = (0..height)
1054 .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u16))
1055 .collect();
1056
1057 let mut horiz = vec![0u16; 4 * 4];
1058 predict(
1059 &reference,
1060 width,
1061 width,
1062 height,
1063 3 * 16 + 8,
1064 3 * 16,
1065 4,
1066 4,
1067 &mut horiz,
1068 );
1069 let mut vert = vec![0u16; 4 * 4];
1070 predict(
1071 &reference,
1072 width,
1073 width,
1074 height,
1075 3 * 16,
1076 3 * 16 + 8,
1077 4,
1078 4,
1079 &mut vert,
1080 );
1081
1082 for row in 0..4 {
1083 for col in 0..4 {
1084 // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put.
1085 assert_eq!(
1086 horiz[row * 4 + col] as i32,
1087 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32),
1088 "horizontal-only MV must interpolate along x only"
1089 );
1090 // Vertical half-pel: y interpolates to y0+row+0.5, x stays put.
1091 assert_eq!(
1092 vert[row * 4 + col] as i32,
1093 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2,
1094 "vertical-only MV must interpolate along y only"
1095 );
1096 }
1097 }
1098 assert_ne!(
1099 horiz, vert,
1100 "horizontal-only and vertical-only sub-pel MVs must give different outputs"
1101 );
1102 }
1103
1104 #[test]
1105 fn mv_past_the_edge_clamps_instead_of_panicking() {
1106 let width = 8;
1107 let height = 8;
1108 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
1109 let mut dst = vec![0u16; 4 * 4];
1110 // Whole-sample position far above and to the left of the plane, with
1111 // an odd fraction so both filter passes exercise the clamp.
1112 predict(
1113 &reference,
1114 width,
1115 width,
1116 height,
1117 -50 * 16 + 5,
1118 -50 * 16 + 5,
1119 4,
1120 4,
1121 &mut dst,
1122 );
1123 let expected = reference[0]; // the whole plane clamps to the top-left corner
1124 assert!(
1125 dst.iter().all(|&v| v == expected),
1126 "an MV past the top-left edge must clamp to the corner sample, got {dst:?}"
1127 );
1128
1129 let mut dst2 = vec![0u16; 4 * 4];
1130 predict(
1131 &reference,
1132 width,
1133 width,
1134 height,
1135 50 * 16 + 5,
1136 50 * 16 + 5,
1137 4,
1138 4,
1139 &mut dst2,
1140 );
1141 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
1142 assert!(
1143 dst2.iter().all(|&v| v == expected2),
1144 "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}"
1145 );
1146 }
1147
1148 #[test]
1149 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
1150 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
1151 // must reduce predict_scaled's per-column scaled walk to the exact
1152 // same int_pel/filter_idx sequence predict_with_filters computes from
1153 // a fixed stride-1 walk -- every subpel fraction, every block width.
1154 let width = 24;
1155 let height = 24;
1156 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
1157 for block_w in [4usize, 8, 16] {
1158 for x_frac in 0..16i32 {
1159 let x_q4 = 3 * 16 + x_frac;
1160 let y_q4 = 2 * 16 + 5;
1161 let mut expected = vec![0u16; block_w * 8];
1162 predict_with_filters(
1163 &reference,
1164 width,
1165 width,
1166 height,
1167 x_q4,
1168 y_q4,
1169 block_w,
1170 8,
1171 InterpFilterKind::Regular,
1172 InterpFilterKind::Regular,
1173 &mut expected,
1174 );
1175 let mut got = vec![0u16; block_w * 8];
1176 predict_scaled(
1177 &reference,
1178 width,
1179 width,
1180 height,
1181 x_q4,
1182 y_q4,
1183 REF_NO_SCALE,
1184 block_w,
1185 8,
1186 InterpFilterKind::Regular,
1187 InterpFilterKind::Regular,
1188 &mut got,
1189 );
1190 assert_eq!(
1191 got, expected,
1192 "block_w={block_w} x_frac={x_frac}: REF_NO_SCALE must reproduce predict_with_filters exactly"
1193 );
1194 }
1195 }
1196 }
1197}