forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mc.rs3755 lines, 143.7 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.
11use archmage::SimdToken;
12use crate::hits::hit;
13
14/// `Round2` (spec 4.7): halves round up.
15fn round2(value: i32, shift: u32) -> i32 {
16 if shift == 0 {
17 value
18 } else {
19 (value + (1 << (shift - 1))) >> shift
20 }
21}
22
23/// The kernels' intermediate is `i16` (lane-mc), and every SIMD store lands
24/// through `packs_epi32`, which saturates -- so the scalar arms must too, or
25/// the two would disagree on an out-of-range sum. Motion compensation never
26/// produces one (`horizontal_intermediate_fits_i16` proves the bound from the
27/// tap sums at every supported bit depth), and restoration's wiener pass
28/// clamps its own output into i16 immediately after.
29fn sat16(value: i32) -> i16 {
30 value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
31}
32
33/// `InterRound0` (spec 7.11.3.2), non-compound: the shift the horizontal
34/// pass's sum is brought down by before it is stored as the intermediate.
35/// This is the 8/10-bit base; at 12-bit [`round_delta`] raises it (libaom
36/// `convolve.h`'s `get_conv_params_no_round`).
37const INTER_ROUND_0: u32 = 3;
38/// `InterRound1` (spec 7.11.3.2), non-compound: the shift the vertical
39/// pass's sum is brought down by to land back on a sample. Composed
40/// with [`INTER_ROUND_0`] the two shifts are the filter's own gain (each pass
41/// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)
42/// -- so an identity or DC input comes back exactly, by construction of the
43/// table rather than by a fitted constant. 8/10-bit base; see [`round_delta`].
44const INTER_ROUND_1: u32 = 11;
45
46/// The bit-depth headroom libaom adds when the `CONV_BUF` intermediate would
47/// no longer fit 16 bits (`convolve.h:81..86`'s
48/// `intbufrange = bd + FILTER_BITS - round_0 + 2 > 16`): zero at 8/10-bit;
49/// `bd - 10` at 12-bit. There the horizontal `round_0` rises by the delta
50/// and the non-compound vertical `round_1` falls by it again, so the
51/// filter's own gain `2*FILTER_BITS - round_0 - round_1` is untouched --
52/// only the intermediate quantisation moves. Warp's
53/// `reduce_bits_horiz == conv_params->round_0` (`warped_motion.c:295`) and
54/// the Wiener pair (`get_conv_params_wiener`) inherit the same delta.
55pub(crate) fn round_delta(bd: u32) -> u32 {
56 bd.saturating_sub(10)
57}
58
59/// A frame's MC rounding pair: horizontal `round_0` and non-compound
60/// vertical `round_1` (the compound vertical round is `INTER_ROUND_1_COMPOUND`
61/// at every bit depth).
62pub(crate) fn round_pair(bd: u32) -> (u32, u32) {
63 let delta = round_delta(bd);
64 (INTER_ROUND_0 + delta, INTER_ROUND_1 - delta)
65}
66
67/// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel
68/// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer
69/// sample (fraction 0 is the identity tap `[.., 128, ..]`).
70const SUBPEL_FILTERS: [[i32; 8]; 16] = [
71 [0, 0, 0, 128, 0, 0, 0, 0],
72 [0, 2, -6, 126, 8, -2, 0, 0],
73 [0, 2, -10, 122, 18, -4, 0, 0],
74 [0, 2, -12, 116, 28, -8, 2, 0],
75 [0, 2, -14, 110, 38, -10, 2, 0],
76 [0, 2, -14, 102, 48, -12, 2, 0],
77 [0, 2, -16, 94, 58, -12, 2, 0],
78 [0, 2, -14, 84, 66, -12, 2, 0],
79 [0, 2, -14, 76, 76, -14, 2, 0],
80 [0, 2, -12, 66, 84, -14, 2, 0],
81 [0, 2, -12, 58, 94, -16, 2, 0],
82 [0, 2, -12, 48, 102, -14, 2, 0],
83 [0, 2, -10, 38, 110, -14, 2, 0],
84 [0, 2, -8, 28, 116, -12, 2, 0],
85 [0, 0, -4, 18, 122, -10, 2, 0],
86 [0, 0, -2, 8, 126, -6, 2, 0],
87];
88
89/// `Subpel_Filters[EIGHTTAP]`'s narrow-block counterpart (spec 7.11.3.4's
90/// filter selection is per-axis: a `predict` axis whose output block
91/// dimension is 4 or less reads this table instead of [`SUBPEL_FILTERS`]),
92/// mirroring `av1_sub_pel_filters_4` (`filter.h`): the same 8-slot shape but
93/// zeroed at taps 0/1/6/7, so a 4-wide (or 4-tall) block's filter never
94/// reaches a full 3 samples past its own edge. Every 4:2:0 chroma block
95/// under an 8x8 (or smaller) luma leaf hits this on at least one axis --
96/// this is not an edge case, it is the common chroma shape.
97const SUBPEL_FILTERS_4: [[i32; 8]; 16] = [
98 [0, 0, 0, 128, 0, 0, 0, 0],
99 [0, 0, -4, 126, 8, -2, 0, 0],
100 [0, 0, -8, 122, 18, -4, 0, 0],
101 [0, 0, -10, 116, 28, -6, 0, 0],
102 [0, 0, -12, 110, 38, -8, 0, 0],
103 [0, 0, -12, 102, 48, -10, 0, 0],
104 [0, 0, -14, 94, 58, -10, 0, 0],
105 [0, 0, -12, 84, 66, -10, 0, 0],
106 [0, 0, -12, 76, 76, -12, 0, 0],
107 [0, 0, -10, 66, 84, -12, 0, 0],
108 [0, 0, -10, 58, 94, -14, 0, 0],
109 [0, 0, -10, 48, 102, -12, 0, 0],
110 [0, 0, -8, 38, 110, -12, 0, 0],
111 [0, 0, -6, 28, 116, -10, 0, 0],
112 [0, 0, -4, 18, 122, -8, 0, 0],
113 [0, 0, -2, 8, 126, -4, 0, 0],
114];
115
116/// `Subpel_Filters[EIGHTTAP_SMOOTH]` (`filter.h`'s `av1_sub_pel_filters_8smooth`).
117const SUBPEL_FILTERS_SMOOTH: [[i32; 8]; 16] = [
118 [0, 0, 0, 128, 0, 0, 0, 0],
119 [0, 2, 28, 62, 34, 2, 0, 0],
120 [0, 0, 26, 62, 36, 4, 0, 0],
121 [0, 0, 22, 62, 40, 4, 0, 0],
122 [0, 0, 20, 60, 42, 6, 0, 0],
123 [0, 0, 18, 58, 44, 8, 0, 0],
124 [0, 0, 16, 56, 46, 10, 0, 0],
125 [0, -2, 16, 54, 48, 12, 0, 0],
126 [0, -2, 14, 52, 52, 14, -2, 0],
127 [0, 0, 12, 48, 54, 16, -2, 0],
128 [0, 0, 10, 46, 56, 16, 0, 0],
129 [0, 0, 8, 44, 58, 18, 0, 0],
130 [0, 0, 6, 42, 60, 20, 0, 0],
131 [0, 0, 4, 40, 62, 22, 0, 0],
132 [0, 0, 4, 36, 62, 26, 0, 0],
133 [0, 0, 2, 34, 62, 28, 2, 0],
134];
135
136/// `SUBPEL_FILTERS_SMOOTH`'s narrow-block counterpart (`av1_sub_pel_filters_4smooth`).
137const SUBPEL_FILTERS_SMOOTH_4: [[i32; 8]; 16] = [
138 [0, 0, 0, 128, 0, 0, 0, 0],
139 [0, 0, 30, 62, 34, 2, 0, 0],
140 [0, 0, 26, 62, 36, 4, 0, 0],
141 [0, 0, 22, 62, 40, 4, 0, 0],
142 [0, 0, 20, 60, 42, 6, 0, 0],
143 [0, 0, 18, 58, 44, 8, 0, 0],
144 [0, 0, 16, 56, 46, 10, 0, 0],
145 [0, 0, 14, 54, 48, 12, 0, 0],
146 [0, 0, 12, 52, 52, 12, 0, 0],
147 [0, 0, 12, 48, 54, 14, 0, 0],
148 [0, 0, 10, 46, 56, 16, 0, 0],
149 [0, 0, 8, 44, 58, 18, 0, 0],
150 [0, 0, 6, 42, 60, 20, 0, 0],
151 [0, 0, 4, 40, 62, 22, 0, 0],
152 [0, 0, 4, 36, 62, 26, 0, 0],
153 [0, 0, 2, 34, 62, 30, 0, 0],
154];
155
156/// `Subpel_Filters[EIGHTTAP_SHARP]` (`av1_sub_pel_filters_8sharp`). A block
157/// whose dimension is 4 or less does NOT read this table: spec 7.11.3.4's
158/// `filterIdx` sends both EIGHTTAP and EIGHTTAP_SHARP to filter index 4, and
159/// libaom agrees -- `av1_interp_4tap[MULTITAP_SHARP]` is `av1_sub_pel_filters_4`,
160/// the REGULAR narrow kernel (`filter.h:243`), not a sharp one (lane-gmaffine r5).
161const SUBPEL_FILTERS_SHARP: [[i32; 8]; 16] = [
162 [0, 0, 0, 128, 0, 0, 0, 0],
163 [-2, 2, -6, 126, 8, -2, 2, 0],
164 [-2, 6, -12, 124, 16, -6, 4, -2],
165 [-2, 8, -18, 120, 26, -10, 6, -2],
166 [-4, 10, -22, 116, 38, -14, 6, -2],
167 [-4, 10, -22, 108, 48, -18, 8, -2],
168 [-4, 10, -24, 100, 60, -20, 8, -2],
169 [-4, 10, -24, 90, 70, -22, 10, -2],
170 [-4, 12, -24, 80, 80, -24, 12, -4],
171 [-2, 10, -22, 70, 90, -24, 10, -4],
172 [-2, 8, -20, 60, 100, -24, 10, -4],
173 [-2, 8, -18, 48, 108, -22, 10, -4],
174 [-2, 6, -14, 38, 116, -22, 10, -4],
175 [-2, 6, -10, 26, 120, -18, 8, -2],
176 [-2, 4, -6, 16, 124, -12, 6, -2],
177 [0, 2, -2, 8, 126, -6, 2, -2],
178];
179
180/// `Subpel_Filters[BILINEAR]` (`av1_bilinear_filters`) -- also never swapped
181/// for a narrow-block table (it is already only 2 non-zero taps).
182const SUBPEL_FILTERS_BILINEAR: [[i32; 8]; 16] = [
183 [0, 0, 0, 128, 0, 0, 0, 0],
184 [0, 0, 0, 120, 8, 0, 0, 0],
185 [0, 0, 0, 112, 16, 0, 0, 0],
186 [0, 0, 0, 104, 24, 0, 0, 0],
187 [0, 0, 0, 96, 32, 0, 0, 0],
188 [0, 0, 0, 88, 40, 0, 0, 0],
189 [0, 0, 0, 80, 48, 0, 0, 0],
190 [0, 0, 0, 72, 56, 0, 0, 0],
191 [0, 0, 0, 64, 64, 0, 0, 0],
192 [0, 0, 0, 56, 72, 0, 0, 0],
193 [0, 0, 0, 48, 80, 0, 0, 0],
194 [0, 0, 0, 40, 88, 0, 0, 0],
195 [0, 0, 0, 32, 96, 0, 0, 0],
196 [0, 0, 0, 24, 104, 0, 0, 0],
197 [0, 0, 0, 16, 112, 0, 0, 0],
198 [0, 0, 0, 8, 120, 0, 0, 0],
199];
200
201/// Which of the spec's four `interpolation_filter` kernels a block's motion
202/// compensation reads (spec 6.8.9 / `frame_header`'s `interpolation_filter`).
203/// A frame codes exactly one of these when not `Switchable`; a `Switchable`
204/// frame codes one per block per direction (spec 5.11.20's
205/// `read_interp_filter`, see `decode::decode_inter_block`), so `predict`'s
206/// callers resolve `Switchable` to a concrete pair of kinds themselves --
207/// this type only ever names the resolved kernel, never `Switchable` itself.
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209pub enum InterpFilterKind {
210 /// The `Regular` interpolation kernel.
211 Regular,
212 /// The `Smooth` interpolation kernel.
213 Smooth,
214 /// The `Sharp` interpolation kernel.
215 Sharp,
216 /// The `Bilinear` interpolation kernel.
217 Bilinear,
218}
219
220impl InterpFilterKind {
221 fn tables(self) -> (&'static [[i32; 8]; 16], &'static [[i32; 8]; 16]) {
222 match self {
223 InterpFilterKind::Regular => (&SUBPEL_FILTERS, &SUBPEL_FILTERS_4),
224 InterpFilterKind::Smooth => (&SUBPEL_FILTERS_SMOOTH, &SUBPEL_FILTERS_SMOOTH_4),
225 InterpFilterKind::Sharp => (&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_4),
226 InterpFilterKind::Bilinear => (&SUBPEL_FILTERS_BILINEAR, &SUBPEL_FILTERS_BILINEAR),
227 }
228 }
229
230 /// The three-symbol alphabet spec 5.11.20's `interp_filter[dir]` reads
231 /// under a `Switchable` frame decodes to (`EIGHTTAP`/`_SMOOTH`/`_SHARP`
232 /// in that order -- `BILINEAR` is never a `switchable_interp` outcome).
233 ///
234 /// # Panics
235 /// Panics when `symbol` is not `0..=2`.
236 pub fn from_switchable_symbol(symbol: usize) -> InterpFilterKind {
237 match symbol {
238 0 => InterpFilterKind::Regular,
239 1 => InterpFilterKind::Smooth,
240 2 => InterpFilterKind::Sharp,
241 _ => panic!("switchable_interp's alphabet is exactly 3 symbols"),
242 }
243 }
244
245 /// The frame header's own `interpolation_filter` (spec 6.8.9), for the
246 /// non-`Switchable` values a fixed-filter frame codes directly.
247 ///
248 /// # Panics
249 /// Panics on `Switchable`, which is not a concrete kernel -- callers
250 /// resolve it per block instead (spec 5.11.20).
251 pub fn from_header(filter: ec_av1_syntax::InterpolationFilter) -> InterpFilterKind {
252 match filter {
253 ec_av1_syntax::InterpolationFilter::Eighttap => InterpFilterKind::Regular,
254 ec_av1_syntax::InterpolationFilter::EighttapSmooth => InterpFilterKind::Smooth,
255 ec_av1_syntax::InterpolationFilter::EighttapSharp => InterpFilterKind::Sharp,
256 ec_av1_syntax::InterpolationFilter::Bilinear => InterpFilterKind::Bilinear,
257 ec_av1_syntax::InterpolationFilter::Switchable => {
258 panic!("Switchable is resolved per block, not as one frame-wide kernel")
259 }
260 }
261 }
262}
263
264/// A reference sample at `(x, y)`, clamped to the frame's true (unpadded)
265/// extent -- `true_width`/`true_height`, which can be narrower than
266/// `stride` -- rather than read out of range (spec 7.11.3.4's `Clip3`
267/// against the frame's edges): a motion vector that points past the true
268/// edge repeats the true edge's sample instead of panicking or picking up
269/// whatever this encoder's own uncoded padding columns/rows hold.
270#[allow(clippy::too_many_arguments)]
271fn sample(
272 reference: &[u16],
273 stride: usize,
274 true_width: usize,
275 true_height: usize,
276 x: i32,
277 y: i32,
278) -> i32 {
279 let cx = x.clamp(0, true_width as i32 - 1) as usize;
280 let cy = y.clamp(0, true_height as i32 - 1) as usize;
281 i32::from(reference[cy * stride + cx])
282}
283
284/// lane-perf5: which explicit-SIMD kernels this CPU can run. The scalar
285/// functions below stay the reference implementation -- every SIMD kernel is
286/// checked against them by `simd_matches_scalar_*` -- and every non-x86_64
287/// build, plus any x86_64 CPU without AVX2 or SSE4.1, decodes through them.
288#[derive(Clone, Copy, PartialEq, Eq, Debug)]
289#[allow(dead_code)] // every variant is constructed only on x86_64
290pub(crate) enum SimdLevel {
291 Scalar,
292 /// `_mm_madd_epi16` (SSE2) horizontal pass, `_mm_mullo_epi32` (SSE4.1)
293 /// vertical pass -- the pair is gated on SSE4.1, the later of the two.
294 Sse41,
295 Avx2,
296}
297
298/// The level, detected once per process (spec-irrelevant: pure dispatch).
299#[cfg(test)]
300pub(crate) fn simd_level() -> SimdLevel {
301 static LEVEL: std::sync::OnceLock<SimdLevel> = std::sync::OnceLock::new();
302 *LEVEL.get_or_init(|| {
303 #[cfg(target_arch = "x86_64")]
304 {
305 if std::arch::is_x86_feature_detected!("avx2") {
306 return SimdLevel::Avx2;
307 }
308 if std::arch::is_x86_feature_detected!("sse4.1") {
309 return SimdLevel::Sse41;
310 }
311 }
312 SimdLevel::Scalar
313 })
314}
315
316/// The horizontal pass's inner loop over a contiguous window (`src` holds the
317/// row's whole footprint, `out.len() + 7` samples): SIMD where available,
318/// [`hpass_contig_scalar`] otherwise. Both produce the same `i32`s -- the
319/// SIMD form multiplies the same `i16` pairs, sums them in `i32` and applies
320/// the same `Round2(sum, InterRound0)`.
321#[inline]
322pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16], round0: u32) {
323 let n = out.len();
324 hpass_rows(src, 0, 1, n, t16, out, round0);
325}
326
327/// lane-mc2: `rows` rows of [`hpass_contig`], `src_stride` apart in `src` and
328/// packed `block_w` apart in `out`. The tap vectors and the SIMD dispatch are
329/// set up once for the whole block instead of once per row.
330// Runtime dispatch is an archmage token summon: the AVX2 token runs the AVX2
331// kernel, the SSE4.1 token the SSE2 one, anything else the scalar loop below.
332pub(crate) fn hpass_rows(
333 src: &[u16],
334 src_stride: usize,
335 rows: usize,
336 block_w: usize,
337 t16: &[i16; 8],
338 out: &mut [i16],
339 round0: u32,
340) {
341 #[cfg(target_arch = "x86_64")]
342 {
343 if let Some(t) = archmage::X64V3Token::summon() {
344 simd::hpass_avx2(t, src, src_stride, rows, block_w, t16, out, round0);
345 return;
346 }
347 if let Some(t) = archmage::X64V2Token::summon() {
348 simd::hpass_sse2(t, src, src_stride, rows, block_w, t16, out, round0);
349 return;
350 }
351 }
352 hpass_rows_scalar_all(src, src_stride, rows, block_w, t16, out, round0);
353}
354
355#[inline]
356fn hpass_rows_scalar_all(
357 src: &[u16],
358 src_stride: usize,
359 rows: usize,
360 block_w: usize,
361 t16: &[i16; 8],
362 out: &mut [i16],
363 round0: u32,
364) {
365 for r in 0..rows {
366 hpass_contig_scalar(
367 &src[r * src_stride..],
368 t16,
369 &mut out[r * block_w..(r + 1) * block_w],
370 round0,
371 );
372 }
373}
374
375/// The scalar reference for [`hpass_contig`] (lane-perf2's loop).
376fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16], round0: u32) {
377 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit
378 // depth), so the products are exactly the i32 ones but the widening
379 // multiply is one instruction per pair.
380 for (o, w) in out.iter_mut().zip(src.windows(8)) {
381 let mut sum = 0i32;
382 for t in 0..8 {
383 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
384 }
385 *o = sat16(round2(sum, round0));
386 }
387}
388
389/// lane-perf5: explicit `std::arch::x86_64` kernels for the two motion
390/// compensation passes -- the 18.7% of a 1080p decode that lane-perf4 left in
391/// `hpass_row` + `vpass_row`. Nothing here is spec logic: each kernel is the
392/// scalar function's arithmetic, lane-parallel, with identical rounding.
393///
394/// Every kernel is a safe `#[arcane]` (or `#[target_feature]` helper) function,
395/// called only with the archmage token of its feature, obtained by `summon`. Loads and stores go through `bytemuck` on slices, so every
396/// access is bounds-checked.
397#[cfg(target_arch = "x86_64")]
398mod simd {
399 use super::{round2, sat16};
400 use archmage::{X64V2Token, X64V3Token, arcane};
401 use bytemuck::Pod;
402 use std::arch::x86_64::*;
403 use std::mem::size_of;
404
405 /// An unaligned vector load from the front of `s` (`loadu`).
406 #[inline(always)]
407 fn ld<T: Pod, V: Pod>(s: &[T]) -> V {
408 bytemuck::pod_read_unaligned(bytemuck::cast_slice::<T, u8>(
409 &s[..size_of::<V>() / size_of::<T>()],
410 ))
411 }
412
413 /// An unaligned vector store to the front of `d` (`storeu`).
414 #[inline(always)]
415 fn st<T: Pod, V: Pod>(d: &mut [T], v: V) {
416 let n = size_of::<V>() / size_of::<T>();
417 bytemuck::cast_slice_mut::<T, u8>(&mut d[..n]).copy_from_slice(bytemuck::bytes_of(&v));
418 }
419
420 /// The first four `i16`s in the low half of a register, the high half
421 /// zero (`loadl_epi64`).
422 #[inline(always)]
423 fn ldl(s: &[i16]) -> __m128i {
424 let v: u64 = bytemuck::pod_read_unaligned(bytemuck::cast_slice::<i16, u8>(&s[..4]));
425 bytemuck::cast([v, 0u64])
426 }
427
428 /// Stores the low 8 bytes of `v` (four `u16`s) to the front of `d`
429 /// (`storel_epi64`).
430 #[inline(always)]
431 fn stl(d: &mut [u16], v: __m128i) {
432 let b: [u64; 2] = bytemuck::cast(v);
433 bytemuck::cast_slice_mut::<u16, u8>(&mut d[..4]).copy_from_slice(&b[0].to_ne_bytes());
434 }
435
436 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
437 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is
438 /// `s[2j]*t_even + s[2j+1]*t_odd`, i.e. two taps of one output at once.
439 #[inline]
440 fn taps16(taps: &[i32; 8]) -> [i16; 8] {
441 [
442 taps[0] as i16,
443 taps[1] as i16,
444 taps[2] as i16,
445 taps[3] as i16,
446 taps[4] as i16,
447 taps[5] as i16,
448 taps[6] as i16,
449 taps[7] as i16,
450 ]
451 }
452
453 #[inline]
454 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
455 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);
456 [
457 pack(t[0], t[1]),
458 pack(t[2], t[3]),
459 pack(t[4], t[5]),
460 pack(t[6], t[7]),
461 ]
462 }
463
464 /// Horizontal pass, AVX2: 16 outputs per iteration. Each 256-bit `madd`
465 /// covers 8 outputs two taps at a time, but only every other output (the
466 /// pairs are consecutive samples), so even and odd output columns are
467 /// accumulated in two registers and interleaved back into order by
468 /// `unpack` + `permute2x128`.
469 ///
470 /// Requires AVX2. `src.len()` must be at least `out.len() + 7`.
471 #[arcane]
472 pub fn hpass_avx2(
473 t: X64V3Token,
474 src: &[u16],
475 src_stride: usize,
476 rows: usize,
477 block_w: usize,
478 t16: &[i16; 8],
479 out: &mut [i16],
480 round0: u32,
481 ) {
482 debug_assert!(out.len() >= rows * block_w);
483 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
484 let tp = tap_pairs(t16);
485 let tv = [
486 _mm256_set1_epi32(tp[0]),
487 _mm256_set1_epi32(tp[1]),
488 _mm256_set1_epi32(tp[2]),
489 _mm256_set1_epi32(tp[3]),
490 ];
491 let rnd = _mm256_set1_epi32(1 << (round0 - 1));
492 for r in 0..rows {
493 let sp = &src[r * src_stride..];
494 let op = &mut out[r * block_w..(r + 1) * block_w];
495 let mut c = 0usize;
496 while c + 16 <= block_w {
497 let mut e = _mm256_setzero_si256();
498 let mut o = _mm256_setzero_si256();
499 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
500 #[allow(clippy::needless_range_loop)]
501 for k in 0..4 {
502 let se: __m256i = ld(&sp[c + 2 * k..]);
503 e = _mm256_add_epi32(e, _mm256_madd_epi16(se, tv[k]));
504 let so: __m256i = ld(&sp[c + 2 * k + 1..]);
505 o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));
506 }
507 e = _mm256_sra_epi32(_mm256_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32));
508 o = _mm256_sra_epi32(_mm256_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32));
509 let lo = _mm256_unpacklo_epi32(e, o);
510 let hi = _mm256_unpackhi_epi32(e, o);
511 // `lo`/`hi` already hold the 16 outputs in order, four per
512 // 128-bit lane; `packs_epi32` narrows lane-wise, so the store
513 // is c..c+16 in order. Saturation never fires: see
514 // `horizontal_intermediate_fits_i16`.
515 st(&mut op[c..], _mm256_packs_epi32(lo, hi));
516 c += 16;
517 }
518 if c < block_w {
519 hpass_sse2(t.v2(), &sp[c..], 0, 1, block_w - c, t16, &mut op[c..], round0);
520 }
521 }
522 }
523
524 /// Vertical pass, AVX2: the intermediate is `i16` (lane-mc: it provably
525 /// fits, see `horizontal_intermediate_fits_i16`), so a row PAIR
526 /// interleaved by `unpack_epi16` is exactly `_mm256_madd_epi16`'s shape --
527 /// two taps of 16 columns per instruction, where the old `i32` form spent
528 /// one `mullo_epi32` per tap per 8 columns. `acc` is left unrounded, as
529 /// the scalar form leaves it.
530 ///
531 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
532 /// and `acc` at least `block_w`.
533 #[arcane]
534 pub fn vpass_avx2(
535 _t: X64V3Token,
536 intermediate: &[i16],
537 block_w: usize,
538 src_stride: usize,
539 rows: usize,
540 taps: &[i32; 8],
541 acc: &mut [i32],
542 ) {
543 debug_assert!(
544 intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w
545 );
546 let tp = tap_pairs(&taps16(taps));
547 for row in 0..rows {
548 let ip = &intermediate[row * src_stride..];
549 let ap = &mut acc[row * block_w..(row + 1) * block_w];
550 let mut c = 0usize;
551 while c + 16 <= block_w {
552 // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit
553 // lane), `hi` the other two runs; the two `permute2x128`s put the
554 // 16 sums back in column order.
555 let mut lo = _mm256_setzero_si256();
556 let mut hi = _mm256_setzero_si256();
557 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
558 #[allow(clippy::needless_range_loop)]
559 for k in 0..4 {
560 if tp[k] == 0 {
561 continue;
562 }
563 let tv = _mm256_set1_epi32(tp[k]);
564 let a: __m256i = ld(&ip[2 * k * src_stride + c..]);
565 let b: __m256i = ld(&ip[(2 * k + 1) * src_stride + c..]);
566 lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
567 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
568 }
569 st(&mut ap[c..], _mm256_permute2x128_si256(lo, hi, 0x20));
570 st(&mut ap[c + 8..], _mm256_permute2x128_si256(lo, hi, 0x31));
571 c += 16;
572 }
573 vpass_tail_sse(ip, block_w, src_stride, &tp, taps, ap, c);
574 }
575 }
576
577 /// [`vpass_avx2`]'s 8- and 4-column steps, 128-bit: every AV1 block width
578 /// is a multiple of 4, and the 8x8 luma block (the most common inter
579 /// shape on real 4K content) lands here whole.
580 ///
581 /// `ip` starts at the row and must reach `8 * src_stride` elements on;
582 /// `ap` is the row's `block_w` outputs; `c` is the column already done.
583 #[inline]
584 #[target_feature(enable = "sse2")]
585 fn vpass_tail_sse(
586 ip: &[i16],
587 block_w: usize,
588 src_stride: usize,
589 tp: &[i32; 4],
590 taps: &[i32; 8],
591 ap: &mut [i32],
592 mut c: usize,
593 ) {
594 while c + 8 <= block_w {
595 let mut lo = _mm_setzero_si128();
596 let mut hi = _mm_setzero_si128();
597 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
598 #[allow(clippy::needless_range_loop)]
599 for k in 0..4 {
600 if tp[k] == 0 {
601 continue;
602 }
603 let tv = _mm_set1_epi32(tp[k]);
604 let a: __m128i = ld(&ip[2 * k * src_stride + c..]);
605 let b: __m128i = ld(&ip[(2 * k + 1) * src_stride + c..]);
606 lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
607 hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
608 }
609 st(&mut ap[c..], lo);
610 st(&mut ap[c + 4..], hi);
611 c += 8;
612 }
613 while c + 4 <= block_w {
614 let mut lo = _mm_setzero_si128();
615 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
616 #[allow(clippy::needless_range_loop)]
617 for k in 0..4 {
618 if tp[k] == 0 {
619 continue;
620 }
621 let tv = _mm_set1_epi32(tp[k]);
622 let a = ldl(&ip[2 * k * src_stride + c..]);
623 let b = ldl(&ip[(2 * k + 1) * src_stride + c..]);
624 lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
625 }
626 st(&mut ap[c..], lo);
627 c += 4;
628 }
629 // Every AV1 block width is a multiple of 4, but the encoder's own
630 // motion search prices odd widths through `predict`, so the last
631 // columns still need the scalar form.
632 while c < block_w {
633 let mut sum = 0i32;
634 for (t, &tap) in taps.iter().enumerate() {
635 sum += tap * i32::from(ip[t * src_stride + c]);
636 }
637 ap[c] = sum;
638 c += 1;
639 }
640 }
641
642 /// [`vpass_avx2`] with the output rounding fused in: the sums never reach
643 /// memory as `i32`, they are rounded by `INTER_ROUND_1`, clamped and
644 /// stored as the block's own `u16` samples. `packus_epi32` is the clamp's
645 /// lower half (a negative sum saturates to 0) and `min_epu16` its upper,
646 /// which is exactly `round2(sum, INTER_ROUND_1).clamp(0, max)`.
647 ///
648 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
649 /// and `dst` at least `block_w`.
650 #[arcane]
651 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
652 #[allow(clippy::too_many_arguments)]
653 pub fn vpass_row_u16_avx2(
654 _t: X64V3Token,
655 intermediate: &[i16],
656 block_w: usize,
657 src_stride: usize,
658 rows: usize,
659 taps: &[i32; 8],
660 max: i32,
661 dst: &mut [u16],
662 round1: u32,
663 ) {
664 debug_assert!(
665 intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w
666 );
667 let tp = tap_pairs(&taps16(taps));
668 let rnd = _mm256_set1_epi32(1 << (round1 - 1));
669 let mx = _mm256_set1_epi16(max as i16);
670 for row in 0..rows {
671 let ip = &intermediate[row * src_stride..];
672 let dp = &mut dst[row * block_w..(row + 1) * block_w];
673 let mut c = 0usize;
674 while c + 16 <= block_w {
675 let mut lo = rnd;
676 let mut hi = rnd;
677 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
678 #[allow(clippy::needless_range_loop)]
679 for k in 0..4 {
680 if tp[k] == 0 {
681 continue;
682 }
683 let tv = _mm256_set1_epi32(tp[k]);
684 let a: __m256i = ld(&ip[2 * k * src_stride + c..]);
685 let b: __m256i = ld(&ip[(2 * k + 1) * src_stride + c..]);
686 lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
687 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
688 }
689 lo = _mm256_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32));
690 hi = _mm256_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32));
691 // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
692 // per lane in order, so this is c..c+16 in order.
693 let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
694 st(&mut dp[c..], v);
695 c += 16;
696 }
697 vpass_u16_tail_sse(ip, block_w, src_stride, &tp, taps, max, dp, c, round1);
698 }
699 }
700
701 /// [`vpass_row_u16_avx2`]'s 8- and 4-column steps (SSE4.1 for
702 /// `packus_epi32`), and the scalar remainder.
703 ///
704 /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
705 #[target_feature(enable = "sse4.1")]
706 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
707 #[allow(clippy::too_many_arguments)]
708 fn vpass_u16_tail_sse(
709 ip: &[i16],
710 block_w: usize,
711 src_stride: usize,
712 tp: &[i32; 4],
713 taps: &[i32; 8],
714 max: i32,
715 dp: &mut [u16],
716 mut c: usize,
717 round1: u32,
718 ) {
719 let rnd = _mm_set1_epi32(1 << (round1 - 1));
720 let mx = _mm_set1_epi16(max as i16);
721 while c + 4 <= block_w {
722 let wide = c + 8 <= block_w;
723 let mut lo = rnd;
724 let mut hi = rnd;
725 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
726 #[allow(clippy::needless_range_loop)]
727 for k in 0..4 {
728 if tp[k] == 0 {
729 continue;
730 }
731 let tv = _mm_set1_epi32(tp[k]);
732 let (pa, pb) = (
733 &ip[2 * k * src_stride + c..],
734 &ip[(2 * k + 1) * src_stride + c..],
735 );
736 let (a, b) = if wide {
737 (ld::<i16, __m128i>(pa), ld::<i16, __m128i>(pb))
738 } else {
739 (ldl(pa), ldl(pb))
740 };
741 lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
742 if wide {
743 hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
744 }
745 }
746 let v = _mm_min_epu16(
747 _mm_packus_epi32(
748 _mm_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32)),
749 _mm_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32)),
750 ),
751 mx,
752 );
753 if wide {
754 st(&mut dp[c..], v);
755 c += 8;
756 } else {
757 stl(&mut dp[c..], v);
758 c += 4;
759 }
760 }
761 while c < block_w {
762 let mut sum = 0i32;
763 for (t, &tap) in taps.iter().enumerate() {
764 sum += tap * i32::from(ip[t * src_stride + c]);
765 }
766 dp[c] = round2(sum, round1).clamp(0, max) as u16;
767 c += 1;
768 }
769 }
770
771 /// [`vpass_row_u16_avx2`] without the 16-column step.
772 ///
773 /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
774 #[arcane]
775 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
776 #[allow(clippy::too_many_arguments)]
777 pub fn vpass_row_u16_sse41(
778 _t: X64V2Token,
779 intermediate: &[i16],
780 block_w: usize,
781 src_stride: usize,
782 rows: usize,
783 taps: &[i32; 8],
784 max: i32,
785 dst: &mut [u16],
786 round1: u32,
787 ) {
788 debug_assert!(
789 intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w
790 );
791 let tp = tap_pairs(&taps16(taps));
792 for row in 0..rows {
793 vpass_u16_tail_sse(
794 &intermediate[row * src_stride..],
795 block_w,
796 src_stride,
797 &tp,
798 taps,
799 max,
800 &mut dst[row * block_w..(row + 1) * block_w],
801 0,
802 round1,
803 );
804 }
805 }
806
807 /// Vertical pass, SSE2: [`vpass_avx2`] without the 16-column step.
808 ///
809 /// SSE2 is baseline x86_64; same slice contract as [`vpass_avx2`].
810 #[arcane]
811 pub fn vpass_sse41(
812 _t: X64V2Token,
813 intermediate: &[i16],
814 block_w: usize,
815 src_stride: usize,
816 rows: usize,
817 taps: &[i32; 8],
818 acc: &mut [i32],
819 ) {
820 debug_assert!(
821 intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w
822 );
823 let tp = tap_pairs(&taps16(taps));
824 for row in 0..rows {
825 vpass_tail_sse(
826 &intermediate[row * src_stride..],
827 block_w,
828 src_stride,
829 &tp,
830 taps,
831 &mut acc[row * block_w..(row + 1) * block_w],
832 0,
833 );
834 }
835 }
836
837 /// Horizontal pass, SSE2: [`hpass_avx2`]'s scheme at 8 outputs per
838 /// iteration; the remainder (a width-4 block, or a 4-column tail) is the
839 /// scalar loop, which is where 4-tap kernels mostly land anyway.
840 ///
841 /// `src.len()` must be at least `out.len() + 7`. SSE2 is baseline x86_64.
842 #[arcane]
843 pub fn hpass_sse2(
844 _t: X64V2Token,
845 src: &[u16],
846 src_stride: usize,
847 rows: usize,
848 block_w: usize,
849 t16: &[i16; 8],
850 out: &mut [i16],
851 round0: u32,
852 ) {
853 debug_assert!(out.len() >= rows * block_w);
854 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
855 let tp = tap_pairs(t16);
856 let tv = [
857 _mm_set1_epi32(tp[0]),
858 _mm_set1_epi32(tp[1]),
859 _mm_set1_epi32(tp[2]),
860 _mm_set1_epi32(tp[3]),
861 ];
862 let rnd = _mm_set1_epi32(1 << (round0 - 1));
863 for r in 0..rows {
864 let sp = &src[r * src_stride..];
865 let op = &mut out[r * block_w..(r + 1) * block_w];
866 let mut c = 0usize;
867 while c + 8 <= block_w {
868 let mut e = _mm_setzero_si128();
869 let mut o = _mm_setzero_si128();
870 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
871 #[allow(clippy::needless_range_loop)]
872 for k in 0..4 {
873 let se: __m128i = ld(&sp[c + 2 * k..]);
874 e = _mm_add_epi32(e, _mm_madd_epi16(se, tv[k]));
875 let so: __m128i = ld(&sp[c + 2 * k + 1..]);
876 o = _mm_add_epi32(o, _mm_madd_epi16(so, tv[k]));
877 }
878 e = _mm_sra_epi32(_mm_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32));
879 o = _mm_sra_epi32(_mm_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32));
880 let lo = _mm_unpacklo_epi32(e, o);
881 let hi = _mm_unpackhi_epi32(e, o);
882 st(&mut op[c..], _mm_packs_epi32(lo, hi));
883 c += 8;
884 }
885 while c < block_w {
886 let mut sum = 0i32;
887 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
888 #[allow(clippy::needless_range_loop)]
889 for t in 0..8 {
890 sum += i32::from(t16[t]) * i32::from(sp[c + t] as i16);
891 }
892 op[c] = sat16(round2(sum, round0));
893 c += 1;
894 }
895 }
896 }
897
898 // Test-only entry points that run one kernel with a summoned token, so
899 // the unit tests can exercise each tier directly (callers check the
900 // feature first).
901 #[cfg(test)]
902 pub mod entry {
903 use archmage::SimdToken;
904 #[allow(unused_variables)]
905 pub fn hpass_sse2(
906 src: &[u16],
907 src_stride: usize,
908 rows: usize,
909 block_w: usize,
910 t16: &[i16; 8],
911 out: &mut [i16],
912 round0: u32,
913 ) {
914 let t = archmage::X64V2Token::summon().expect("sse4.1 entry on a CPU without sse4.1");
915 super::hpass_sse2(t, src, src_stride, rows, block_w, t16, out, round0)
916 }
917
918 #[allow(unused_variables)]
919 pub fn vpass_sse41(
920 intermediate: &[i16],
921 block_w: usize,
922 src_stride: usize,
923 rows: usize,
924 taps: &[i32; 8],
925 acc: &mut [i32],
926 ) {
927 let t = archmage::X64V2Token::summon().expect("sse4.1 entry on a CPU without sse4.1");
928 super::vpass_sse41(t, intermediate, block_w, src_stride, rows, taps, acc)
929 }
930
931 #[allow(unused_variables)]
932 pub fn hpass_avx2(
933 src: &[u16],
934 src_stride: usize,
935 rows: usize,
936 block_w: usize,
937 t16: &[i16; 8],
938 out: &mut [i16],
939 round0: u32,
940 ) {
941 let t = archmage::X64V3Token::summon().expect("avx2 entry on a CPU without avx2");
942 super::hpass_avx2(t, src, src_stride, rows, block_w, t16, out, round0)
943 }
944
945 #[allow(unused_variables)]
946 pub fn vpass_avx2(
947 intermediate: &[i16],
948 block_w: usize,
949 src_stride: usize,
950 rows: usize,
951 taps: &[i32; 8],
952 acc: &mut [i32],
953 ) {
954 let t = archmage::X64V3Token::summon().expect("avx2 entry on a CPU without avx2");
955 super::vpass_avx2(t, intermediate, block_w, src_stride, rows, taps, acc)
956 }
957
958 #[allow(unused_variables, clippy::too_many_arguments)]
959 pub fn vpass_row_u16_avx2(
960 intermediate: &[i16],
961 block_w: usize,
962 src_stride: usize,
963 rows: usize,
964 taps: &[i32; 8],
965 max: i32,
966 dst: &mut [u16],
967 round1: u32,
968 ) {
969 let t = archmage::X64V3Token::summon().expect("avx2 entry on a CPU without avx2");
970 super::vpass_row_u16_avx2(t, intermediate, block_w, src_stride, rows, taps, max, dst, round1)
971 }
972
973 #[allow(unused_variables, clippy::too_many_arguments)]
974 pub fn vpass_row_u16_sse41(
975 intermediate: &[i16],
976 block_w: usize,
977 src_stride: usize,
978 rows: usize,
979 taps: &[i32; 8],
980 max: i32,
981 dst: &mut [u16],
982 round1: u32,
983 ) {
984 let t = archmage::X64V2Token::summon().expect("sse4.1 entry on a CPU without sse4.1");
985 super::vpass_row_u16_sse41(t, intermediate, block_w, src_stride, rows, taps, max, dst, round1)
986 }
987 }
988}
989
990/// lane-perf2: one row of the separable filter's horizontal pass, dav1d
991/// style. When the row's whole 8-tap footprint (`x0-3 .. x0+block_w+4`) lies
992/// inside the reference's true extent -- the overwhelmingly common case --
993/// the row is one contiguous slice and the taps are a fixed `[i32; 8]`, so
994/// the per-sample `Clip3` and the per-tap table load both leave the inner
995/// loop and it auto-vectorises. The edge case keeps the exact spec form
996/// (`sample`'s clamp per tap); both arms compute the same sums.
997#[inline]
998fn hpass_row(
999 reference: &[u16],
1000 row_base: usize,
1001 true_width: usize,
1002 x0: i32,
1003 taps: &[i32; 8],
1004 out: &mut [i16],
1005 round0: u32,
1006) {
1007 let block_w = out.len();
1008 let start = x0 - 3;
1009 if start >= 0 && start as usize + block_w + 7 <= true_width {
1010 let s = row_base + start as usize;
1011 if let Some(src) = reference.get(s..s + block_w + 7) {
1012 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the
1013 // bit depth), so the products are exactly the i32 ones above but
1014 // the widening multiply is one instruction per pair.
1015 let t16 = [
1016 taps[0] as i16,
1017 taps[1] as i16,
1018 taps[2] as i16,
1019 taps[3] as i16,
1020 taps[4] as i16,
1021 taps[5] as i16,
1022 taps[6] as i16,
1023 taps[7] as i16,
1024 ];
1025 hpass_contig(src, &t16, out, round0);
1026 return;
1027 }
1028 }
1029 for (c, o) in out.iter_mut().enumerate() {
1030 let mut sum = 0i32;
1031 for (t, &tap) in taps.iter().enumerate() {
1032 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
1033 sum += tap * i32::from(reference[row_base + x]);
1034 }
1035 *o = sat16(round2(sum, round0));
1036 }
1037}
1038
1039/// lane-perf2: the unscaled horizontal pass, `block_h + 7` rows of
1040/// [`hpass_row`] with the vertical clamp hoisted out of the row.
1041#[allow(clippy::too_many_arguments)]
1042fn horizontal_pass_unscaled(
1043 reference: &[u16],
1044 stride: usize,
1045 true_width: usize,
1046 true_height: usize,
1047 x0: i32,
1048 y0: i32,
1049 taps: &[i32; 8],
1050 block_w: usize,
1051 rows: usize,
1052 intermediate: &mut [i16],
1053 round0: u32,
1054) {
1055 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
1056 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
1057 // needs no filter at all -- one widened row read.
1058 let identity = taps[3] == 128 && taps.iter().enumerate().all(|(i, &t)| i == 3 || t == 0);
1059 // lane-mc2: when the whole `rows x (block_w+7)` footprint lies inside the
1060 // reference -- the overwhelmingly common case -- every per-row test in
1061 // the general loop below (the vertical clamp, the horizontal interior
1062 // test, the slice bounds check, the tap narrowing and the SIMD dispatch)
1063 // has the same answer for every row, so it is hoisted out and the loop
1064 // becomes a walk of `stride`. Same sums, same order.
1065 let start = x0 - 3;
1066 let y_top = y0 - 3;
1067 if !identity
1068 && start >= 0
1069 && y_top >= 0
1070 && start as usize + block_w + 7 <= true_width
1071 && y_top as usize + rows <= true_height
1072 {
1073 let base = y_top as usize * stride + start as usize;
1074 let span = block_w + 7;
1075 if base + (rows - 1) * stride + span <= reference.len() {
1076 let t16 = [
1077 taps[0] as i16,
1078 taps[1] as i16,
1079 taps[2] as i16,
1080 taps[3] as i16,
1081 taps[4] as i16,
1082 taps[5] as i16,
1083 taps[6] as i16,
1084 taps[7] as i16,
1085 ];
1086 hpass_rows(
1087 &reference[base..],
1088 stride,
1089 rows,
1090 block_w,
1091 &t16,
1092 &mut intermediate[..rows * block_w],
1093 round0,
1094 );
1095 return;
1096 }
1097 }
1098 for r in 0..rows {
1099 let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize;
1100 let out = &mut intermediate[r * block_w..(r + 1) * block_w];
1101 if identity {
1102 let gain = 128 >> round0;
1103 if x0 >= 0
1104 && x0 as usize + block_w <= true_width
1105 && let Some(src) =
1106 reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w)
1107 {
1108 for (o, &s) in out.iter_mut().zip(src) {
1109 *o = (gain * i32::from(s)) as i16;
1110 }
1111 continue;
1112 }
1113 for (c, o) in out.iter_mut().enumerate() {
1114 let x = (x0 + c as i32).clamp(0, true_width as i32 - 1) as usize;
1115 *o = (gain * i32::from(reference[y * stride + x])) as i16;
1116 }
1117 continue;
1118 }
1119 hpass_row(reference, y * stride, true_width, x0, taps, out, round0);
1120 }
1121}
1122
1123/// lane-perf2: one output row of the vertical pass, accumulated tap-major so
1124/// the inner loop walks two contiguous `i32` slices (vectorisable) instead of
1125/// striding the intermediate by `block_w` per tap. A zero tap is skipped --
1126/// adding `0 * x` is exactly nothing, and the 4-tap kernels zero four of the
1127/// eight slots. `acc` is left holding the unrounded sums.
1128pub(crate) fn vpass_row(
1129 intermediate: &[i16],
1130 block_w: usize,
1131 src_stride: usize,
1132 rows: usize,
1133 taps: &[i32; 8],
1134 acc: &mut [i32],
1135) {
1136 #[cfg(target_arch = "x86_64")]
1137 {
1138 if let Some(t) = archmage::X64V3Token::summon() {
1139 simd::vpass_avx2(t, intermediate, block_w, src_stride, rows, taps, acc);
1140 return;
1141 }
1142 if let Some(t) = archmage::X64V2Token::summon() {
1143 simd::vpass_sse41(t, intermediate, block_w, src_stride, rows, taps, acc);
1144 return;
1145 }
1146 }
1147 vpass_row_scalar_all(intermediate, block_w, src_stride, rows, taps, acc);
1148}
1149
1150#[inline]
1151fn vpass_row_scalar_all(
1152 intermediate: &[i16],
1153 block_w: usize,
1154 src_stride: usize,
1155 rows: usize,
1156 taps: &[i32; 8],
1157 acc: &mut [i32],
1158) {
1159 for row in 0..rows {
1160 vpass_row_scalar(
1161 &intermediate[row * src_stride..],
1162 block_w,
1163 src_stride,
1164 0,
1165 taps,
1166 &mut acc[row * block_w..(row + 1) * block_w],
1167 );
1168 }
1169}
1170
1171/// lane-mc: [`vpass_row`] with the output rounding fused in, for the two
1172/// entry points whose destination is `u16` samples. The unrounded `i32` sums
1173/// used to be stored to a scratch row and read straight back by a rounding
1174/// loop; here they never leave the register.
1175// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1176#[allow(clippy::too_many_arguments)]
1177fn vpass_row_u16(
1178 intermediate: &[i16],
1179 block_w: usize,
1180 src_stride: usize,
1181 rows: usize,
1182 taps: &[i32; 8],
1183 max: i32,
1184 dst: &mut [u16],
1185 round1: u32,
1186) {
1187 #[cfg(target_arch = "x86_64")]
1188 {
1189 if let Some(t) = archmage::X64V3Token::summon() {
1190 simd::vpass_row_u16_avx2(
1191 t,
1192 intermediate,
1193 block_w,
1194 src_stride,
1195 rows,
1196 taps,
1197 max,
1198 dst,
1199 round1,
1200 );
1201 return;
1202 }
1203 if let Some(t) = archmage::X64V2Token::summon() {
1204 simd::vpass_row_u16_sse41(
1205 t,
1206 intermediate,
1207 block_w,
1208 src_stride,
1209 rows,
1210 taps,
1211 max,
1212 dst,
1213 round1,
1214 );
1215 return;
1216 }
1217 }
1218 vpass_row_u16_scalar_all(
1219 intermediate,
1220 block_w,
1221 src_stride,
1222 rows,
1223 taps,
1224 max,
1225 dst,
1226 round1,
1227 );
1228}
1229
1230#[inline]
1231#[allow(clippy::too_many_arguments)]
1232fn vpass_row_u16_scalar_all(
1233 intermediate: &[i16],
1234 block_w: usize,
1235 src_stride: usize,
1236 rows: usize,
1237 taps: &[i32; 8],
1238 max: i32,
1239 dst: &mut [u16],
1240 round1: u32,
1241) {
1242 for row in 0..rows {
1243 vpass_row_u16_scalar(
1244 &intermediate[row * src_stride..],
1245 block_w,
1246 src_stride,
1247 0,
1248 taps,
1249 max,
1250 &mut dst[row * block_w..(row + 1) * block_w],
1251 round1,
1252 );
1253 }
1254}
1255
1256/// The scalar reference for [`vpass_row_u16`].
1257// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1258#[allow(clippy::too_many_arguments)]
1259fn vpass_row_u16_scalar(
1260 intermediate: &[i16],
1261 block_w: usize,
1262 src_stride: usize,
1263 row: usize,
1264 taps: &[i32; 8],
1265 max: i32,
1266 dst: &mut [u16],
1267 round1: u32,
1268) {
1269 for (c, d) in dst[..block_w].iter_mut().enumerate() {
1270 let mut sum = 0i32;
1271 for (t, &tap) in taps.iter().enumerate() {
1272 sum += tap * i32::from(intermediate[(row + t) * src_stride + c]);
1273 }
1274 *d = round2(sum, round1).clamp(0, max) as u16;
1275 }
1276}
1277
1278/// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).
1279fn vpass_row_scalar(
1280 intermediate: &[i16],
1281 block_w: usize,
1282 src_stride: usize,
1283 row: usize,
1284 taps: &[i32; 8],
1285 acc: &mut [i32],
1286) {
1287 acc[..block_w].fill(0);
1288 for (t, &tap) in taps.iter().enumerate() {
1289 if tap == 0 {
1290 continue;
1291 }
1292 let base = (row + t) * src_stride;
1293 for (a, &s) in acc[..block_w]
1294 .iter_mut()
1295 .zip(&intermediate[base..base + block_w])
1296 {
1297 *a += tap * i32::from(s);
1298 }
1299 }
1300}
1301
1302thread_local! {
1303 /// lane-perf2: the separable filter's intermediate buffer, reused across
1304 /// calls -- a 4K inter frame runs `predict*` hundreds of thousands of
1305 /// times and each call used to `vec![0i32; (block_h+7) * block_w]`. The
1306 /// horizontal pass writes every element it later reads, so no clearing is
1307 /// needed; the tail `block_w` elements are the vertical pass's row
1308 /// accumulator.
1309 static MC_SCRATCH: std::cell::RefCell<(Vec<i16>, Vec<i32>)> =
1310 const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
1311}
1312
1313/// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus
1314/// a `block_w` accumulator (see [`MC_SCRATCH`]).
1315fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i16], &mut [i32]) -> R) -> R {
1316 MC_SCRATCH.with(|s| {
1317 let mut buf = s.borrow_mut();
1318 let (inter, acc) = &mut *buf;
1319 let need = rows * block_w;
1320 if inter.len() < need {
1321 inter.resize(need, 0);
1322 }
1323 if acc.len() < block_w {
1324 acc.resize(block_w, 0);
1325 }
1326 f(&mut inter[..need], &mut acc[..block_w])
1327 })
1328}
1329
1330/// Predicts one `block_w * block_h` block into `dst`, row-major, from
1331/// `reference` (row-major, stride `stride`, true content
1332/// `true_width` x `true_height` -- a reference frame's decoded picture
1333/// buffer can be wider/taller than the true frame it holds, when this
1334/// encoder pads a picture to a whole number of superblocks; a spec decoder
1335/// never codes syntax for those extra columns/rows, so motion compensation
1336/// must clamp to the true extent, not the buffer's own stride).
1337///
1338/// `x_q4` / `y_q4` are the block's top-left position in the reference, in
1339/// 1/16-pel units (an integer MV has its low 4 bits zero); this function
1340/// splits each into its whole-sample part and its 0..16 fraction itself, so
1341/// the caller need not pre-split a motion vector.
1342///
1343/// # Panics
1344/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1345/// empty.
1346#[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape
1347pub(crate) fn predict(
1348 reference: &[u16],
1349 stride: usize,
1350 true_width: usize,
1351 true_height: usize,
1352 x_q4: i32,
1353 y_q4: i32,
1354 block_w: usize,
1355 block_h: usize,
1356 dst: &mut [u16],
1357 fctx: &crate::decode::FrameCtx,
1358) {
1359 predict_with_filter(
1360 reference,
1361 stride,
1362 true_width,
1363 true_height,
1364 x_q4,
1365 y_q4,
1366 block_w,
1367 block_h,
1368 // lane-refs: the FRAME's kernel (spec 6.8.9), not a hardwired
1369 // `Regular` -- `FrameCtx::interp_filter` is what the encoder set from
1370 // the header it is about to write, and every decode leaves it at
1371 // `Regular` (the decoder's own inter path calls
1372 // `predict_with_filters` with the kernels it parsed).
1373 fctx.interp_filter.get(),
1374 dst,
1375 fctx,
1376 );
1377}
1378
1379/// [`predict`], selecting the interpolation filter kernel explicitly (spec
1380/// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same
1381/// kernel both directions.
1382#[allow(clippy::too_many_arguments)]
1383pub(crate) fn predict_with_filter(
1384 reference: &[u16],
1385 stride: usize,
1386 true_width: usize,
1387 true_height: usize,
1388 x_q4: i32,
1389 y_q4: i32,
1390 block_w: usize,
1391 block_h: usize,
1392 filter_kind: InterpFilterKind,
1393 dst: &mut [u16],
1394 fctx: &crate::decode::FrameCtx,
1395) {
1396 predict_with_filters(
1397 reference,
1398 stride,
1399 true_width,
1400 true_height,
1401 x_q4,
1402 y_q4,
1403 block_w,
1404 block_h,
1405 filter_kind,
1406 filter_kind,
1407 dst,
1408 fctx,
1409 );
1410}
1411
1412/// [`predict_with_filter`], with the horizontal (`interp_filter[0]`) and
1413/// vertical (`interp_filter[1]`) kernels chosen independently -- spec
1414/// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),
1415/// so the two passes can genuinely differ.
1416#[allow(clippy::too_many_arguments)]
1417pub(crate) fn predict_with_filters(
1418 reference: &[u16],
1419 stride: usize,
1420 true_width: usize,
1421 true_height: usize,
1422 x_q4: i32,
1423 y_q4: i32,
1424 block_w: usize,
1425 block_h: usize,
1426 h_kind: InterpFilterKind,
1427 v_kind: InterpFilterKind,
1428 dst: &mut [u16],
1429 fctx: &crate::decode::FrameCtx,
1430) {
1431 predict_with_filters_kern(
1432 reference,
1433 stride,
1434 true_width,
1435 true_height,
1436 x_q4,
1437 y_q4,
1438 block_w,
1439 block_h,
1440 block_w,
1441 block_h,
1442 h_kind,
1443 v_kind,
1444 dst,
1445 fctx,
1446 );
1447}
1448
1449/// [`predict_with_filters`] with the 4-tap decision taken from the block's
1450/// TRUE width/height (`kern_w`/`kern_h`) rather than the destination buffer's.
1451/// libaom's `av1_get_interp_filter_params_with_block_size` (reconinter.h,
1452/// called per axis from `inter_predictor` with `w` then `h`) picks the narrow
1453/// kernel from the PREDICTION block's own dimensions; our inter path predicts
1454/// a rectangular block over its enclosing square buffer, so a rect block whose
1455/// chroma is 4 wide or 4 tall (luma 8x16 / 16x8 and taller kin) must still ask
1456/// for the 4-tap kernel on that axis -- lane-rectchroma2 r1.
1457#[allow(clippy::too_many_arguments)]
1458pub(crate) fn predict_with_filters_kern(
1459 reference: &[u16],
1460 stride: usize,
1461 true_width: usize,
1462 true_height: usize,
1463 x_q4: i32,
1464 y_q4: i32,
1465 block_w: usize,
1466 block_h: usize,
1467 kern_w: usize,
1468 kern_h: usize,
1469 h_kind: InterpFilterKind,
1470 v_kind: InterpFilterKind,
1471 dst: &mut [u16],
1472 fctx: &crate::decode::FrameCtx,
1473) {
1474 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1475 assert!(!reference.is_empty(), "a reference plane has samples");
1476 hit!(INTER_PRED_HITS);
1477
1478 #[cfg(test)]
1479 let stage_t = crate::encode::stage_start();
1480
1481 let x0 = x_q4.div_euclid(16);
1482 let xfrac = x_q4.rem_euclid(16) as usize;
1483 let y0 = y_q4.div_euclid(16);
1484 let yfrac = y_q4.rem_euclid(16) as usize;
1485 if crate::envflags::env_flag!("EC_MC_TRACE") && block_w >= 4 {
1486 eprintln!(
1487 "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}"
1488 );
1489 }
1490
1491 // Whole-pel fast path: `SUBPEL_FILTERS[0]` is the identity tap (`128` at
1492 // its centre, everything else `0`), and both rounding shifts are exactly
1493 // that filter's own gain (see `INTER_ROUND_1`'s doc comment), so the two
1494 // 8-tap passes reproduce the reference sample byte-for-byte here --
1495 // `integer_mv_is_identity` below pins that. Skipping straight to a
1496 // clamped copy is bit-identical, not an approximation: it matters
1497 // because the motion search's own log/diamond stage (`motion.rs`) is
1498 // whole-pel-only and calls `predict` for every candidate it prices, so
1499 // this path is what most of a search's `predict` calls actually hit
1500 // (measured: `stage_timing_breakdown_inter` attributed 403 of a 720p
1501 // inter frame's 408ms motion-search bucket to `predict`, almost all of
1502 // it whole-pel candidates from stage 1).
1503 if xfrac == 0 && yfrac == 0 {
1504 for row in 0..block_h {
1505 let y = (y0 + row as i32).clamp(0, true_height as i32 - 1) as usize;
1506 let row_base = y * stride;
1507 let out = &mut dst[row * block_w..(row + 1) * block_w];
1508 // lane-perf2: an interior row is one contiguous copy.
1509 if x0 >= 0
1510 && x0 as usize + block_w <= true_width
1511 && let Some(src) =
1512 reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w)
1513 {
1514 // The common widths get a constant-length copy: at 8
1515 // samples a `memcpy` call costs more than the move it
1516 // makes, and 8x8 is the most common inter block on real
1517 // 4K content.
1518 match block_w {
1519 4 => out[..4].copy_from_slice(&src[..4]),
1520 8 => out[..8].copy_from_slice(&src[..8]),
1521 16 => out[..16].copy_from_slice(&src[..16]),
1522 _ => out.copy_from_slice(src),
1523 }
1524 continue;
1525 }
1526 for (col, o) in out.iter_mut().enumerate() {
1527 let x = (x0 + col as i32).clamp(0, true_width as i32 - 1) as usize;
1528 *o = reference[row_base + x];
1529 }
1530 }
1531 #[cfg(test)]
1532 crate::encode::stage_since(1, stage_t);
1533 return;
1534 }
1535
1536 let (h_wide, h_narrow) = h_kind.tables();
1537 let (v_wide, v_narrow) = v_kind.tables();
1538 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1539 let h_filter = if kern_w <= 4 {
1540 &h_narrow[xfrac]
1541 } else {
1542 &h_wide[xfrac]
1543 };
1544 let v_filter = if kern_h <= 4 {
1545 &v_narrow[yfrac]
1546 } else {
1547 &v_wide[yfrac]
1548 };
1549
1550 // The vertical pass reads 3 rows above and 4 below the block, so the
1551 // horizontal pass must produce that many extra intermediate rows.
1552 // A whole-pel vertical position needs neither the 3 rows above nor the 4
1553 // below, and its vertical pass is the identity tap: `Round2(128 * a,
1554 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the
1555 // block's own first row where the pass would have put the 4th.
1556 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1557 let max = crate::decode::sample_max(fctx);
1558 // lane-av112bit: the frame's rounding pair (libaom `get_conv_params_no_round`
1559 // via [`round_pair`]) -- 3/11 at 8 and 10 bits, 5/9 at 12.
1560 let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
1561 // lane-mc2: a whole-pel horizontal position makes the horizontal pass the
1562 // identity tap, whose output is `(128 >> round0) * s` (`Round2(128 * s,
1563 // round0)` with the tap 128). The vertical pass then computes
1564 // `Round2(sum(tap * ((128 >> round0) * s)), round1)`, which is the same
1565 // 8-tap sum taken straight off the reference rows with every tap scaled
1566 // by `128 >> round0` -- bit-identical (128 is a multiple of `2^round0` at
1567 // every supported depth), and it skips materialising `block_h + 7`
1568 // intermediate rows. Interior blocks only; an edge block still needs the
1569 // clamped read.
1570 if xfrac != 0 || yfrac == 0 {
1571 // fall through to the two-pass path
1572 if xfrac != 0 || yfrac != 0 {
1573 hit!(MC_SUBPEL_HITS);
1574 }
1575 } else {
1576 let top = y0 - 3;
1577 if top >= 0
1578 && x0 >= 0
1579 && x0 as usize + block_w <= true_width
1580 && top as usize + block_h + 7 <= true_height
1581 {
1582 let base = top as usize * stride + x0 as usize;
1583 if base + (block_h + 6) * stride + block_w <= reference.len() {
1584 let mut v16 = [0i32; 8];
1585 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1586 *o = t * (128 >> round0);
1587 }
1588 // Samples are below `2^15` at every supported bit depth, so
1589 // the same bytes read as `i16` are the same values.
1590 let src: &[i16] = bytemuck::cast_slice(reference);
1591 vpass_row_u16(
1592 &src[base..],
1593 block_w,
1594 stride,
1595 block_h,
1596 &v16,
1597 max,
1598 dst,
1599 round1,
1600 );
1601 #[cfg(test)]
1602 crate::encode::stage_since(1, stage_t);
1603 return;
1604 }
1605 }
1606 }
1607 with_scratch(rows, block_w, |intermediate, _acc| {
1608 horizontal_pass_unscaled(
1609 reference,
1610 stride,
1611 true_width,
1612 true_height,
1613 x0,
1614 if yfrac == 0 { y0 + 3 } else { y0 },
1615 h_filter,
1616 block_w,
1617 rows,
1618 intermediate,
1619 round0,
1620 );
1621 if yfrac == 0 {
1622 // The vertical filter is the identity tap here:
1623 // `Round2(128 * a, round1) == Round2(a, round1 - 7)` exactly.
1624 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1625 *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16;
1626 }
1627 return;
1628 }
1629 vpass_row_u16(
1630 intermediate,
1631 block_w,
1632 block_w,
1633 block_h,
1634 v_filter,
1635 max,
1636 dst,
1637 round1,
1638 );
1639 });
1640
1641 #[cfg(test)]
1642 crate::encode::stage_since(1, stage_t);
1643}
1644
1645/// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h`
1646/// `REF_NO_SCALE`): `x_scale_fp == REF_NO_SCALE` means the stored reference's
1647/// luma width equals the current frame's, so [`predict_scaled`] reduces
1648/// exactly to [`predict_with_filters`] (verified in
1649/// `predict_scaled_at_no_scale_matches_predict_with_filters` below).
1650pub const REF_NO_SCALE: i64 = 1 << 14;
1651
1652/// The horizontal scale ratio spec 7.11.3.3 derives from luma widths only
1653/// (libaom `av1_setup_scale_factors_for_frame`, luma widths, `REF_SCALE_SHIFT
1654/// == 14`): `other_width` is the stored reference picture's own luma width,
1655/// `this_width` the current frame's coded luma width. The vertical ratio is
1656/// the same formula on heights ([`RefScale::new`]).
1657pub fn scale_factor(other_width: usize, this_width: usize) -> i64 {
1658 (((other_width as i64) << 14) + this_width as i64 / 2) / this_width as i64
1659}
1660
1661/// Spec 7.11.3.3's `xScale` / `yScale` for one reference: the reference's
1662/// own luma size against the current frame's (`REF_SCALE_SHIFT == 14`).
1663/// `x` is [`scale_factor`]'s width ratio, `y` the same ratio on heights. A
1664/// reference is "scaled" (libaom `av1_is_scaled`) when either differs.
1665#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1666pub struct RefScale {
1667 /// `xScale`: reference width over current width, Q14.
1668 pub x: i64,
1669 /// `yScale`: reference height over current height, Q14.
1670 pub y: i64,
1671}
1672
1673impl RefScale {
1674 /// The scale of a reference of `ref_width` x `ref_height` for a current
1675 /// frame of `cur_width` x `cur_height` (all luma, cropped sizes).
1676 #[must_use]
1677 pub fn new(ref_width: usize, ref_height: usize, cur_width: usize, cur_height: usize) -> Self {
1678 Self {
1679 x: scale_factor(ref_width, cur_width),
1680 y: scale_factor(ref_height, cur_height),
1681 }
1682 }
1683
1684 /// Neither axis scaled: the reference is the current frame's own size.
1685 pub const UNSCALED: Self = Self {
1686 x: REF_NO_SCALE,
1687 y: REF_NO_SCALE,
1688 };
1689
1690 /// `true` when neither axis scales (the ordinary, byte-identical path).
1691 #[must_use]
1692 pub fn is_unscaled(self) -> bool {
1693 self.x == REF_NO_SCALE && self.y == REF_NO_SCALE
1694 }
1695
1696 /// `true` when a reference of this size is outside the spec's limits for
1697 /// a conforming scaled reference (7.11.3.3): more than 2x down on either
1698 /// axis (`2 * cur < ref`), or more than 16x up (`cur > 16 * ref`).
1699 #[must_use]
1700 pub fn out_of_limits(
1701 ref_width: usize,
1702 ref_height: usize,
1703 cur_width: usize,
1704 cur_height: usize,
1705 ) -> bool {
1706 2 * cur_width < ref_width
1707 || 2 * cur_height < ref_height
1708 || cur_width > 16 * ref_width
1709 || cur_height > 16 * ref_height
1710 }
1711}
1712
1713thread_local! {
1714 /// lane-superres r10: firing count for the bypass gate (class
1715 /// `gate-blind-to-feature`) -- how many times [`predict_scaled`] itself
1716 /// ran, so the gate can hard-assert the scaled MC path actually fired
1717 /// rather than trust a pixel match alone (an unscaled reference would
1718 /// pass the pixels and prove nothing).
1719 static PREDICT_SCALED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1720}
1721
1722/// Current value of [`PREDICT_SCALED_HITS`].
1723pub fn predict_scaled_hits() -> usize {
1724 PREDICT_SCALED_HITS.with(|c| c.get())
1725}
1726
1727thread_local! {
1728 /// lane-av112bit: how many inter predictions took the two-pass SUBPEL
1729 /// path (a non-zero horizontal or vertical fraction) -- the 12-bit
1730 /// inter gate's proof that the frame's own `round_0`/`round_1` actually
1731 /// ran, not just the whole-pel identity copy (class
1732 /// `gate-blind-to-feature`).
1733 pub(crate) static MC_SUBPEL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1734
1735 /// lane-hbdinter: how many inter predictions this thread has produced
1736 /// (single-reference, scaled, and the compound intermediate entry). The
1737 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
1738 /// only intra blocks cannot pass it by construction (class
1739 /// `gate-blind-to-feature`).
1740 static INTER_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1741
1742 /// lane-rectchroma2 r1: how often the 4-tap decision came out DIFFERENT
1743 /// from what the destination buffer's own dimensions would have given --
1744 /// i.e. how often a rectangular block predicted over its enclosing square
1745 /// buffer asked for libaom's narrow kernel on an axis. Zero means a gate
1746 /// never exercised the rect-chroma shape at all.
1747 static RECT_NARROW_KERN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1748}
1749
1750/// Current value of [`RECT_NARROW_KERN_HITS`].
1751pub fn rect_narrow_kern_hits() -> usize {
1752 RECT_NARROW_KERN_HITS.with(|c| c.get())
1753}
1754
1755/// Resets [`RECT_NARROW_KERN_HITS`] (per-attempt counting, class
1756/// `counter-from-refused-stream`).
1757pub fn reset_rect_narrow_kern_hits() {
1758 RECT_NARROW_KERN_HITS.with(|c| c.set(0));
1759}
1760
1761/// Bumps [`RECT_NARROW_KERN_HITS`] when the block's true dims pick a kernel
1762/// the destination buffer's dims would not have.
1763fn note_narrow_kern(block_w: usize, block_h: usize, kern_w: usize, kern_h: usize) {
1764 if (kern_w <= 4) != (block_w <= 4) || (kern_h <= 4) != (block_h <= 4) {
1765 hit!(RECT_NARROW_KERN_HITS);
1766 }
1767}
1768
1769/// Current value of [`INTER_PRED_HITS`].
1770pub fn inter_pred_hits() -> usize {
1771 INTER_PRED_HITS.with(|c| c.get())
1772}
1773
1774/// Current value of [`MC_SUBPEL_HITS`].
1775#[allow(dead_code)] // reader is test-only (the 12-bit inter witness); dead in non-test builds
1776pub(crate) fn mc_subpel_hits() -> usize {
1777 MC_SUBPEL_HITS.with(|c| c.get())
1778}
1779
1780fn round_pow2_64(value: i64, shift: u32) -> i64 {
1781 if shift == 0 {
1782 value
1783 } else {
1784 (value + (1i64 << (shift - 1))) >> shift
1785 }
1786}
1787
1788/// `ROUND_POWER_OF_TWO_SIGNED` (libaom `common/common.h`): halves round away
1789/// from zero's *magnitude* -- negative inputs are rounded like their
1790/// negation, not truncated toward zero the way a plain arithmetic shift
1791/// would.
1792fn round_pow2_signed_64(value: i64, shift: u32) -> i64 {
1793 if value < 0 {
1794 -round_pow2_64(-value, shift)
1795 } else {
1796 round_pow2_64(value, shift)
1797 }
1798}
1799
1800/// Spec 7.11.3.3's horizontal pass on a (possibly) scaled reference, shared
1801/// by [`predict_scaled`] and [`predict_compound_intermediate`] -- the two
1802/// differ only in their VERTICAL rounding ([`INTER_ROUND_1`] vs
1803/// [`INTER_ROUND_1_COMPOUND`]), never here. Each output column walks the
1804/// reference by `x_step_qn` (the Q14 scale rounded down to the Q10
1805/// `SCALE_SUBPEL_BITS` grid) and picks its own filter phase from the low
1806/// bits, so `x_scale_fp == REF_NO_SCALE` reduces to the ordinary stride-1
1807/// whole-pel walk with one fixed phase (pinned by
1808/// `predict_scaled_at_no_scale_matches_predict_with_filters`).
1809#[allow(clippy::too_many_arguments)]
1810fn horizontal_scaled_pass(
1811 reference: &[u16],
1812 stride: usize,
1813 true_width: usize,
1814 true_height: usize,
1815 x_q4: i32,
1816 y0: i32,
1817 x_scale_fp: i64,
1818 block_w: usize,
1819 kern_w: usize,
1820 rows: usize,
1821 h_kind: InterpFilterKind,
1822 intermediate: &mut [i16],
1823 round0: u32,
1824) {
1825 let x_step_qn = round_pow2_64(x_scale_fp, 4);
1826 let off = (x_scale_fp - REF_NO_SCALE) * 8;
1827 let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32;
1828 let (h_wide, h_narrow) = h_kind.tables();
1829 for c in 0..block_w {
1830 let x_qn = pos_x_q10 + c as i64 * x_step_qn;
1831 let int_pel = (x_qn >> 10) as i32;
1832 let filter_idx = ((x_qn & 1023) >> 6) as usize;
1833 let h_filter = if kern_w <= 4 {
1834 &h_narrow[filter_idx]
1835 } else {
1836 &h_wide[filter_idx]
1837 };
1838 for r in 0..rows {
1839 let y = y0 - 3 + r as i32;
1840 let mut sum = 0;
1841 for (t, &tap) in h_filter.iter().enumerate() {
1842 let x = int_pel + t as i32 - 3;
1843 sum += tap * sample(reference, stride, true_width, true_height, x, y);
1844 }
1845 intermediate[r * block_w + c] = round2(sum, round0) as i16;
1846 }
1847 }
1848}
1849
1850/// lane-perf2: the horizontal pass every two-pass entry point takes.
1851/// `horizontal_scaled_pass` was carrying the UNSCALED work too (every
1852/// compound prediction goes through it whatever the reference's scale), and
1853/// its per-column walk re-derives an integer position and a filter phase
1854/// that are constant at `REF_NO_SCALE`, reads the reference column-major,
1855/// and clamps per tap -- 14% of decode self time. At `REF_NO_SCALE` the
1856/// scaled walk reduces algebraically to `x0 = x_q4 / 16`, phase `x_q4 % 16`
1857/// (`pos_x_q10 == x_q4 * 64 + 32`, so `int_pel == x0` and
1858/// `(x_qn & 1023) >> 6 == xfrac` for every column), which is exactly
1859/// [`horizontal_pass_unscaled`] -- and
1860/// `predict_scaled_at_no_scale_matches_predict_with_filters` pins that
1861/// equality end to end. A genuinely scaled reference (superres) still takes
1862/// the general path.
1863#[allow(clippy::too_many_arguments)]
1864fn horizontal_pass(
1865 reference: &[u16],
1866 stride: usize,
1867 true_width: usize,
1868 true_height: usize,
1869 x_q4: i32,
1870 y0: i32,
1871 x_scale_fp: i64,
1872 block_w: usize,
1873 kern_w: usize,
1874 rows: usize,
1875 h_kind: InterpFilterKind,
1876 intermediate: &mut [i16],
1877 round0: u32,
1878) {
1879 if x_scale_fp == REF_NO_SCALE {
1880 let (h_wide, h_narrow) = h_kind.tables();
1881 let xfrac = x_q4.rem_euclid(16) as usize;
1882 let taps = if kern_w <= 4 {
1883 &h_narrow[xfrac]
1884 } else {
1885 &h_wide[xfrac]
1886 };
1887 horizontal_pass_unscaled(
1888 reference,
1889 stride,
1890 true_width,
1891 true_height,
1892 x_q4.div_euclid(16),
1893 y0,
1894 taps,
1895 block_w,
1896 rows,
1897 intermediate,
1898 round0,
1899 );
1900 return;
1901 }
1902 horizontal_scaled_pass(
1903 reference,
1904 stride,
1905 true_width,
1906 true_height,
1907 x_q4,
1908 y0,
1909 x_scale_fp,
1910 block_w,
1911 kern_w,
1912 rows,
1913 h_kind,
1914 intermediate,
1915 round0,
1916 );
1917}
1918
1919/// Spec 7.11.3.3 + 7.11.3.4 for a reference scaled vertically (and possibly
1920/// horizontally): the vertical 8-tap sums per output sample, before the
1921/// caller's own `InterRound1`. `dst` is `block_w * block_h`, row-major.
1922///
1923/// The position is the spec's: `startY = Round2Signed(origY * yScale -
1924/// (8 << 14), 8) + 32` with `origY = (y_q4 + 8)` (the `+ 8` is the spec's
1925/// `halfSample`, folded here as `(yScale - REF_NO_SCALE) * 8`), `yStep =
1926/// Round2(yScale, 4)`. The horizontal pass runs `intermediateHeight` rows from
1927/// the integer row `startY >> 10` (minus 3 taps), and output row `r` filters
1928/// `intermediate` rows `((startY & 1023) + yStep * r) >> 10` onward, with the
1929/// phase `(p >> 6) & 15`. Every reference sample is clamped to the true edges
1930/// (spec `Clip3`), as in [`sample`].
1931#[allow(clippy::too_many_arguments)]
1932fn scaled_vertical_sums(
1933 reference: &[u16],
1934 stride: usize,
1935 true_width: usize,
1936 true_height: usize,
1937 x_q4: i32,
1938 y_q4: i32,
1939 scale: RefScale,
1940 block_w: usize,
1941 block_h: usize,
1942 kern_w: usize,
1943 kern_h: usize,
1944 h_kind: InterpFilterKind,
1945 v_kind: InterpFilterKind,
1946 round0: u32,
1947 dst: &mut [i32],
1948) {
1949 let pos_y_q10 =
1950 round_pow2_signed_64(i64::from(y_q4) * scale.y + (scale.y - REF_NO_SCALE) * 8, 8) + 32;
1951 let y_step = round_pow2_64(scale.y, 4);
1952 let y_int = pos_y_q10 >> 10;
1953 let y_frac = pos_y_q10 & 1023;
1954 let inter_h = ((((block_h as i64 - 1) * y_step + 1023) >> 10) + 8) as usize;
1955 let (v_wide, v_narrow) = v_kind.tables();
1956 let v_table = if kern_h <= 4 { v_narrow } else { v_wide };
1957 let mut intermediate = vec![0i16; inter_h * block_w];
1958 horizontal_scaled_pass(
1959 reference,
1960 stride,
1961 true_width,
1962 true_height,
1963 x_q4,
1964 y_int as i32,
1965 scale.x,
1966 block_w,
1967 kern_w,
1968 inter_h,
1969 h_kind,
1970 &mut intermediate,
1971 round0,
1972 );
1973 for r in 0..block_h {
1974 let p = y_frac + y_step * r as i64;
1975 let taps = &v_table[((p >> 6) & 15) as usize];
1976 let base = (p >> 10) as usize;
1977 for c in 0..block_w {
1978 let mut sum = 0i32;
1979 for (t, &tap) in taps.iter().enumerate() {
1980 sum += tap * i32::from(intermediate[(base + t) * block_w + c]);
1981 }
1982 dst[r * block_w + c] = sum;
1983 }
1984 }
1985}
1986
1987/// [`predict_with_filters`]'s scaled-reference counterpart (spec 7.11.3.3 and
1988/// 7.11.3.4): used when the stored reference differs in size from the current
1989/// frame on either axis. A reference unscaled on both axes reproduces
1990/// `predict_with_filters` bit-exact (pinned by
1991/// `predict_scaled_at_no_scale_matches_predict_with_filters`). A scaled axis
1992/// walks the reference by its own step: the horizontal pass per column
1993/// (`x_qn`), the vertical pass per output row ([`scaled_vertical_sums`]).
1994///
1995/// # Panics
1996/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1997/// empty.
1998#[allow(clippy::too_many_arguments)]
1999pub(crate) fn predict_scaled(
2000 reference: &[u16],
2001 stride: usize,
2002 true_width: usize,
2003 true_height: usize,
2004 x_q4: i32,
2005 y_q4: i32,
2006 scale: RefScale,
2007 block_w: usize,
2008 block_h: usize,
2009 h_kind: InterpFilterKind,
2010 v_kind: InterpFilterKind,
2011 dst: &mut [u16],
2012 fctx: &crate::decode::FrameCtx,
2013) {
2014 predict_scaled_kern(
2015 reference,
2016 stride,
2017 true_width,
2018 true_height,
2019 x_q4,
2020 y_q4,
2021 scale,
2022 block_w,
2023 block_h,
2024 block_w,
2025 block_h,
2026 h_kind,
2027 v_kind,
2028 dst,
2029 fctx,
2030 );
2031}
2032
2033/// [`predict_scaled`] with the 4-tap decision from the block's true dims
2034/// (see [`predict_with_filters_kern`]).
2035#[allow(clippy::too_many_arguments)]
2036pub(crate) fn predict_scaled_kern(
2037 reference: &[u16],
2038 stride: usize,
2039 true_width: usize,
2040 true_height: usize,
2041 x_q4: i32,
2042 y_q4: i32,
2043 scale: RefScale,
2044 block_w: usize,
2045 block_h: usize,
2046 kern_w: usize,
2047 kern_h: usize,
2048 h_kind: InterpFilterKind,
2049 v_kind: InterpFilterKind,
2050 dst: &mut [u16],
2051 fctx: &crate::decode::FrameCtx,
2052) {
2053 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
2054 assert!(!reference.is_empty(), "a reference plane has samples");
2055 hit!(INTER_PRED_HITS);
2056 hit!(PREDICT_SCALED_HITS);
2057
2058 let max = crate::decode::sample_max(fctx);
2059 let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
2060 if scale.y != REF_NO_SCALE {
2061 // A vertically scaled reference: the general two-pass walk (spec
2062 // 7.11.3.4 with yStep != 1 << 10), rounded like the unscaled path.
2063 let mut sums = vec![0i32; block_w * block_h];
2064 scaled_vertical_sums(
2065 reference,
2066 stride,
2067 true_width,
2068 true_height,
2069 x_q4,
2070 y_q4,
2071 scale,
2072 block_w,
2073 block_h,
2074 kern_w,
2075 kern_h,
2076 h_kind,
2077 v_kind,
2078 round0,
2079 &mut sums,
2080 );
2081 for (d, &s) in dst.iter_mut().zip(sums.iter()) {
2082 *d = round2(s, round1).clamp(0, max) as u16;
2083 }
2084 return;
2085 }
2086 let x_scale_fp = scale.x;
2087 let y0 = y_q4.div_euclid(16);
2088 let yfrac = y_q4.rem_euclid(16) as usize;
2089
2090 // SCALE_SUBPEL_BITS == 10: x_step_qn is x_scale_fp (Q14) rounded down to
2091 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
2092 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
2093 let (v_wide, v_narrow) = v_kind.tables();
2094 note_narrow_kern(block_w, block_h, kern_w, kern_h);
2095 let v_filter = if kern_h <= 4 {
2096 &v_narrow[yfrac]
2097 } else {
2098 &v_wide[yfrac]
2099 };
2100
2101 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
2102 with_scratch(rows, block_w, |intermediate, _acc| {
2103 horizontal_pass(
2104 reference,
2105 stride,
2106 true_width,
2107 true_height,
2108 x_q4,
2109 if yfrac == 0 { y0 + 3 } else { y0 },
2110 x_scale_fp,
2111 block_w,
2112 kern_w,
2113 rows,
2114 h_kind,
2115 intermediate,
2116 round0,
2117 );
2118 if yfrac == 0 {
2119 // Identity vertical tap: `Round2(128 * a, round1) ==
2120 // Round2(a, round1 - 7)` exactly.
2121 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
2122 *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16;
2123 }
2124 return;
2125 }
2126 vpass_row_u16(
2127 intermediate,
2128 block_w,
2129 block_w,
2130 block_h,
2131 v_filter,
2132 max,
2133 dst,
2134 round1,
2135 );
2136 });
2137}
2138
2139/// [`predict_with_filters`] or [`predict_scaled`], on this reference's own
2140/// `x_scale_fp` -- the dispatch every inter path needs once a reference can be
2141/// scaled (superres). `REF_NO_SCALE` takes the ordinary stride-1 path, which
2142/// keeps [`predict_scaled_hits`] a true count of scaled predictions.
2143#[allow(clippy::too_many_arguments)]
2144pub(crate) fn predict_maybe_scaled(
2145 reference: &[u16],
2146 stride: usize,
2147 true_width: usize,
2148 true_height: usize,
2149 x_q4: i32,
2150 y_q4: i32,
2151 scale: RefScale,
2152 block_w: usize,
2153 block_h: usize,
2154 h_kind: InterpFilterKind,
2155 v_kind: InterpFilterKind,
2156 dst: &mut [u16],
2157 fctx: &crate::decode::FrameCtx,
2158) {
2159 if scale.is_unscaled() {
2160 predict_with_filters(
2161 reference,
2162 stride,
2163 true_width,
2164 true_height,
2165 x_q4,
2166 y_q4,
2167 block_w,
2168 block_h,
2169 h_kind,
2170 v_kind,
2171 dst,
2172 fctx,
2173 );
2174 } else {
2175 predict_scaled(
2176 reference,
2177 stride,
2178 true_width,
2179 true_height,
2180 x_q4,
2181 y_q4,
2182 scale,
2183 block_w,
2184 block_h,
2185 h_kind,
2186 v_kind,
2187 dst,
2188 fctx,
2189 );
2190 }
2191}
2192
2193/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch,
2194/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than
2195/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain
2196/// (still above 8-bit pixel range) instead of a finished sample --
2197/// `predict_compound_intermediate` below stops there and leaves the final
2198/// clip to whichever combine step (simple/distance-weighted average, or a
2199/// future masked blend) runs on the pair of intermediates.
2200const INTER_ROUND_1_COMPOUND: u32 = 7;
2201
2202/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 +
2203/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) ==
2204/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS`
2205/// (below) into one final shift.
2206const INTER_POST_ROUND: u32 = 4;
2207
2208/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two
2209/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether
2210/// they are the simple-average split (8/8) or a distance-weighted split
2211/// from [`crate::compound::dist_wtd_comp_weight_assign`].
2212const DIST_PRECISION_BITS: u32 = 4;
2213
2214/// [`predict_with_filters`]'s compound counterpart: same two-pass separable
2215/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`]
2216/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the
2217/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two
2218/// per-reference predictions in until [`combine_compound`] blends them.
2219/// `dst` receives one `i32` per sample, row-major, same shape as
2220/// [`predict_with_filters`]'s `u8` `dst`.
2221///
2222/// # Panics
2223/// Panics when `dst` is not `block_w * block_h` long, or the reference is
2224/// empty.
2225#[allow(clippy::too_many_arguments)]
2226pub(crate) fn predict_compound_intermediate(
2227 reference: &[u16],
2228 stride: usize,
2229 true_width: usize,
2230 true_height: usize,
2231 x_q4: i32,
2232 y_q4: i32,
2233 scale: RefScale,
2234 block_w: usize,
2235 block_h: usize,
2236 h_kind: InterpFilterKind,
2237 v_kind: InterpFilterKind,
2238 dst: &mut [i32],
2239 fctx: &crate::decode::FrameCtx,
2240) {
2241 predict_compound_intermediate_kern(
2242 reference,
2243 stride,
2244 true_width,
2245 true_height,
2246 x_q4,
2247 y_q4,
2248 scale,
2249 block_w,
2250 block_h,
2251 block_w,
2252 block_h,
2253 h_kind,
2254 v_kind,
2255 dst,
2256 fctx,
2257 );
2258}
2259
2260/// [`predict_compound_intermediate`] with the 4-tap decision from the block's
2261/// true dims (see [`predict_with_filters_kern`]).
2262#[allow(clippy::too_many_arguments)]
2263pub(crate) fn predict_compound_intermediate_kern(
2264 reference: &[u16],
2265 stride: usize,
2266 true_width: usize,
2267 true_height: usize,
2268 x_q4: i32,
2269 y_q4: i32,
2270 scale: RefScale,
2271 block_w: usize,
2272 block_h: usize,
2273 kern_w: usize,
2274 kern_h: usize,
2275 h_kind: InterpFilterKind,
2276 v_kind: InterpFilterKind,
2277 dst: &mut [i32],
2278 fctx: &crate::decode::FrameCtx,
2279) {
2280 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
2281 assert!(!reference.is_empty(), "a reference plane has samples");
2282 hit!(INTER_PRED_HITS);
2283
2284 if !scale.is_unscaled() {
2285 hit!(PREDICT_SCALED_HITS);
2286 }
2287 let x_scale_fp = scale.x;
2288 if scale.y != REF_NO_SCALE {
2289 let (round0, _) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
2290 scaled_vertical_sums(
2291 reference,
2292 stride,
2293 true_width,
2294 true_height,
2295 x_q4,
2296 y_q4,
2297 scale,
2298 block_w,
2299 block_h,
2300 kern_w,
2301 kern_h,
2302 h_kind,
2303 v_kind,
2304 round0,
2305 dst,
2306 );
2307 for d in dst.iter_mut() {
2308 *d = round2(*d, INTER_ROUND_1_COMPOUND);
2309 }
2310 return;
2311 }
2312
2313 let y0 = y_q4.div_euclid(16);
2314 let yfrac = y_q4.rem_euclid(16) as usize;
2315 if crate::envflags::env_flag!("EC_MC_TRACE") {
2316 eprintln!(
2317 "EC_MC_COMP x_q4={x_q4} y_q4={y_q4} w={block_w} h={block_h} hk={h_kind:?} vk={v_kind:?}"
2318 );
2319 }
2320
2321 let (v_wide, v_narrow) = v_kind.tables();
2322 note_narrow_kern(block_w, block_h, kern_w, kern_h);
2323 let v_filter = if kern_h <= 4 {
2324 &v_narrow[yfrac]
2325 } else {
2326 &v_wide[yfrac]
2327 };
2328
2329 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
2330 // lane-av112bit: the horizontal pass shares `predict_with_filters_kern`'s
2331 // `round_0` (the compound VERTICAL round below is `INTER_ROUND_1_COMPOUND`
2332 // at every bit depth), so the identity-tap gain moves with it the same way.
2333 let (round0, _round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
2334 // lane-mc2: the unscaled whole-pel horizontal position is the identity
2335 // tap, whose intermediate is `(128 >> round0) * s`, so the vertical pass
2336 // is the same 8-tap sum taken straight off the reference rows with the
2337 // taps scaled by that gain (see `predict_with_filters_kern`). Interior
2338 // blocks only.
2339 let x0 = x_q4.div_euclid(16);
2340 if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 {
2341 let top = y0 - 3;
2342 if top >= 0
2343 && x0 >= 0
2344 && x0 as usize + block_w <= true_width
2345 && top as usize + block_h + 7 <= true_height
2346 {
2347 let base = top as usize * stride + x0 as usize;
2348 if base + (block_h + 6) * stride + block_w <= reference.len() {
2349 let mut v16 = [0i32; 8];
2350 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
2351 *o = t * (128 >> round0);
2352 }
2353 // Samples are below `2^15` at every supported bit depth, so
2354 // the same bytes read as `i16` are the same values.
2355 let src: &[i16] = bytemuck::cast_slice(reference);
2356 vpass_row(&src[base..], block_w, stride, block_h, &v16, dst);
2357 for d in dst.iter_mut() {
2358 *d = round2(*d, INTER_ROUND_1_COMPOUND);
2359 }
2360 return;
2361 }
2362 }
2363 }
2364 with_scratch(rows, block_w, |intermediate, _acc| {
2365 horizontal_pass(
2366 reference,
2367 stride,
2368 true_width,
2369 true_height,
2370 x_q4,
2371 if yfrac == 0 { y0 + 3 } else { y0 },
2372 x_scale_fp,
2373 block_w,
2374 kern_w,
2375 rows,
2376 h_kind,
2377 intermediate,
2378 round0,
2379 );
2380 if yfrac == 0 {
2381 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
2382 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
2383 *d = i32::from(a);
2384 }
2385 return;
2386 }
2387 vpass_row(intermediate, block_w, block_w, block_h, v_filter, dst);
2388 for d in dst.iter_mut() {
2389 *d = round2(*d, INTER_ROUND_1_COMPOUND);
2390 }
2391 });
2392}
2393
2394/// Blends two [`predict_compound_intermediate`] outputs into a finished
2395/// 8-bit block (spec 7.11.3.15's weighted-average combine, the
2396/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the
2397/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
2398/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
2399/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
2400/// function does not cover -- see [`blend_masked_compound`]/[`diffwtd_mask`];
2401/// every kind absorbs the same CONV_BUF gain drop at 12 bits
2402/// ([`round_delta`]), witnessed by the 12-bit compound stream gate.
2403pub(crate) fn combine_compound(
2404 pred0: &[i32],
2405 pred1: &[i32],
2406 fwd_weight: i32,
2407 bck_weight: i32,
2408 dst: &mut [u16],
2409 fctx: &crate::decode::FrameCtx,
2410) {
2411 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
2412 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
2413 // lane-av112bit: `round_bits` is `2*FILTER_BITS - round_0 - round_1`
2414 // with the frame's own `round_0`, i.e. `INTER_POST_ROUND` minus
2415 // [`round_delta`] -- the CONV_BUF gain drops from 16x to 4x at 12-bit
2416 // (`round_0` 5, compound `round_1` 7) and this final round absorbs it.
2417 let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx)));
2418 for i in 0..dst.len() {
2419 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
2420 // applies the two shifts SEPARATELY: a truncating `>>
2421 // DIST_PRECISION_BITS` on the weighted sum, then `ROUND_POWER_OF_TWO`
2422 // by `round_bits == INTER_POST_ROUND`. Folding them into one
2423 // `Round2(sum, 8)` is NOT the same function -- it rounds up one LSB
2424 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
2425 // dropped low 4 bits are non-zero.
2426 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
2427 dst[i] = round2(sum >> DIST_PRECISION_BITS, post_round)
2428 .clamp(0, crate::decode::sample_max(fctx)) as u16;
2429 }
2430}
2431
2432/// lane-maskcomp r2: `build_compound_diffwtd_mask` (reconinter.c) --
2433/// `DIFFWTD_38`/`DIFFWTD_38_INV` (`mask_type` bit: 0/1). Operates directly on
2434/// the two [`predict_compound_intermediate`] outputs: libaom's own
2435/// `av1_build_compound_diffwtd_mask_d16_c` runs on its CONV_BUF domain (which
2436/// carries a constant `round_offset` bias baked into every sample by its
2437/// convolve stage), but `abs(src0 - src1)` cancels an equal bias on both
2438/// sides exactly, so the unbiased `i32` intermediates this crate already
2439/// produces give the identical `diff` libaom computes. `round` is
2440/// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
2441/// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
2442pub(crate) fn diffwtd_mask(
2443 pred0: &[i32],
2444 pred1: &[i32],
2445 inv: bool,
2446 mask: &mut [u8],
2447 fctx: &crate::decode::FrameCtx,
2448) {
2449 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
2450 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
2451 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
2452 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
2453 // bit-depth headroom the CONV_BUF domain carries, minus the [`round_delta`]
2454 // that moves `round_0` itself at 12-bit (`convolve.h:83`'s
2455 // `intbufrange > 16`; at 12-bit this is 14 - 5 - 7 + 4 == 6).
2456 let bd = u32::from(crate::decode::bit_depth(fctx));
2457 let round = INTER_POST_ROUND + bd.saturating_sub(8) - round_delta(bd);
2458 for i in 0..mask.len() {
2459 let diff = round2((pred0[i] - pred1[i]).abs(), round);
2460 let m = (38 + diff / 16).clamp(0, 64) as u8;
2461 mask[i] = if inv { 64 - m } else { m };
2462 }
2463}
2464
2465/// lane-maskcomp r2: `aom_lowbd_blend_a64_d16_mask_c` (blend_a64_mask.c),
2466/// algebraically simplified to this crate's unbiased `i32` intermediate
2467/// domain the same way [`diffwtd_mask`]'s doc comment derives -- libaom's
2468/// `res -= round_offset` step cancels exactly against the bias `m + (64-m)
2469/// == 64` contributes equally from both inputs, leaving `(m*pred0 +
2470/// (64-m)*pred1) >> 6` (a plain, unrounded shift, matching the C `>>` on
2471/// `int32_t`) then one final [`round2`] by [`INTER_POST_ROUND`]. `mask` is
2472/// always the LUMA-resolution mask (`mask_stride` == luma block width);
2473/// `(subw, subh)` are the PLANE's own subsampling shifts and pick the mask
2474/// read exactly as aom_dsp/blend-a64-mask.c's four `subw`/`subh` branches do:
2475/// `(0, 0)` the direct luma sample, `(1, 1)` the 2x2 box average,
2476/// `(1, 0)`/`(0, 1)` the `AOM_BLEND_AVG` pair average on the subsampled axis
2477/// alone (4:2:2).
2478#[allow(clippy::too_many_arguments)]
2479pub(crate) fn blend_masked_compound(
2480 pred0: &[i32],
2481 pred1: &[i32],
2482 mask: &[u8],
2483 mask_stride: usize,
2484 w: usize,
2485 h: usize,
2486 subw: usize,
2487 subh: usize,
2488 dst: &mut [u16],
2489 fctx: &crate::decode::FrameCtx,
2490) {
2491 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
2492 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
2493 assert_eq!(dst.len(), w * h, "the destination is the block");
2494 let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx)));
2495 for i in 0..h {
2496 for j in 0..w {
2497 let m: i32 = match (subw, subh) {
2498 (0, 0) => i32::from(mask[i * mask_stride + j]),
2499 (1, 1) => {
2500 let idx = (2 * i) * mask_stride + 2 * j;
2501 round2(
2502 i32::from(mask[idx])
2503 + i32::from(mask[idx + 1])
2504 + i32::from(mask[idx + mask_stride])
2505 + i32::from(mask[idx + mask_stride + 1]),
2506 2,
2507 )
2508 }
2509 // aom_blend_a64_mask_c's `subw == 1 && subh == 0` branch:
2510 // `AOM_BLEND_AVG(mask[2 * j], mask[2 * j + 1])` per row.
2511 (1, 0) => {
2512 let idx = i * mask_stride + 2 * j;
2513 (i32::from(mask[idx]) + i32::from(mask[idx + 1]) + 1) >> 1
2514 }
2515 // the `subw == 0 && subh == 1` branch: averaged down the
2516 // columns instead.
2517 (_sw, _sh) => {
2518 let idx = (2 * i) * mask_stride + j;
2519 (i32::from(mask[idx]) + i32::from(mask[idx + mask_stride]) + 1) >> 1
2520 }
2521 };
2522 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
2523 // `post_round` above: `INTER_POST_ROUND - round_delta` -- see
2524 // [`combine_compound`] (the same CONV_BUF gain absorption; the
2525 // `>> 6` above is bit-depth free because the CONV_BUF relative
2526 // weights are).
2527 dst[i * w + j] =
2528 round2(res, post_round).clamp(0, crate::decode::sample_max(fctx)) as u16;
2529 }
2530 }
2531}
2532
2533/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass
2534/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a
2535/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 ==
2536/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path
2537/// keeps over [`predict`]'s 11-bit round survives untouched) --
2538/// [`combine_compound`] then divides that back out exactly with an 8/8
2539/// simple-average weight split, so a compound block whose two references
2540/// (and MVs) happen to coincide reproduces the plain source sample, not an
2541/// off-by-one from double rounding.
2542#[test]
2543fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
2544 let fctx = &crate::decode::FrameCtx::new();
2545 let reference = vec![100u16; 16 * 16];
2546 let mut pred0 = vec![0i32; 16];
2547 predict_compound_intermediate(
2548 &reference,
2549 16,
2550 16,
2551 16,
2552 0,
2553 0,
2554 RefScale::UNSCALED,
2555 4,
2556 4,
2557 InterpFilterKind::Regular,
2558 InterpFilterKind::Regular,
2559 &mut pred0,
2560 fctx,
2561 );
2562 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
2563
2564 let pred1 = pred0.clone();
2565 let mut dst = vec![0u16; 16];
2566 combine_compound(&pred0, &pred1, 8, 8, &mut dst, fctx);
2567 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
2568}
2569
2570/// lane-av1c10: the whole compound pipeline -- two
2571/// [`predict_compound_intermediate`] taps through every combine this crate
2572/// ships ([`combine_compound`] dist-wtd and (8,8), [`diffwtd_mask`] both
2573/// inverses, [`blend_masked_compound`]) -- vs faithful transcriptions of the
2574/// libaom C at the same inputs, over all 16x16 phase pairs at 8 and 10 bits.
2575///
2576/// The C twins keep the CONV_BUF biased (`sum = dot + (1 << (bd + FILTER_BITS
2577/// - 1))` horizontally, `1 << offset_bits` vertically -- `convolve.c`
2578/// `av1_highbd_dist_wtd_convolve_2d_c`); this crate's intermediates are
2579/// unbiased, so each transcription adds the constant bias
2580/// `(1 << (bd + 4)) + (1 << (bd + 3))` (= `(1 << (offset_bits - round_1)) +
2581/// (1 << (offset_bits - round_1 - 1))`) before its combine and subtracts it
2582/// where libaom does. The diffwtd transcription is `diffwtd_mask_d16`
2583/// (reconinter.c:301): `round = 2*FILTER_BITS - round_0 - round_1 + (bd-8)`;
2584/// the blend is `aom_highbd_blend_a64_d16_mask_c` (blend_a64_mask.c):
2585/// `((m*c0 + (64-m)*c1) >> 6) - bias`, one `ROUND_POWER_OF_TWO` by
2586/// `round_bits`, `negative_to_zero`, clip. A 10-bit-only wrong constant in
2587/// any of the three -- the exact shape of the compound rounding defect the
2588/// cwarp-r1 charter named (and of the `(bd - 8)` diffwtd term that landed
2589/// without a 10-bit gate behind it) -- fails here per phase, no aomenc stream
2590/// needed.
2591#[cfg(test)]
2592mod libaom_transcription {
2593 use super::{
2594 InterpFilterKind, RefScale, blend_masked_compound, combine_compound, diffwtd_mask,
2595 predict_compound_intermediate,
2596 };
2597
2598 fn lcg(state: &mut u64) -> u32 {
2599 *state = state
2600 .wrapping_mul(6364136223846793005)
2601 .wrapping_add(1442695040888963407);
2602 (*state >> 33) as u32
2603 }
2604
2605 /// `ROUND_POWER_OF_TWO` on the C `int` domain: arithmetic shift of
2606 /// `value + half` (halves round toward +inf, negatives included).
2607 fn c_round(value: i32, shift: u32) -> i32 {
2608 (value + (1 << (shift - 1))) >> shift
2609 }
2610
2611 /// `av1_highbd_dist_wtd_convolve_2d_c` for both taps (biased domain) plus
2612 /// its `do_average` finish: dist-wtd two-weight split, or the plain
2613 /// `>> 1` average.
2614 #[allow(clippy::too_many_arguments)]
2615 fn libaom_compound_2d(
2616 reference: &[u16],
2617 stride: usize,
2618 (x0_q4, y0_q4): (i32, i32),
2619 (x1_q4, y1_q4): (i32, i32),
2620 w: usize,
2621 h: usize,
2622 hf: &[i32; 8],
2623 vf: &[i32; 8],
2624 fwd: i32,
2625 bck: i32,
2626 bd: u32,
2627 dist_wtd: bool,
2628 ) -> Vec<u16> {
2629 let rd = bd.saturating_sub(10);
2630 let round_0 = 3 + rd;
2631 let round_1 = 7u32;
2632 let offset_bits = (bd + 14 - round_0) as i32;
2633 let bias =
2634 (1 << (offset_bits - round_1 as i32)) + (1 << (offset_bits - round_1 as i32 - 1));
2635 let round_bits = 14 - round_0 - round_1;
2636 let mut out = vec![0u16; w * h];
2637 let mut conv = vec![0i32; w * h];
2638 for (tap, (x_q4, y_q4)) in [(0usize, (x0_q4, y0_q4)), (1usize, (x1_q4, y1_q4))] {
2639 // horizontal, biased
2640 let mut im = vec![0i32; (h + 7) * w];
2641 for y in 0..h + 7 {
2642 for x in 0..w {
2643 let mut sum = 1i32 << (bd + 7 - 1);
2644 for (k, &t) in hf.iter().enumerate() {
2645 let sx = (x_q4.div_euclid(16) + x as i32 + k as i32 - 3) as usize;
2646 let sy = (y_q4.div_euclid(16) + y as i32 - 3) as usize;
2647 sum += t * i32::from(reference[sy * stride + sx]);
2648 }
2649 im[y * w + x] = c_round(sum, round_0);
2650 }
2651 }
2652 for y in 0..h {
2653 for x in 0..w {
2654 let mut sum = 1i32 << offset_bits;
2655 for (k, &t) in vf.iter().enumerate() {
2656 sum += t * im[(y + k) * w + x];
2657 }
2658 let res = c_round(sum, round_1);
2659 if tap == 0 {
2660 conv[y * w + x] = res;
2661 } else {
2662 let mut tmp = if dist_wtd {
2663 (conv[y * w + x] * fwd + res * bck) >> 4 // DIST_PRECISION_BITS
2664 } else {
2665 (conv[y * w + x] + res) >> 1
2666 };
2667 tmp -= bias;
2668 let v = c_round(tmp, round_bits).max(0) as u32;
2669 out[y * w + x] = v.min((1u32 << bd) - 1) as u16;
2670 }
2671 }
2672 }
2673 }
2674 out
2675 }
2676
2677 /// `diffwtd_mask_d16` on the biased conv bufs.
2678 fn libaom_diffwtd(c0: &[i32], c1: &[i32], inv: bool, bd: u32, round_0: u32) -> Vec<u8> {
2679 let round = (14 - round_0 - 7 + (bd - 8)) as i32;
2680 c0.iter()
2681 .zip(c1)
2682 .map(|(&a, &b)| {
2683 let diff = c_round((a - b).abs(), round.unsigned_abs());
2684 let m = (38 + diff / 16).clamp(0, 64) as u8;
2685 if inv { 64 - m } else { m }
2686 })
2687 .collect()
2688 }
2689
2690 /// `aom_highbd_blend_a64_d16_mask_c`, subw == subh == 0, biased domain.
2691 fn libaom_blend(c0: &[i32], c1: &[i32], mask: &[u8], bd: u32, round_0: u32) -> Vec<u16> {
2692 let bias = (1i32 << (bd + 4)) + (1i32 << (bd + 3));
2693 let round_bits = 14 - round_0 - 7;
2694 c0.iter()
2695 .zip(c1)
2696 .zip(mask)
2697 .map(|((&a, &b), &m)| {
2698 let res = ((i32::from(m) * a + (64 - i32::from(m)) * b) >> 6) - bias;
2699 let v = c_round(res, round_bits).max(0) as u32;
2700 v.min((1u32 << bd) - 1) as u16
2701 })
2702 .collect()
2703 }
2704
2705 #[test]
2706 fn compound_pipeline_matches_the_libaom_transcription_at_8_and_10_bits() {
2707 let fctx = &crate::decode::FrameCtx::new();
2708 for bd in [8u32, 10u32] {
2709 crate::decode::set_bit_depth(bd as u8, fctx);
2710 let max = (1u16 << bd) - 1;
2711 let (wide, _narrow) = InterpFilterKind::Regular.tables();
2712 let mut state = 0x9e37_79b9_7f4a_7c15u64 ^ u64::from(bd);
2713 let reference: Vec<u16> = (0..48 * 48)
2714 .map(|_| (lcg(&mut state) % (u32::from(max) + 1)) as u16)
2715 .collect();
2716 let rd = bd.saturating_sub(10);
2717 let round_0 = 3 + rd;
2718 let bias = (1i32 << (bd + 4)) + (1i32 << (bd + 3));
2719 for &dist_wtd in &[false, true] {
2720 let (fwd, bck) = if dist_wtd { (9, 7) } else { (8, 8) };
2721 for xf in 0..16i32 {
2722 for yf in 0..16i32 {
2723 let (mv0, mv1) = ((16 * 8 + xf, 16 * 8 + yf), (16 * 10 + xf, 16 * 7 + yf));
2724 let (hf, vf) = (&wide[xf as usize], &wide[yf as usize]);
2725 let mut p0 = vec![0i32; 64];
2726 let mut p1 = vec![0i32; 64];
2727 for (mv, dst) in [(mv0, &mut p0), (mv1, &mut p1)] {
2728 predict_compound_intermediate(
2729 &reference,
2730 48,
2731 48,
2732 48,
2733 mv.0,
2734 mv.1,
2735 RefScale::UNSCALED,
2736 8,
2737 8,
2738 InterpFilterKind::Regular,
2739 InterpFilterKind::Regular,
2740 dst,
2741 fctx,
2742 );
2743 }
2744 let mut got = vec![0u16; 64];
2745 combine_compound(&p0, &p1, fwd, bck, &mut got, fctx);
2746 let want = libaom_compound_2d(
2747 &reference, 48, mv0, mv1, 8, 8, hf, vf, fwd, bck, bd, dist_wtd,
2748 );
2749 assert_eq!(
2750 got, want,
2751 "combine bd {bd} dist_wtd {dist_wtd} phase ({xf},{yf})"
2752 );
2753
2754 let c0: Vec<i32> = p0.iter().map(|&v| v + bias).collect();
2755 let c1: Vec<i32> = p1.iter().map(|&v| v + bias).collect();
2756 for inv in [false, true] {
2757 let mut mask = vec![0u8; 64];
2758 diffwtd_mask(&p0, &p1, inv, &mut mask, fctx);
2759 assert_eq!(
2760 mask,
2761 libaom_diffwtd(&c0, &c1, inv, bd, round_0),
2762 "diffwtd bd {bd} inv {inv} phase ({xf},{yf})"
2763 );
2764 }
2765 let mask: Vec<u8> = (0..64).map(|_| (lcg(&mut state) % 65) as u8).collect();
2766 let mut blended = vec![0u16; 64];
2767 // main shape: the branch's `subsampled: bool` split into
2768 // the plane's own `subw`/`subh` shifts; luma is (0, 0).
2769 blend_masked_compound(&p0, &p1, &mask, 8, 8, 8, 0, 0, &mut blended, fctx);
2770 assert_eq!(
2771 blended,
2772 libaom_blend(&c0, &c1, &mask, bd, round_0),
2773 "blend bd {bd} phase ({xf},{yf})"
2774 );
2775 }
2776 }
2777 }
2778 }
2779 }
2780}
2781
2782#[cfg(test)]
2783mod tests {
2784 use super::{
2785 InterpFilterKind, RefScale, predict, predict_scaled, predict_with_filter,
2786 predict_with_filters,
2787 };
2788
2789 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
2790 /// inter block at the frame's top-left corner (mv q4 = (row 7, col 15),
2791 /// bw=bh=16) predicted the wrong value because this decoder always used
2792 /// the REGULAR filter table -- aomdec's own `av1_convolve_2d_sr_c` trace
2793 /// showed this block actually used `EIGHTTAP_SMOOTH`
2794 /// (`0 0 2 34 62 28 2 0` at xfrac=15, not REGULAR's `0 0 -2 8 126 -6 2
2795 /// 0`). Window and expected output dumped straight from an
2796 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
2797 #[test]
2798 fn smooth_filter_matches_aomdec_chroma_inter_block() {
2799 let fctx = &crate::decode::FrameCtx::new();
2800 #[rustfmt::skip]
2801 let window: [[u8; 24]; 24] = [
2802 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
2803 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
2804 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
2805 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
2806 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
2807 [114,114,114,114,114,114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116,115,115,115],
2808 [114,114,114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,116,116,115,115,115,115],
2809 [113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,116,116,116,116,115,115,115,115],
2810 [113,113,113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,115,115,115,115,115,115],
2811 [112,112,112,112,112,112,112,112,112,113,113,113,113,114,114,114,114,114,115,115,115,115,115,115],
2812 [111,111,111,111,111,111,111,111,112,112,112,112,113,113,113,113,114,114,114,114,115,115,115,115],
2813 [110,110,110,110,110,110,110,110,111,111,111,111,112,112,112,113,113,113,113,113,114,114,114,115],
2814 [109,109,109,109,109,109,109,110,110,110,110,111,111,111,111,112,112,112,112,113,113,114,114,114],
2815 [108,108,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111,111,111,112,112,113,113,113],
2816 [108,108,108,108,108,108,108,108,108,108,109,109,109,110,110,110,110,110,111,111,112,112,112,112],
2817 [107,107,107,107,107,107,107,107,107,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111],
2818 [106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,110,110,110],
2819 [106,106,106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,109],
2820 [105,105,105,105,105,105,105,105,106,106,106,107,107,107,107,108,108,108,108,108,108,108,108,109],
2821 [104,104,104,104,104,104,104,104,104,105,105,106,106,106,107,107,107,107,107,107,107,108,108,108],
2822 [102,102,102,102,102,103,103,103,103,104,104,105,105,105,106,106,107,107,107,107,107,107,107,107],
2823 [101,101,101,101,101,101,101,102,102,103,103,104,104,104,105,105,106,106,106,106,106,107,107,107],
2824 [100,100,100,100,100,100,100,101,101,102,102,103,103,104,104,105,105,105,106,106,106,106,106,106],
2825 [99,99,99,99,99,99,100,100,100,101,101,102,103,103,104,104,105,105,105,105,105,105,105,106],
2826 ];
2827 // The dumped window spans real cols/rows -4..19; the block itself
2828 // starts at real (0, 0), so pad the reference plane so col/row 4 of
2829 // this buffer is real col/row 0, and hand `predict_with_filter` the
2830 // real (0, 0) coordinates -- clamping then reproduces the identical
2831 // extended border the dump already captured.
2832 let stride = 24;
2833 let mut reference = vec![0u16; stride * 24];
2834 for (r, row) in window.iter().enumerate() {
2835 for (c, &v) in row.iter().enumerate() {
2836 reference[r * stride + c] = u16::from(v);
2837 }
2838 }
2839 // predict()'s own edge clamp starts at true (0,0); shift so the
2840 // dumped window's row/col 4 lands there by biasing x_q4/y_q4's
2841 // whole-pel part by -4 and reading from a plane whose true origin
2842 // is the window's row/col 4 -- simplest is to pass true_width /
2843 // true_height covering the whole dumped window and offset the
2844 // whole-pel part of x_q4/y_q4 by +4 to land on real (0,0).
2845 let x_q4 = 4 * 16 + 15; // real block x0=0, xfrac=15
2846 let y_q4 = 4 * 16 + 7; // real block y0=0, yfrac=7
2847 let mut dst = vec![0u16; 16 * 16];
2848 predict_with_filter(
2849 &reference,
2850 stride,
2851 24,
2852 24,
2853 x_q4,
2854 y_q4,
2855 16,
2856 16,
2857 InterpFilterKind::Smooth,
2858 &mut dst,
2859 fctx,
2860 );
2861 #[rustfmt::skip]
2862 let expected_row0: [u16; 16] =
2863 [114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116];
2864 assert_eq!(
2865 &dst[0..16],
2866 &expected_row0,
2867 "row0 vs aomdec's real av1_convolve_2d_sr_c output"
2868 );
2869 #[rustfmt::skip]
2870 let expected_row15: [u16; 16] =
2871 [103,103,104,104,104,105,105,106,106,106,107,107,107,107,107,107];
2872 assert_eq!(
2873 &dst[15 * 16..15 * 16 + 16],
2874 &expected_row15,
2875 "row15 vs aomdec"
2876 );
2877 }
2878
2879 /// lane-gmaffine r5 root cause: a block 4 or fewer samples wide reads
2880 /// `Subpel_Filters[4]` -- the REGULAR narrow kernel -- for BOTH
2881 /// `EIGHTTAP` and `EIGHTTAP_SHARP` (spec 7.11.3.4's `filterIdx`, libaom
2882 /// `av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`,
2883 /// `filter.h:243`). We used the 8-tap sharp kernel there, which is
2884 /// invisible above 4 samples and so only ever bit the 4x4 chroma of an
2885 /// 8x8 (or smaller) luma leaf.
2886 #[test]
2887 fn a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness() {
2888 use crate::mc::{SUBPEL_FILTERS_4, SUBPEL_FILTERS_BILINEAR, SUBPEL_FILTERS_SMOOTH_4};
2889 for kind in [
2890 InterpFilterKind::Regular,
2891 InterpFilterKind::Smooth,
2892 InterpFilterKind::Sharp,
2893 InterpFilterKind::Bilinear,
2894 ] {
2895 let (wide, narrow) = kind.tables();
2896 let want: &[[i32; 8]; 16] = match kind {
2897 InterpFilterKind::Regular | InterpFilterKind::Sharp => &SUBPEL_FILTERS_4,
2898 InterpFilterKind::Smooth => &SUBPEL_FILTERS_SMOOTH_4,
2899 InterpFilterKind::Bilinear => &SUBPEL_FILTERS_BILINEAR,
2900 };
2901 assert_eq!(narrow, want, "{kind:?}: wrong narrow-block kernel");
2902 if kind == InterpFilterKind::Sharp {
2903 assert_ne!(wide, narrow, "sharp's wide kernel is not its narrow one");
2904 }
2905 }
2906 }
2907
2908 #[test]
2909 fn integer_mv_is_identity() {
2910 let fctx = &crate::decode::FrameCtx::new();
2911 let width = 12;
2912 let height = 12;
2913 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
2914 let mut dst = vec![0u16; 6 * 6];
2915 predict(
2916 &reference,
2917 width,
2918 width,
2919 height,
2920 3 * 16,
2921 4 * 16,
2922 6,
2923 6,
2924 &mut dst,
2925 fctx,
2926 );
2927 for row in 0..6 {
2928 for col in 0..6 {
2929 assert_eq!(
2930 dst[row * 6 + col],
2931 reference[(4 + row) * width + 3 + col],
2932 "integer MV must reproduce the reference block byte-for-byte"
2933 );
2934 }
2935 }
2936 }
2937
2938 #[test]
2939 fn half_pel_reproduces_the_ramp_midpoint() {
2940 let fctx = &crate::decode::FrameCtx::new();
2941 // Step 2 so every half-pel position lands on an exact integer.
2942 let width = 16;
2943 let height = 16;
2944 let reference: Vec<u16> = (0..width * height)
2945 .map(|i| (2 * (i % width)) as u16)
2946 .collect();
2947 let mut dst = vec![0u16; 4 * 4];
2948 // Half-pel in x only: fraction 8/16, integer part at column 5.
2949 predict(
2950 &reference,
2951 width,
2952 width,
2953 height,
2954 5 * 16 + 8,
2955 5 * 16,
2956 4,
2957 4,
2958 &mut dst,
2959 fctx,
2960 );
2961 for row in 0..4 {
2962 for col in 0..4 {
2963 let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1
2964 assert_eq!(
2965 dst[row * 4 + col] as i32,
2966 midpoint as i32,
2967 "half-pel MV over a linear ramp must land exactly on the midpoint"
2968 );
2969 }
2970 }
2971 }
2972
2973 #[test]
2974 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
2975 let fctx = &crate::decode::FrameCtx::new();
2976 let width = 20;
2977 let height = 20;
2978 let reference = vec![142u16; width * height];
2979 for yfrac in 0..16 {
2980 for xfrac in 0..16 {
2981 let mut dst = vec![0u16; 5 * 5];
2982 predict(
2983 &reference,
2984 width,
2985 width,
2986 height,
2987 5 * 16 + xfrac,
2988 5 * 16 + yfrac,
2989 5,
2990 5,
2991 &mut dst,
2992 fctx,
2993 );
2994 assert!(
2995 dst.iter().all(|&v| v == 142),
2996 "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}"
2997 );
2998 }
2999 }
3000 }
3001
3002 #[test]
3003 fn horizontal_and_vertical_only_filtering_differ() {
3004 let fctx = &crate::decode::FrameCtx::new();
3005 // A plane linear in both x and y with different, even coefficients so
3006 // each axis's half-pel interpolation lands on an exact integer: this
3007 // pins the actual value each pass produces, not just that the two
3008 // differ, so swapping which pass reads which axis is caught even if
3009 // it happened to produce two merely-different numbers.
3010 let width = 10;
3011 let height = 10;
3012 let reference: Vec<u16> = (0..height)
3013 .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u16))
3014 .collect();
3015
3016 let mut horiz = vec![0u16; 4 * 4];
3017 predict(
3018 &reference,
3019 width,
3020 width,
3021 height,
3022 3 * 16 + 8,
3023 3 * 16,
3024 4,
3025 4,
3026 &mut horiz,
3027 fctx,
3028 );
3029 let mut vert = vec![0u16; 4 * 4];
3030 predict(
3031 &reference,
3032 width,
3033 width,
3034 height,
3035 3 * 16,
3036 3 * 16 + 8,
3037 4,
3038 4,
3039 &mut vert,
3040 fctx,
3041 );
3042
3043 for row in 0..4 {
3044 for col in 0..4 {
3045 // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put.
3046 assert_eq!(
3047 horiz[row * 4 + col] as i32,
3048 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32),
3049 "horizontal-only MV must interpolate along x only"
3050 );
3051 // Vertical half-pel: y interpolates to y0+row+0.5, x stays put.
3052 assert_eq!(
3053 vert[row * 4 + col] as i32,
3054 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2,
3055 "vertical-only MV must interpolate along y only"
3056 );
3057 }
3058 }
3059 assert_ne!(
3060 horiz, vert,
3061 "horizontal-only and vertical-only sub-pel MVs must give different outputs"
3062 );
3063 }
3064
3065 #[test]
3066 fn mv_past_the_edge_clamps_instead_of_panicking() {
3067 let fctx = &crate::decode::FrameCtx::new();
3068 let width = 8;
3069 let height = 8;
3070 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
3071 let mut dst = vec![0u16; 4 * 4];
3072 // Whole-sample position far above and to the left of the plane, with
3073 // an odd fraction so both filter passes exercise the clamp.
3074 predict(
3075 &reference,
3076 width,
3077 width,
3078 height,
3079 -50 * 16 + 5,
3080 -50 * 16 + 5,
3081 4,
3082 4,
3083 &mut dst,
3084 fctx,
3085 );
3086 let expected = reference[0]; // the whole plane clamps to the top-left corner
3087 assert!(
3088 dst.iter().all(|&v| v == expected),
3089 "an MV past the top-left edge must clamp to the corner sample, got {dst:?}"
3090 );
3091
3092 let mut dst2 = vec![0u16; 4 * 4];
3093 predict(
3094 &reference,
3095 width,
3096 width,
3097 height,
3098 50 * 16 + 5,
3099 50 * 16 + 5,
3100 4,
3101 4,
3102 &mut dst2,
3103 fctx,
3104 );
3105 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
3106 assert!(
3107 dst2.iter().all(|&v| v == expected2),
3108 "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}"
3109 );
3110 }
3111
3112 #[test]
3113 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
3114 let fctx = &crate::decode::FrameCtx::new();
3115 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
3116 // must reduce predict_scaled's per-column scaled walk to the exact
3117 // same int_pel/filter_idx sequence predict_with_filters computes from
3118 // a fixed stride-1 walk -- every subpel fraction, every block width.
3119 let width = 24;
3120 let height = 24;
3121 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
3122 for block_w in [4usize, 8, 16] {
3123 for x_frac in 0..16i32 {
3124 let x_q4 = 3 * 16 + x_frac;
3125 let y_q4 = 2 * 16 + 5;
3126 let mut expected = vec![0u16; block_w * 8];
3127 predict_with_filters(
3128 &reference,
3129 width,
3130 width,
3131 height,
3132 x_q4,
3133 y_q4,
3134 block_w,
3135 8,
3136 InterpFilterKind::Regular,
3137 InterpFilterKind::Regular,
3138 &mut expected,
3139 fctx,
3140 );
3141 let mut got = vec![0u16; block_w * 8];
3142 predict_scaled(
3143 &reference,
3144 width,
3145 width,
3146 height,
3147 x_q4,
3148 y_q4,
3149 RefScale::UNSCALED,
3150 block_w,
3151 8,
3152 InterpFilterKind::Regular,
3153 InterpFilterKind::Regular,
3154 &mut got,
3155 fctx,
3156 );
3157 assert_eq!(
3158 got, expected,
3159 "block_w={block_w} x_frac={x_frac}: REF_NO_SCALE must reproduce predict_with_filters exactly"
3160 );
3161 }
3162 }
3163 }
3164
3165 /// lane-perf5: every explicit-SIMD kernel is checked against the scalar
3166 /// reference it replaces, over the whole domain a decode can hand it --
3167 /// all block widths (4..=128), all 16 sub-pel phases, all four filter
3168 /// kinds with both their wide and narrow (4-tap) tables, and 8/10/12-bit
3169 /// sample ranges. The dispatch itself is exercised through
3170 /// [`super::hpass_contig`] (whatever this CPU selected).
3171 #[test]
3172 fn simd_matches_scalar_horizontal_pass() {
3173 let mut state = 0x2545_f491_4f6c_dd1du64;
3174 let mut rng = move || {
3175 state ^= state << 13;
3176 state ^= state >> 7;
3177 state ^= state << 17;
3178 state
3179 };
3180 let kinds = [
3181 InterpFilterKind::Regular,
3182 InterpFilterKind::Smooth,
3183 InterpFilterKind::Sharp,
3184 InterpFilterKind::Bilinear,
3185 ];
3186 let mut checked = 0usize;
3187 for depth_max in [255u16, 1023, 4095] {
3188 for &kind in &kinds {
3189 let (wide, narrow) = kind.tables();
3190 for table in [wide, narrow] {
3191 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3192 #[allow(clippy::needless_range_loop)]
3193 for frac in 0..16usize {
3194 let taps = &table[frac];
3195 let t16 = [
3196 taps[0] as i16,
3197 taps[1] as i16,
3198 taps[2] as i16,
3199 taps[3] as i16,
3200 taps[4] as i16,
3201 taps[5] as i16,
3202 taps[6] as i16,
3203 taps[7] as i16,
3204 ];
3205 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
3206 let src: Vec<u16> = (0..w + 7)
3207 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
3208 .collect();
3209 let mut want = vec![0i16; w];
3210 super::hpass_contig_scalar(&src, &t16, &mut want, 3);
3211 let mut got = vec![0i16; w];
3212 super::hpass_contig(&src, &t16, &mut got, 3);
3213 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
3214 #[cfg(target_arch = "x86_64")]
3215 {
3216 if std::arch::is_x86_feature_detected!("sse4.1") {
3217 let mut sse = vec![0i16; w];
3218 super::simd::entry::hpass_sse2(
3219 &src,
3220 0,
3221 1,
3222 sse.len(),
3223 &t16,
3224 &mut sse,
3225 3,
3226 );
3227 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
3228 }
3229 if std::arch::is_x86_feature_detected!("avx2") {
3230 let mut avx = vec![0i16; w];
3231 super::simd::entry::hpass_avx2(
3232 &src,
3233 0,
3234 1,
3235 avx.len(),
3236 &t16,
3237 &mut avx,
3238 3,
3239 );
3240 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
3241 }
3242 }
3243 checked += 1;
3244 }
3245 }
3246 }
3247 }
3248 }
3249 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);
3250 }
3251
3252 /// lane-mc: the intermediate the horizontal pass writes is `i16`, which
3253 /// is a claim about the FILTER TABLES, not about a sample: every kernel's
3254 /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
3255 /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored
3256 /// value is that over `1 << round_0`. This enumerates all four
3257 /// filter kinds, both their wide and narrow tables and all 16 phases at
3258 /// the deepest sample this decoder accepts (12-bit now -- lane-av112bit
3259 /// lifted the refusal, with `round_0` at 5 there and 3 at 8/10-bit) and
3260 /// pins the result inside `i16` -- so the SIMD
3261 /// stores' `packs_epi32` never saturates on a motion-compensation path.
3262 #[test]
3263 fn horizontal_intermediate_fits_i16() {
3264 let kinds = [
3265 InterpFilterKind::Regular,
3266 InterpFilterKind::Smooth,
3267 InterpFilterKind::Sharp,
3268 InterpFilterKind::Bilinear,
3269 ];
3270 // (max sample, the frame's `round_0`) per supported bit depth.
3271 for (max_sample, round0) in [(255i32, 3u32), (1023, 3), (4095, 5)] {
3272 let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
3273 for &kind in &kinds {
3274 let (wide, narrow) = kind.tables();
3275 for table in [wide, narrow] {
3276 for taps in table {
3277 let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
3278 let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
3279 worst_hi = worst_hi.max(super::round2(max_sample * pos, round0));
3280 worst_lo = worst_lo.min(super::round2(max_sample * neg, round0));
3281 }
3282 }
3283 }
3284 assert!(
3285 worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
3286 "the {max_sample}-sample (round_0 {round0}) intermediate range \
3287 [{worst_lo}, {worst_hi}] must fit i16"
3288 );
3289 }
3290 }
3291
3292 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
3293 /// reference, over the same domain as
3294 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,
3295 /// both wide and narrow (4-tap) tables of all four filter kinds, and
3296 /// intermediates spanning the 8/10/12-bit ranges the horizontal pass can
3297 /// produce (a 12-bit sample times the filter gain, both signs).
3298 /// lane-mc2: with `xfrac == 0` the horizontal pass is the identity tap,
3299 /// so its intermediate is exactly `s << 4` and the vertical pass reads it
3300 /// with the taps scaled by 16. The fast path in
3301 /// [`predict_with_filters_kern`] skips the intermediate and reads the
3302 /// reference rows directly; this pins that it reproduces the two-pass
3303 /// form value-for-value at every vertical fraction and every block width
3304 /// (including the odd width the encoder's motion search prices).
3305 #[test]
3306 fn whole_pel_horizontal_matches_the_two_pass_form() {
3307 let fctx = &crate::decode::FrameCtx::new();
3308 let width = 160usize;
3309 let height = 48usize;
3310 let mut state = 0x2545_f491_4f6c_dd1du64;
3311 let mut rng = move || {
3312 state ^= state << 13;
3313 state ^= state >> 7;
3314 state ^= state << 17;
3315 state
3316 };
3317 let reference: Vec<u16> = (0..width * height).map(|_| (rng() % 256) as u16).collect();
3318 let mut checked = 0usize;
3319 for &kind in &[
3320 InterpFilterKind::Regular,
3321 InterpFilterKind::Smooth,
3322 InterpFilterKind::Sharp,
3323 ] {
3324 let (v_wide, v_narrow) = kind.tables();
3325 for (bw, bh) in [
3326 (4usize, 4usize),
3327 (5, 4),
3328 (8, 8),
3329 (16, 16),
3330 (12, 8),
3331 (32, 16),
3332 ] {
3333 for yfrac in 1..16i32 {
3334 let (x0, y0) = (7i32, 9i32);
3335 let taps = if bh <= 4 {
3336 &v_narrow[yfrac as usize]
3337 } else {
3338 &v_wide[yfrac as usize]
3339 };
3340 let mut want = vec![0u16; bw * bh];
3341 for row in 0..bh {
3342 for col in 0..bw {
3343 let mut sum = 0i32;
3344 for (t, &tap) in taps.iter().enumerate() {
3345 let y = y0 - 3 + row as i32 + t as i32;
3346 let s =
3347 i32::from(reference[y as usize * width + x0 as usize + col]);
3348 // The identity horizontal tap's output.
3349 sum += tap * (s << 4);
3350 }
3351 want[row * bw + col] =
3352 super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;
3353 }
3354 }
3355 let mut got = vec![0u16; bw * bh];
3356 super::predict_with_filters_kern(
3357 &reference,
3358 width,
3359 width,
3360 height,
3361 x0 * 16,
3362 y0 * 16 + yfrac,
3363 bw,
3364 bh,
3365 bw,
3366 bh,
3367 kind,
3368 kind,
3369 &mut got,
3370 fctx,
3371 );
3372 assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}");
3373 checked += 1;
3374 }
3375 }
3376 }
3377 assert_eq!(checked, 3 * 6 * 15);
3378 }
3379
3380 #[test]
3381 fn simd_matches_scalar_vertical_pass() {
3382 let mut state = 0x9e37_79b9_7f4a_7c15u64;
3383 let mut rng = move || {
3384 state ^= state << 13;
3385 state ^= state >> 7;
3386 state ^= state << 17;
3387 state
3388 };
3389 let kinds = [
3390 InterpFilterKind::Regular,
3391 InterpFilterKind::Smooth,
3392 InterpFilterKind::Sharp,
3393 InterpFilterKind::Bilinear,
3394 ];
3395 let mut checked = 0usize;
3396 // The horizontal pass's own range at 8- and 10-bit (12-bit is
3397 // refused in stream.rs), plus the saturating store's extreme.
3398 for span in [255i32 * 16, 1023 * 20, 32767] {
3399 for &kind in &kinds {
3400 let (wide, narrow) = kind.tables();
3401 for table in [wide, narrow] {
3402 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3403 #[allow(clippy::needless_range_loop)]
3404 for frac in 0..16usize {
3405 let taps = &table[frac];
3406 for w in [4usize, 5, 8, 12, 16, 20, 32, 64, 128] {
3407 let rows = 12usize;
3408 // lane-mc2: `st != w` is the fused whole-pel
3409 // horizontal path, which runs these kernels
3410 // straight over a reference plane's stride.
3411 for st in [w, w + 3] {
3412 let inter: Vec<i16> = (0..rows * st)
3413 .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
3414 .collect();
3415 for row in [0usize, 1, 4] {
3416 let mut want = vec![0i32; w];
3417 super::vpass_row_scalar(
3418 &inter[row * st..],
3419 w,
3420 st,
3421 0,
3422 taps,
3423 &mut want,
3424 );
3425 let mut got = vec![0i32; w];
3426 super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);
3427 assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");
3428 #[cfg(target_arch = "x86_64")]
3429 {
3430 if std::arch::is_x86_feature_detected!("sse4.1") {
3431 let mut sse = vec![0i32; w];
3432 super::simd::entry::vpass_sse41(
3433 &inter[row * st..],
3434 w,
3435 st,
3436 1,
3437 taps,
3438 &mut sse,
3439 );
3440 assert_eq!(
3441 sse, want,
3442 "sse4.1 w={w} frac={frac} row={row}"
3443 );
3444 }
3445 if std::arch::is_x86_feature_detected!("avx2") {
3446 let mut avx = vec![0i32; w];
3447 super::simd::entry::vpass_avx2(
3448 &inter[row * st..],
3449 w,
3450 st,
3451 1,
3452 taps,
3453 &mut avx,
3454 );
3455 assert_eq!(
3456 avx, want,
3457 "avx2 w={w} frac={frac} row={row}"
3458 );
3459 }
3460 }
3461 // lane-mc: the rounding-fused form, over both
3462 // sample maxima this decoder accepts -- its
3463 // `packus`/`min_epu16` pair must reproduce
3464 // `round2(_, InterRound1).clamp(0, max)`.
3465 for max in [255i32, 1023] {
3466 let mut want_u16 = vec![0u16; w];
3467 super::vpass_row_u16_scalar(
3468 &inter,
3469 w,
3470 st,
3471 row,
3472 taps,
3473 max,
3474 &mut want_u16,
3475 11,
3476 );
3477 for (d, &a) in want_u16.iter().zip(want.iter()) {
3478 assert_eq!(
3479 i32::from(*d),
3480 super::round2(a, super::INTER_ROUND_1)
3481 .clamp(0, max),
3482 "the fused reference is the two-step one"
3483 );
3484 }
3485 let mut got_u16 = vec![0u16; w];
3486 super::vpass_row_u16(
3487 &inter[row * st..],
3488 w,
3489 st,
3490 1,
3491 taps,
3492 max,
3493 &mut got_u16,
3494 11,
3495 );
3496 assert_eq!(
3497 got_u16, want_u16,
3498 "fused w={w} frac={frac} row={row} max={max}"
3499 );
3500 #[cfg(target_arch = "x86_64")]
3501 {
3502 if std::arch::is_x86_feature_detected!("sse4.1") {
3503 let mut sse = vec![0u16; w];
3504 super::simd::entry::vpass_row_u16_sse41(
3505 &inter[row * st..],
3506 w,
3507 st,
3508 1,
3509 taps,
3510 max,
3511 &mut sse,
3512 11,
3513 );
3514 assert_eq!(
3515 sse, want_u16,
3516 "fused sse4.1 w={w} max={max}"
3517 );
3518 }
3519 if std::arch::is_x86_feature_detected!("avx2") {
3520 let mut avx = vec![0u16; w];
3521 super::simd::entry::vpass_row_u16_avx2(
3522 &inter[row * st..],
3523 w,
3524 st,
3525 1,
3526 taps,
3527 max,
3528 &mut avx,
3529 11,
3530 );
3531 assert_eq!(
3532 avx, want_u16,
3533 "fused avx2 w={w} max={max}"
3534 );
3535 }
3536 }
3537 }
3538 checked += 1;
3539 }
3540 }
3541 }
3542 }
3543 }
3544 }
3545 }
3546 assert_eq!(checked, 3 * 4 * 2 * 16 * 9 * 3 * 2);
3547 }
3548}
3549
3550#[cfg(test)]
3551mod scaled_spec_tests {
3552 //! Pins [`predict_scaled`] and [`predict_compound_intermediate`] at a
3553 //! reference scaled on either axis against a literal transcription of spec
3554 //! 7.11.3.3 (motion vector scaling) and 7.11.3.4 (block inter prediction).
3555 use super::*;
3556
3557 fn round2signed(x: i64, n: u32) -> i64 {
3558 if x < 0 {
3559 -((-x + (1 << (n - 1))) >> n)
3560 } else {
3561 (x + (1 << (n - 1))) >> n
3562 }
3563 }
3564
3565 /// The spec's own steps, written out as the spec states them. `x_q4` is
3566 /// the block's sample position in 1/16 pel including the motion vector
3567 /// (`(x << 4) + mv`), so the spec's `origX` is `x_q4 + halfSample`.
3568 #[allow(clippy::too_many_arguments)]
3569 fn spec_block(
3570 refp: &[u16],
3571 (ref_w, ref_h): (usize, usize),
3572 (cur_w, cur_h): (usize, usize),
3573 (x_q4, y_q4): (i64, i64),
3574 (w, h): (usize, usize),
3575 (hk, vk): (InterpFilterKind, InterpFilterKind),
3576 (kern_w, kern_h): (usize, usize),
3577 bit_depth: u32,
3578 compound: bool,
3579 ) -> Vec<i64> {
3580 // 7.11.3.3
3581 let x_scale = ((ref_w as i64) << 14) + cur_w as i64 / 2;
3582 let x_scale = x_scale / cur_w as i64;
3583 let y_scale = (((ref_h as i64) << 14) + cur_h as i64 / 2) / cur_h as i64;
3584 let start_x = round2signed((x_q4 + 8) * x_scale - (8 << 14), 8) + 32;
3585 let start_y = round2signed((y_q4 + 8) * y_scale - (8 << 14), 8) + 32;
3586 let x_step = round2signed(x_scale, 4);
3587 let y_step = round2signed(y_scale, 4);
3588 // 7.11.3.4
3589 let (round0, round1) = if compound {
3590 (if bit_depth == 12 { 5 } else { 3 }, 7)
3591 } else if bit_depth == 12 {
3592 (5, 9)
3593 } else {
3594 (3, 11)
3595 };
3596 let last_x = ref_w as i64 - 1;
3597 let last_y = ref_h as i64 - 1;
3598 let inter_h = ((((h as i64 - 1) * y_step + 1023) >> 10) + 8) as usize;
3599 let (hw, hn) = hk.tables();
3600 let (vw, vn) = vk.tables();
3601 let hf = if kern_w <= 4 { hn } else { hw };
3602 let vf = if kern_h <= 4 { vn } else { vw };
3603 let mut inter = vec![0i64; inter_h * w];
3604 for r in 0..inter_h {
3605 for c in 0..w {
3606 let p = start_x + x_step * c as i64;
3607 let mut s = 0i64;
3608 let taps = &hf[((p >> 6) & 15) as usize];
3609 for (t, &tap) in taps.iter().enumerate() {
3610 let ry = ((start_y >> 10) + r as i64 - 3).clamp(0, last_y) as usize;
3611 let rx = ((p >> 10) + t as i64 - 3).clamp(0, last_x) as usize;
3612 s += i64::from(tap) * i64::from(refp[ry * ref_w + rx]);
3613 }
3614 // Round2 (spec 4.7): an arithmetic shift, not the signed form.
3615 inter[r * w + c] = (s + (1 << (round0 - 1))) >> round0;
3616 }
3617 }
3618 let mut out = vec![0i64; w * h];
3619 for r in 0..h {
3620 for c in 0..w {
3621 let p = (start_y & 1023) + y_step * r as i64;
3622 let mut s = 0i64;
3623 let taps = &vf[((p >> 6) & 15) as usize];
3624 for (t, &tap) in taps.iter().enumerate() {
3625 let row = ((p >> 10) as usize) + t;
3626 s += i64::from(tap) * inter[row * w + c];
3627 }
3628 out[r * w + c] = (s + (1 << (round1 - 1))) >> round1;
3629 }
3630 }
3631 out
3632 }
3633
3634 fn xorshift(state: &mut u64) -> u64 {
3635 *state ^= *state << 13;
3636 *state ^= *state >> 7;
3637 *state ^= *state << 17;
3638 *state
3639 }
3640
3641 /// Random reference sizes and current sizes inside the spec limits, both
3642 /// axes scaled, one axis scaled, 8 and 10 bit, all three filter kinds.
3643 #[test]
3644 fn scaled_prediction_matches_the_spec_transcription() {
3645 let mut seed = 0x5eed_u64;
3646 let kinds = [
3647 InterpFilterKind::Regular,
3648 InterpFilterKind::Smooth,
3649 InterpFilterKind::Sharp,
3650 ];
3651 let mut checked = 0usize;
3652 for &bit_depth in &[8u32, 10] {
3653 for _ in 0..400 {
3654 let cur_w = 16 + (xorshift(&mut seed) % 48) as usize;
3655 let cur_h = 16 + (xorshift(&mut seed) % 48) as usize;
3656 // Reference between cur/2 and 2*cur (the spec's 2x down / 16x up
3657 // limits, per axis, seen from the reference side).
3658 let (lo_w, lo_h) = (cur_w.div_ceil(2), cur_h.div_ceil(2));
3659 let ref_w = lo_w + (xorshift(&mut seed) % (2 * cur_w - lo_w + 1) as u64) as usize;
3660 let ref_h = lo_h + (xorshift(&mut seed) % (2 * cur_h - lo_h + 1) as u64) as usize;
3661 let ref_w = if xorshift(&mut seed).is_multiple_of(4) {
3662 cur_w
3663 } else {
3664 ref_w
3665 };
3666 let ref_h = if xorshift(&mut seed).is_multiple_of(4) {
3667 cur_h
3668 } else {
3669 ref_h
3670 };
3671 let scale = RefScale::new(ref_w, ref_h, cur_w, cur_h);
3672 let refp: Vec<u16> = (0..ref_w * ref_h)
3673 .map(|_| (xorshift(&mut seed) % (1 << bit_depth)) as u16)
3674 .collect();
3675 let (w, h) = [(4usize, 4usize), (8, 8), (16, 8), (8, 16)]
3676 [(xorshift(&mut seed) % 4) as usize];
3677 let x_q4 = (xorshift(&mut seed) % (cur_w as u64 * 16)) as i64 - 8 * 16;
3678 let y_q4 = (xorshift(&mut seed) % (cur_h as u64 * 16)) as i64 - 8 * 16;
3679 let hk = kinds[(xorshift(&mut seed) % 3) as usize];
3680 let vk = kinds[(xorshift(&mut seed) % 3) as usize];
3681 let fctx = crate::decode::FrameCtx::new();
3682 fctx.bit_depth.set(bit_depth as u8);
3683 let max = (1i64 << bit_depth) - 1;
3684
3685 let mut dst = vec![0u16; w * h];
3686 predict_scaled(
3687 &refp,
3688 ref_w,
3689 ref_w,
3690 ref_h,
3691 x_q4 as i32,
3692 y_q4 as i32,
3693 scale,
3694 w,
3695 h,
3696 hk,
3697 vk,
3698 &mut dst,
3699 &fctx,
3700 );
3701 let want = spec_block(
3702 &refp,
3703 (ref_w, ref_h),
3704 (cur_w, cur_h),
3705 (x_q4, y_q4),
3706 (w, h),
3707 (hk, vk),
3708 (w, h),
3709 bit_depth,
3710 false,
3711 );
3712 for (i, (&got, &exp)) in dst.iter().zip(want.iter()).enumerate() {
3713 assert_eq!(
3714 i64::from(got),
3715 exp.clamp(0, max),
3716 "bd={bit_depth} ref={ref_w}x{ref_h} cur={cur_w}x{cur_h} q4=({x_q4},{y_q4}) {w}x{h} sample {i}"
3717 );
3718 }
3719
3720 let mut comp = vec![0i32; w * h];
3721 predict_compound_intermediate(
3722 &refp,
3723 ref_w,
3724 ref_w,
3725 ref_h,
3726 x_q4 as i32,
3727 y_q4 as i32,
3728 scale,
3729 w,
3730 h,
3731 hk,
3732 vk,
3733 &mut comp,
3734 &fctx,
3735 );
3736 let want = spec_block(
3737 &refp,
3738 (ref_w, ref_h),
3739 (cur_w, cur_h),
3740 (x_q4, y_q4),
3741 (w, h),
3742 (hk, vk),
3743 (w, h),
3744 bit_depth,
3745 true,
3746 );
3747 for (i, (&got, &exp)) in comp.iter().zip(want.iter()).enumerate() {
3748 assert_eq!(i64::from(got), exp, "compound bd={bit_depth} sample {i}");
3749 }
3750 checked += 1;
3751 }
3752 }
3753 assert_eq!(checked, 800);
3754 }
3755}