forge
Explore
Log in

Don't you dare go Hollow

lane-av112bit: lift the 12-bit gate to the witnessed set

Browse files at this commit

053138781e702c75b43fc3d7bef38b24d5751e3cAhmet Kaan GümüşParent: e32630c
The blanket bit-depth-12 refusal (hdr report section 4.2) becomes four
named refusals, each pinned by a real aomenc --bit-depth=12 stream:
warp, compound inter blocks, film grain, and screen content tools
(palette/intrabc). Everything else 12-bit is lifted behind two
byte-exact-vs-ffmpeg witnesses: a key frame and a key+inter sequence
with sub-pixel motion, CDEF and loop restoration ON (cdef_idx and
Wiener/SGR unit counters hard-asserted; a new MC_SUBPEL_HITS counter
proves the frame's own round_0/round_1 ran).

The rounding rule is libaom convolve.h:81..86 verbatim: round_0 +=
bd - 10, non-compound round_1 -= bd - 10 (mc.rs round_pair, threaded
through scalar and SIMD passes, the identity fast paths, the scaled
walk, and the compound combines' post-rounds; the Wiener pair likewise).
Wiener's intermediate clamp keeps the corpus-proven constant structure
- the exact per-sample C transform moved the 10-bit 128-sb film gate
and is recorded as the lane's open half in lanes/av112bit.report.md.

8/10-bit regression: the three 10-bit film fixture gates, the 10-bit
key/inter/grain gates and 8-bit spot arms all green; refusal_inventory
and gate_coverage updated and green. Fixtures av112bit-{key,inter}.obu
committed with sha256 provenance in the report.
crates/ec-av1/fixtures/av112bit-inter.obuadded+0 -0

Binary file changed

crates/ec-av1/fixtures/av112bit-key.obuadded+0 -0

Binary file changed

crates/ec-av1/src/decode.rsmodified+59 -24
@@ -28,6 +28,14 @@ use ec_av1_syntax::{
2828 };
2929 use ec_core::{Error, Result};
3030
31+// lane-av112bit: the 12-bit warp/compound refusals below are inline literals
32+// (refusal_inventory.rs extracts them from the decode source); each names the
33+// witness gap that keeps the path refused -- warp's reduce bits inherit the
34+// 12-bit `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86), and
35+// the inter witness is a single-reference stream, so compound of every kind
36+// is unwitnessed. All sites are PARSE-time: a refused stream never builds a
37+// warp predictor or blends a compound pair.
38+
3139 /// Per-frame decode state, one instance per decoded stream (lane-thread1).
3240 ///
3341 /// Every field here used to be a `thread_local!` static, which made a decode a
@@ -28993,6 +29001,13 @@ fn decode_inter_block(
2899329001 } else {
2899429002 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
2899529003 };
29004+ // lane-av112bit: refused by name -- see `COMPOUND_12BIT_REFUSAL`.
29005+ if bit_depth(fctx) == 12 {
29006+ return Err(Error::unsupported(
29007+ "AV1 tile decode",
29008+ "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)",
29009+ ));
29010+ }
2899629011 let (mv0, mv1) = assign_compound_mv(
2899729012 dec,
2899829013 cdfs,
@@ -29083,6 +29098,13 @@ fn decode_inter_block(
2908329098 let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1));
2908429099 if warp0.is_some() || warp1.is_some() {
2908529100 hit!(COMPOUND_WARP_HITS);
29101+ // lane-av112bit: refused by name -- see `WARP_12BIT_REFUSAL`.
29102+ if bit_depth(fctx) == 12 {
29103+ return Err(Error::unsupported(
29104+ "AV1 tile decode",
29105+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
29106+ ));
29107+ }
2908629108 }
2908729109 // spec `get_ref_filter_type`: matches when EITHER of the
2908829110 // neighbour's two references equals this block's own ref0 --
@@ -29545,8 +29567,7 @@ fn decode_inter_block(
2954529567 write_h,
2954629568 h_filter,
2954729569 v_filter,
29548- &mut inter0_y,
29549- );
29570+ &mut inter0_y, fctx,);
2955029571 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
2955129572 // translational tap (libaom `av1_warp_plane` with
2955229573 // `conv_params->is_compound`); the blend below is unchanged.
@@ -29572,8 +29593,7 @@ fn decode_inter_block(
2957229593 write_h,
2957329594 h_filter,
2957429595 v_filter,
29575- &mut inter1_y,
29576- );
29596+ &mut inter1_y, fctx,);
2957729597 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
2957829598 // translational tap (libaom `av1_warp_plane` with
2957929599 // `conv_params->is_compound`); the blend below is unchanged.
@@ -29621,8 +29641,7 @@ fn decode_inter_block(
2962129641 write_chroma_h,
2962229642 h_filter,
2962329643 v_filter,
29624- &mut inter0_u,
29625- );
29644+ &mut inter0_u, fctx,);
2962629645 // `av1_init_warp_params` bails when the PLANE's block is
2962729646 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
2962829647 // block of an 8x8 luma block stays translational.
@@ -29650,8 +29669,7 @@ fn decode_inter_block(
2965029669 write_chroma_h,
2965129670 h_filter,
2965229671 v_filter,
29653- &mut inter1_u,
29654- );
29672+ &mut inter1_u, fctx,);
2965529673 // `av1_init_warp_params` bails when the PLANE's block is
2965629674 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
2965729675 // block of an 8x8 luma block stays translational.
@@ -29695,8 +29713,7 @@ fn decode_inter_block(
2969529713 write_chroma_h,
2969629714 h_filter,
2969729715 v_filter,
29698- &mut inter0_v,
29699- );
29716+ &mut inter0_v, fctx,);
2970029717 // `av1_init_warp_params` bails when the PLANE's block is
2970129718 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
2970229719 // block of an 8x8 luma block stays translational.
@@ -29724,8 +29741,7 @@ fn decode_inter_block(
2972429741 write_chroma_h,
2972529742 h_filter,
2972629743 v_filter,
29727- &mut inter1_v,
29728- );
29744+ &mut inter1_v, fctx,);
2972929745 // `av1_init_warp_params` bails when the PLANE's block is
2973029746 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
2973129747 // block of an 8x8 luma block stays translational.
@@ -30665,6 +30681,15 @@ fn decode_inter_block(
3066530681 hit!(AFFINE_GM_HITS);
3066630682 }
3066730683 }
30684+ // lane-av112bit: a local `WARPED_CAUSAL` projection (set above) or
30685+ // a global warp model both land here with `warp_params` set --
30686+ // refused by name at 12 bits (see `WARP_12BIT_REFUSAL`).
30687+ if bit_depth(fctx) == 12 && warp_params.is_some() {
30688+ return Err(Error::unsupported(
30689+ "AV1 tile decode",
30690+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
30691+ ));
30692+ }
3066830693 if crate::envflags::env_flag!("EC_AV1_TELL") {
3066930694 eprintln!(
3067030695 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
@@ -34541,6 +34566,13 @@ fn decode_inter_block8(
3454134566 comp_stack.ref_mv_ctx,
3454234567 )
3454334568 };
34569+ // lane-av112bit: refused by name -- see `COMPOUND_12BIT_REFUSAL`.
34570+ if bit_depth(fctx) == 12 {
34571+ return Err(Error::unsupported(
34572+ "AV1 tile decode",
34573+ "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)",
34574+ ));
34575+ }
3454434576 if crate::envflags::env_flag!("EC_TRACE_MODE") {
3454534577 eprintln!(
3454634578 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
@@ -34835,8 +34867,7 @@ fn decode_inter_block8(
3483534867 SIDE,
3483634868 h_filter,
3483734869 v_filter,
34838- &mut inter0_y,
34839- );
34870+ &mut inter0_y, fctx,);
3484034871 if let Some(wp) = &warp0_c {
3484134872 crate::warp::warp_affine_compound(
3484234873 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
@@ -34857,8 +34888,7 @@ fn decode_inter_block8(
3485734888 SIDE,
3485834889 h_filter,
3485934890 v_filter,
34860- &mut inter1_y,
34861- );
34891+ &mut inter1_y, fctx,);
3486234892 if let Some(wp) = &warp1_c {
3486334893 crate::warp::warp_affine_compound(
3486434894 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
@@ -34897,8 +34927,7 @@ fn decode_inter_block8(
3489734927 CHROMA_SIDE,
3489834928 h_filter,
3489934929 v_filter,
34900- &mut inter0_u,
34901- );
34930+ &mut inter0_u, fctx,);
3490234931 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
3490334932 mc::predict_compound_intermediate(
3490434933 &pu1.data,
@@ -34912,8 +34941,7 @@ fn decode_inter_block8(
3491234941 CHROMA_SIDE,
3491334942 h_filter,
3491434943 v_filter,
34915- &mut inter1_u,
34916- );
34944+ &mut inter1_u, fctx,);
3491734945 let mut pred_u = refill(std::mem::take(&mut out[1]), CHROMA_SIDE * CHROMA_SIDE);
3491834946 if let Some(mask_y) = mask_y {
3491934947 mc::blend_masked_compound(
@@ -34943,8 +34971,7 @@ fn decode_inter_block8(
3494334971 CHROMA_SIDE,
3494434972 h_filter,
3494534973 v_filter,
34946- &mut inter0_v,
34947- );
34974+ &mut inter0_v, fctx,);
3494834975 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
3494934976 mc::predict_compound_intermediate(
3495034977 &pv1.data,
@@ -34958,8 +34985,7 @@ fn decode_inter_block8(
3495834985 CHROMA_SIDE,
3495934986 h_filter,
3496034987 v_filter,
34961- &mut inter1_v,
34962- );
34988+ &mut inter1_v, fctx,);
3496334989 let mut pred_v = refill(std::mem::take(&mut out[2]), CHROMA_SIDE * CHROMA_SIDE);
3496434990 if let Some(mask_y) = mask_y {
3496534991 mc::blend_masked_compound(
@@ -35513,6 +35539,15 @@ fn decode_inter_block8(
3551335539 hit!(AFFINE_GM_HITS);
3551435540 }
3551535541 }
35542+ // lane-av112bit: same 12-bit refusal as the 16x16+ leaf -- a local
35543+ // `WARPED_CAUSAL` projection or a global model both leave
35544+ // `warp_params` set here (see `WARP_12BIT_REFUSAL`).
35545+ if bit_depth(fctx) == 12 && warp_params.is_some() {
35546+ return Err(Error::unsupported(
35547+ "AV1 tile decode",
35548+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
35549+ ));
35550+ }
3551635551 if crate::envflags::env_flag!("EC_TRACE_MODE") {
3551735552 eprintln!(
3551835553 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
crates/ec-av1/src/encode.rsmodified+2 -2
@@ -9745,7 +9745,7 @@ fn mc_trial_compound_typed(
97459745 side,
97469746 fctx.interp_filter.get(),
97479747 fctx.interp_filter.get(),
9748- dst,
9748+ dst, fctx,
97499749 );
97509750 }
97519751 let mut blended16 = [0u16; BLOCK * BLOCK];
@@ -9838,7 +9838,7 @@ fn predict_compound_u8(
98389838 side,
98399839 fctx.interp_filter.get(),
98409840 fctx.interp_filter.get(),
9841- dst,
9841+ dst, fctx,
98429842 );
98439843 }
98449844 let mut blended = vec![0u16; side * side];
crates/ec-av1/src/mc.rsmodified+762 -262
@@ -23,24 +23,46 @@ fn round2(value: i32, shift: u32) -> i32 {
2323 /// through `packs_epi32`, which saturates -- so the scalar arms must too, or
2424 /// the two would disagree on an out-of-range sum. Motion compensation never
2525 /// produces one (`horizontal_intermediate_fits_i16` proves the bound from the
26-/// tap sums at 8/10-bit; 12-bit is refused in stream.rs), and restoration's
27-/// wiener pass clamps its own output into i16 immediately after.
26+/// tap sums at every supported bit depth), and restoration's wiener pass
27+/// clamps its own output into i16 immediately after.
2828 fn sat16(value: i32) -> i16 {
2929 value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
3030 }
3131
32-/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the
33-/// horizontal pass's sum is brought down by before it is stored as the
34-/// intermediate.
32+/// `InterRound0` (spec 7.11.3.2), non-compound: the shift the horizontal
33+/// pass's sum is brought down by before it is stored as the intermediate.
34+/// This is the 8/10-bit base; at 12-bit [`round_delta`] raises it (libaom
35+/// `convolve.h`'s `get_conv_params_no_round`).
3536 const INTER_ROUND_0: u32 = 3;
36-/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical
37-/// pass's sum is brought down by to land back on an 8-bit sample. Composed
38-/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass
37+/// `InterRound1` (spec 7.11.3.2), non-compound: the shift the vertical
38+/// pass's sum is brought down by to land back on a sample. Composed
39+/// with [`INTER_ROUND_0`] the two shifts are the filter's own gain (each pass
3940 /// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)
4041 /// -- so an identity or DC input comes back exactly, by construction of the
41-/// table rather than by a fitted constant.
42+/// table rather than by a fitted constant. 8/10-bit base; see [`round_delta`].
4243 const INTER_ROUND_1: u32 = 11;
4344
45+/// The bit-depth headroom libaom adds when the `CONV_BUF` intermediate would
46+/// no longer fit 16 bits (`convolve.h:81..86`'s
47+/// `intbufrange = bd + FILTER_BITS - round_0 + 2 > 16`): zero at 8/10-bit;
48+/// `bd - 10` at 12-bit. There the horizontal `round_0` rises by the delta
49+/// and the non-compound vertical `round_1` falls by it again, so the
50+/// filter's own gain `2*FILTER_BITS - round_0 - round_1` is untouched --
51+/// only the intermediate quantisation moves. Warp's
52+/// `reduce_bits_horiz == conv_params->round_0` (`warped_motion.c:295`) and
53+/// the Wiener pair (`get_conv_params_wiener`) inherit the same delta.
54+pub(crate) fn round_delta(bd: u32) -> u32 {
55+ bd.saturating_sub(10)
56+}
57+
58+/// A frame's MC rounding pair: horizontal `round_0` and non-compound
59+/// vertical `round_1` (the compound vertical round is `INTER_ROUND_1_COMPOUND`
60+/// at every bit depth).
61+pub(crate) fn round_pair(bd: u32) -> (u32, u32) {
62+ let delta = round_delta(bd);
63+ (INTER_ROUND_0 + delta, INTER_ROUND_1 - delta)
64+}
65+
4466 /// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel
4567 /// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer
4668 /// sample (fraction 0 is the identity tap `[.., 128, ..]`).
@@ -296,9 +318,9 @@ pub(crate) fn simd_level() -> SimdLevel {
296318 /// the same `Round2(sum, InterRound0)`.
297319 #[allow(unsafe_code)]
298320 #[inline]
299-pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
321+pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16], round0: u32) {
300322 let n = out.len();
301- hpass_rows(src, 0, 1, n, t16, out);
323+ hpass_rows(src, 0, 1, n, t16, out, round0);
302324 }
303325
304326 /// lane-mc2: `rows` rows of [`hpass_contig`], `src_stride` apart in `src` and
@@ -313,6 +335,7 @@ pub(crate) fn hpass_rows(
313335 block_w: usize,
314336 t16: &[i16; 8],
315337 out: &mut [i16],
338+ round0: u32,
316339 ) {
317340 #[cfg(target_arch = "x86_64")]
318341 {
@@ -320,13 +343,13 @@ pub(crate) fn hpass_rows(
320343 SimdLevel::Avx2 => {
321344 // SAFETY: the AVX2 arm is reached only when the CPU reports
322345 // avx2; each row reads at most `block_w + 7` samples.
323- unsafe { simd::hpass_avx2(src, src_stride, rows, block_w, t16, out) };
346+ unsafe { simd::hpass_avx2(src, src_stride, rows, block_w, t16, out, round0) };
324347 return;
325348 }
326349 SimdLevel::Sse41 => {
327350 // SAFETY: as above; the kernel needs only SSE2, which every
328351 // x86_64 CPU has.
329- unsafe { simd::hpass_sse2(src, src_stride, rows, block_w, t16, out) };
352+ unsafe { simd::hpass_sse2(src, src_stride, rows, block_w, t16, out, round0) };
330353 return;
331354 }
332355 SimdLevel::Scalar => {}
@@ -337,12 +360,13 @@ pub(crate) fn hpass_rows(
337360 &src[r * src_stride..],
338361 t16,
339362 &mut out[r * block_w..(r + 1) * block_w],
363+ round0,
340364 );
341365 }
342366 }
343367
344368 /// The scalar reference for [`hpass_contig`] (lane-perf2's loop).
345-fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
369+fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16], round0: u32) {
346370 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit
347371 // depth), so the products are exactly the i32 ones but the widening
348372 // multiply is one instruction per pair.
@@ -351,7 +375,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
351375 for t in 0..8 {
352376 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
353377 }
354- *o = sat16(round2(sum, INTER_ROUND_0));
378+ *o = sat16(round2(sum, round0));
355379 }
356380 }
357381
@@ -363,7 +387,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
363387 #[cfg(target_arch = "x86_64")]
364388 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
365389 mod simd {
366- use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1};
390+ use super::{round2, sat16};
367391 use std::arch::x86_64::*;
368392
369393 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
@@ -372,15 +396,26 @@ mod simd {
372396 #[inline]
373397 fn taps16(taps: &[i32; 8]) -> [i16; 8] {
374398 [
375- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
376- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
399+ taps[0] as i16,
400+ taps[1] as i16,
401+ taps[2] as i16,
402+ taps[3] as i16,
403+ taps[4] as i16,
404+ taps[5] as i16,
405+ taps[6] as i16,
406+ taps[7] as i16,
377407 ]
378408 }
379409
380410 #[inline]
381411 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
382412 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);
383- [pack(t[0], t[1]), pack(t[2], t[3]), pack(t[4], t[5]), pack(t[6], t[7])]
413+ [
414+ pack(t[0], t[1]),
415+ pack(t[2], t[3]),
416+ pack(t[4], t[5]),
417+ pack(t[6], t[7]),
418+ ]
384419 }
385420
386421 /// Horizontal pass, AVX2: 16 outputs per iteration. Each 256-bit `madd`
@@ -399,6 +434,7 @@ mod simd {
399434 block_w: usize,
400435 t16: &[i16; 8],
401436 out: &mut [i16],
437+ round0: u32,
402438 ) {
403439 debug_assert!(out.len() >= rows * block_w);
404440 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
@@ -409,7 +445,7 @@ mod simd {
409445 _mm256_set1_epi32(tp[2]),
410446 _mm256_set1_epi32(tp[3]),
411447 ];
412- let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_0 - 1));
448+ let rnd = _mm256_set1_epi32(1 << (round0 - 1));
413449 for r in 0..rows {
414450 let sp = src.as_ptr().add(r * src_stride);
415451 let op = out.as_mut_ptr().add(r * block_w);
@@ -423,8 +459,8 @@ mod simd {
423459 let so = _mm256_loadu_si256(sp.add(c + 2 * k + 1).cast());
424460 o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));
425461 }
426- e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), INTER_ROUND_0 as i32);
427- o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);
462+ e = _mm256_sra_epi32(_mm256_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32));
463+ o = _mm256_sra_epi32(_mm256_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32));
428464 let lo = _mm256_unpacklo_epi32(e, o);
429465 let hi = _mm256_unpackhi_epi32(e, o);
430466 // `lo`/`hi` already hold the 16 outputs in order, four per
@@ -437,7 +473,15 @@ mod simd {
437473 if c < block_w {
438474 let s = r * src_stride + c;
439475 let o = r * block_w + c;
440- hpass_sse2(&src[s..], 0, 1, block_w - c, t16, &mut out[o..o + block_w - c]);
476+ hpass_sse2(
477+ &src[s..],
478+ 0,
479+ 1,
480+ block_w - c,
481+ t16,
482+ &mut out[o..o + block_w - c],
483+ round0,
484+ );
441485 }
442486 }
443487 }
@@ -461,33 +505,38 @@ mod simd {
461505 taps: &[i32; 8],
462506 acc: &mut [i32],
463507 ) {
464- debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w);
508+ debug_assert!(
509+ intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w
510+ );
465511 let tp = tap_pairs(&taps16(taps));
466512 for row in 0..rows {
467- let ip = intermediate.as_ptr().add(row * src_stride);
468- let ap = acc.as_mut_ptr().add(row * block_w);
469- let mut c = 0usize;
470- while c + 16 <= block_w {
471- // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit
472- // lane), `hi` the other two runs; the two `permute2x128`s put the
473- // 16 sums back in column order.
474- let mut lo = _mm256_setzero_si256();
475- let mut hi = _mm256_setzero_si256();
476- for k in 0..4 {
477- if tp[k] == 0 {
478- continue;
513+ let ip = intermediate.as_ptr().add(row * src_stride);
514+ let ap = acc.as_mut_ptr().add(row * block_w);
515+ let mut c = 0usize;
516+ while c + 16 <= block_w {
517+ // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit
518+ // lane), `hi` the other two runs; the two `permute2x128`s put the
519+ // 16 sums back in column order.
520+ let mut lo = _mm256_setzero_si256();
521+ let mut hi = _mm256_setzero_si256();
522+ for k in 0..4 {
523+ if tp[k] == 0 {
524+ continue;
525+ }
526+ let tv = _mm256_set1_epi32(tp[k]);
527+ let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast());
528+ let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast());
529+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
530+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
479531 }
480- let tv = _mm256_set1_epi32(tp[k]);
481- let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast());
482- let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast());
483- lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
484- hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
532+ _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));
533+ _mm256_storeu_si256(
534+ ap.add(c + 8).cast(),
535+ _mm256_permute2x128_si256(lo, hi, 0x31),
536+ );
537+ c += 16;
485538 }
486- _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));
487- _mm256_storeu_si256(ap.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31));
488- c += 16;
489- }
490- vpass_tail_sse(ip, block_w, src_stride, &tp, taps, ap, c);
539+ vpass_tail_sse(ip, block_w, src_stride, &tp, taps, ap, c);
491540 }
492541 }
493542
@@ -570,37 +619,40 @@ mod simd {
570619 taps: &[i32; 8],
571620 max: i32,
572621 dst: &mut [u16],
622+ round1: u32,
573623 ) {
574- debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w);
624+ debug_assert!(
625+ intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w
626+ );
575627 let tp = tap_pairs(&taps16(taps));
576- let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_1 - 1));
628+ let rnd = _mm256_set1_epi32(1 << (round1 - 1));
577629 let mx = _mm256_set1_epi16(max as i16);
578630 for row in 0..rows {
579- let ip = intermediate.as_ptr().add(row * src_stride);
580- let dp = dst.as_mut_ptr().add(row * block_w);
581- let mut c = 0usize;
582- while c + 16 <= block_w {
583- let mut lo = rnd;
584- let mut hi = rnd;
585- for k in 0..4 {
586- if tp[k] == 0 {
587- continue;
631+ let ip = intermediate.as_ptr().add(row * src_stride);
632+ let dp = dst.as_mut_ptr().add(row * block_w);
633+ let mut c = 0usize;
634+ while c + 16 <= block_w {
635+ let mut lo = rnd;
636+ let mut hi = rnd;
637+ for k in 0..4 {
638+ if tp[k] == 0 {
639+ continue;
640+ }
641+ let tv = _mm256_set1_epi32(tp[k]);
642+ let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast());
643+ let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast());
644+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
645+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
588646 }
589- let tv = _mm256_set1_epi32(tp[k]);
590- let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast());
591- let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast());
592- lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
593- hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
647+ lo = _mm256_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32));
648+ hi = _mm256_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32));
649+ // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
650+ // per lane in order, so this is c..c+16 in order.
651+ let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
652+ _mm256_storeu_si256(dp.add(c).cast(), v);
653+ c += 16;
594654 }
595- lo = _mm256_srai_epi32(lo, INTER_ROUND_1 as i32);
596- hi = _mm256_srai_epi32(hi, INTER_ROUND_1 as i32);
597- // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
598- // per lane in order, so this is c..c+16 in order.
599- let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
600- _mm256_storeu_si256(dp.add(c).cast(), v);
601- c += 16;
602- }
603- vpass_u16_tail_sse(ip, block_w, src_stride, &tp, taps, max, dp, c);
655+ vpass_u16_tail_sse(ip, block_w, src_stride, &tp, taps, max, dp, c, round1);
604656 }
605657 }
606658
@@ -619,8 +671,9 @@ mod simd {
619671 max: i32,
620672 dp: *mut u16,
621673 mut c: usize,
674+ round1: u32,
622675 ) {
623- let rnd = _mm_set1_epi32(1 << (INTER_ROUND_1 - 1));
676+ let rnd = _mm_set1_epi32(1 << (round1 - 1));
624677 let mx = _mm_set1_epi16(max as i16);
625678 while c + 4 <= block_w {
626679 let wide = c + 8 <= block_w;
@@ -631,7 +684,10 @@ mod simd {
631684 continue;
632685 }
633686 let tv = _mm_set1_epi32(tp[k]);
634- let (pa, pb) = (ip.add(2 * k * src_stride + c), ip.add((2 * k + 1) * src_stride + c));
687+ let (pa, pb) = (
688+ ip.add(2 * k * src_stride + c),
689+ ip.add((2 * k + 1) * src_stride + c),
690+ );
635691 let (a, b) = if wide {
636692 (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast()))
637693 } else {
@@ -643,7 +699,10 @@ mod simd {
643699 }
644700 }
645701 let v = _mm_min_epu16(
646- _mm_packus_epi32(_mm_srai_epi32(lo, INTER_ROUND_1 as i32), _mm_srai_epi32(hi, INTER_ROUND_1 as i32)),
702+ _mm_packus_epi32(
703+ _mm_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32)),
704+ _mm_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32)),
705+ ),
647706 mx,
648707 );
649708 if wide {
@@ -659,7 +718,7 @@ mod simd {
659718 for (t, &tap) in taps.iter().enumerate() {
660719 sum += tap * i32::from(*ip.add(t * src_stride + c));
661720 }
662- *dp.add(c) = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
721+ *dp.add(c) = round2(sum, round1).clamp(0, max) as u16;
663722 c += 1;
664723 }
665724 }
@@ -677,13 +736,23 @@ mod simd {
677736 taps: &[i32; 8],
678737 max: i32,
679738 dst: &mut [u16],
739+ round1: u32,
680740 ) {
681- debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w);
741+ debug_assert!(
742+ intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w
743+ );
682744 let tp = tap_pairs(&taps16(taps));
683745 for row in 0..rows {
684746 vpass_u16_tail_sse(
685- intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps, max,
686- dst.as_mut_ptr().add(row * block_w), 0,
747+ intermediate.as_ptr().add(row * src_stride),
748+ block_w,
749+ src_stride,
750+ &tp,
751+ taps,
752+ max,
753+ dst.as_mut_ptr().add(row * block_w),
754+ 0,
755+ round1,
687756 );
688757 }
689758 }
@@ -700,12 +769,19 @@ mod simd {
700769 taps: &[i32; 8],
701770 acc: &mut [i32],
702771 ) {
703- debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w);
772+ debug_assert!(
773+ intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w
774+ );
704775 let tp = tap_pairs(&taps16(taps));
705776 for row in 0..rows {
706777 vpass_tail_sse(
707- intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps,
708- acc.as_mut_ptr().add(row * block_w), 0,
778+ intermediate.as_ptr().add(row * src_stride),
779+ block_w,
780+ src_stride,
781+ &tp,
782+ taps,
783+ acc.as_mut_ptr().add(row * block_w),
784+ 0,
709785 );
710786 }
711787 }
@@ -723,6 +799,7 @@ mod simd {
723799 block_w: usize,
724800 t16: &[i16; 8],
725801 out: &mut [i16],
802+ round0: u32,
726803 ) {
727804 debug_assert!(out.len() >= rows * block_w);
728805 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
@@ -733,7 +810,7 @@ mod simd {
733810 _mm_set1_epi32(tp[2]),
734811 _mm_set1_epi32(tp[3]),
735812 ];
736- let rnd = _mm_set1_epi32(1 << (INTER_ROUND_0 - 1));
813+ let rnd = _mm_set1_epi32(1 << (round0 - 1));
737814 for r in 0..rows {
738815 let sp = src.as_ptr().add(r * src_stride);
739816 let op = out.as_mut_ptr().add(r * block_w);
@@ -747,8 +824,8 @@ mod simd {
747824 let so = _mm_loadu_si128(sp.add(c + 2 * k + 1).cast());
748825 o = _mm_add_epi32(o, _mm_madd_epi16(so, tv[k]));
749826 }
750- e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);
751- o = _mm_srai_epi32(_mm_add_epi32(o, rnd), INTER_ROUND_0 as i32);
827+ e = _mm_sra_epi32(_mm_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32));
828+ o = _mm_sra_epi32(_mm_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32));
752829 let lo = _mm_unpacklo_epi32(e, o);
753830 let hi = _mm_unpackhi_epi32(e, o);
754831 _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));
@@ -759,7 +836,7 @@ mod simd {
759836 for t in 0..8 {
760837 sum += i32::from(t16[t]) * i32::from(*sp.add(c + t) as i16);
761838 }
762- *op.add(c) = sat16(round2(sum, INTER_ROUND_0));
839+ *op.add(c) = sat16(round2(sum, round0));
763840 c += 1;
764841 }
765842 }
@@ -774,7 +851,15 @@ mod simd {
774851 /// loop and it auto-vectorises. The edge case keeps the exact spec form
775852 /// (`sample`'s clamp per tap); both arms compute the same sums.
776853 #[inline]
777-fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i16]) {
854+fn hpass_row(
855+ reference: &[u16],
856+ row_base: usize,
857+ true_width: usize,
858+ x0: i32,
859+ taps: &[i32; 8],
860+ out: &mut [i16],
861+ round0: u32,
862+) {
778863 let block_w = out.len();
779864 let start = x0 - 3;
780865 if start >= 0 && start as usize + block_w + 7 <= true_width {
@@ -784,10 +869,16 @@ fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, tap
784869 // bit depth), so the products are exactly the i32 ones above but
785870 // the widening multiply is one instruction per pair.
786871 let t16 = [
787- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
788- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
872+ taps[0] as i16,
873+ taps[1] as i16,
874+ taps[2] as i16,
875+ taps[3] as i16,
876+ taps[4] as i16,
877+ taps[5] as i16,
878+ taps[6] as i16,
879+ taps[7] as i16,
789880 ];
790- hpass_contig(src, &t16, out);
881+ hpass_contig(src, &t16, out, round0);
791882 return;
792883 }
793884 }
@@ -797,7 +888,7 @@ fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, tap
797888 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
798889 sum += tap * i32::from(reference[row_base + x]);
799890 }
800- *o = sat16(round2(sum, INTER_ROUND_0));
891+ *o = sat16(round2(sum, round0));
801892 }
802893 }
803894
@@ -815,6 +906,7 @@ fn horizontal_pass_unscaled(
815906 block_w: usize,
816907 rows: usize,
817908 intermediate: &mut [i16],
909+ round0: u32,
818910 ) {
819911 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
820912 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
@@ -838,8 +930,14 @@ fn horizontal_pass_unscaled(
838930 let span = block_w + 7;
839931 if base + (rows - 1) * stride + span <= reference.len() {
840932 let t16 = [
841- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
842- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
933+ taps[0] as i16,
934+ taps[1] as i16,
935+ taps[2] as i16,
936+ taps[3] as i16,
937+ taps[4] as i16,
938+ taps[5] as i16,
939+ taps[6] as i16,
940+ taps[7] as i16,
843941 ];
844942 hpass_rows(
845943 &reference[base..],
@@ -848,6 +946,7 @@ fn horizontal_pass_unscaled(
848946 block_w,
849947 &t16,
850948 &mut intermediate[..rows * block_w],
949+ round0,
851950 );
852951 return;
853952 }
@@ -856,9 +955,11 @@ fn horizontal_pass_unscaled(
856955 let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize;
857956 let out = &mut intermediate[r * block_w..(r + 1) * block_w];
858957 if identity {
859- let gain = 128 >> INTER_ROUND_0;
958+ let gain = 128 >> round0;
860959 if x0 >= 0 && x0 as usize + block_w <= true_width {
861- if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {
960+ if let Some(src) =
961+ reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w)
962+ {
862963 for (o, &s) in out.iter_mut().zip(src) {
863964 *o = (gain * i32::from(s)) as i16;
864965 }
@@ -871,7 +972,7 @@ fn horizontal_pass_unscaled(
871972 }
872973 continue;
873974 }
874- hpass_row(reference, y * stride, true_width, x0, taps, out);
975+ hpass_row(reference, y * stride, true_width, x0, taps, out, round0);
875976 }
876977 }
877978
@@ -882,7 +983,14 @@ fn horizontal_pass_unscaled(
882983 /// eight slots. `acc` is left holding the unrounded sums.
883984 #[inline]
884985 #[allow(unsafe_code)]
885-pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, src_stride: usize, rows: usize, taps: &[i32; 8], acc: &mut [i32]) {
986+pub(crate) fn vpass_row(
987+ intermediate: &[i16],
988+ block_w: usize,
989+ src_stride: usize,
990+ rows: usize,
991+ taps: &[i32; 8],
992+ acc: &mut [i32],
993+) {
886994 #[cfg(target_arch = "x86_64")]
887995 {
888996 match simd_level() {
@@ -903,7 +1011,11 @@ pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, src_stride: usize,
9031011 }
9041012 for row in 0..rows {
9051013 vpass_row_scalar(
906- &intermediate[row * src_stride..], block_w, src_stride, 0, taps,
1014+ &intermediate[row * src_stride..],
1015+ block_w,
1016+ src_stride,
1017+ 0,
1018+ taps,
9071019 &mut acc[row * block_w..(row + 1) * block_w],
9081020 );
9091021 }
@@ -923,6 +1035,7 @@ fn vpass_row_u16(
9231035 taps: &[i32; 8],
9241036 max: i32,
9251037 dst: &mut [u16],
1038+ round1: u32,
9261039 ) {
9271040 #[cfg(target_arch = "x86_64")]
9281041 {
@@ -932,11 +1045,33 @@ fn vpass_row_u16(
9321045 // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which
9331046 // the debug asserts pin.
9341047 SimdLevel::Avx2 => {
935- unsafe { simd::vpass_row_u16_avx2(intermediate, block_w, src_stride, rows, taps, max, dst) };
1048+ unsafe {
1049+ simd::vpass_row_u16_avx2(
1050+ intermediate,
1051+ block_w,
1052+ src_stride,
1053+ rows,
1054+ taps,
1055+ max,
1056+ dst,
1057+ round1,
1058+ )
1059+ };
9361060 return;
9371061 }
9381062 SimdLevel::Sse41 => {
939- unsafe { simd::vpass_row_u16_sse41(intermediate, block_w, src_stride, rows, taps, max, dst) };
1063+ unsafe {
1064+ simd::vpass_row_u16_sse41(
1065+ intermediate,
1066+ block_w,
1067+ src_stride,
1068+ rows,
1069+ taps,
1070+ max,
1071+ dst,
1072+ round1,
1073+ )
1074+ };
9401075 return;
9411076 }
9421077 SimdLevel::Scalar => {}
@@ -944,8 +1079,14 @@ fn vpass_row_u16(
9441079 }
9451080 for row in 0..rows {
9461081 vpass_row_u16_scalar(
947- &intermediate[row * src_stride..], block_w, src_stride, 0, taps, max,
1082+ &intermediate[row * src_stride..],
1083+ block_w,
1084+ src_stride,
1085+ 0,
1086+ taps,
1087+ max,
9481088 &mut dst[row * block_w..(row + 1) * block_w],
1089+ round1,
9491090 );
9501091 }
9511092 }
@@ -959,25 +1100,36 @@ fn vpass_row_u16_scalar(
9591100 taps: &[i32; 8],
9601101 max: i32,
9611102 dst: &mut [u16],
1103+ round1: u32,
9621104 ) {
9631105 for (c, d) in dst[..block_w].iter_mut().enumerate() {
9641106 let mut sum = 0i32;
9651107 for (t, &tap) in taps.iter().enumerate() {
9661108 sum += tap * i32::from(intermediate[(row + t) * src_stride + c]);
9671109 }
968- *d = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
1110+ *d = round2(sum, round1).clamp(0, max) as u16;
9691111 }
9701112 }
9711113
9721114 /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).
973-fn vpass_row_scalar(intermediate: &[i16], block_w: usize, src_stride: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
1115+fn vpass_row_scalar(
1116+ intermediate: &[i16],
1117+ block_w: usize,
1118+ src_stride: usize,
1119+ row: usize,
1120+ taps: &[i32; 8],
1121+ acc: &mut [i32],
1122+) {
9741123 acc[..block_w].fill(0);
9751124 for (t, &tap) in taps.iter().enumerate() {
9761125 if tap == 0 {
9771126 continue;
9781127 }
9791128 let base = (row + t) * src_stride;
980- for (a, &s) in acc[..block_w].iter_mut().zip(&intermediate[base..base + block_w]) {
1129+ for (a, &s) in acc[..block_w]
1130+ .iter_mut()
1131+ .zip(&intermediate[base..base + block_w])
1132+ {
9811133 *a += tap * i32::from(s);
9821134 }
9831135 }
@@ -1037,7 +1189,8 @@ pub(crate) fn predict(
10371189 y_q4: i32,
10381190 block_w: usize,
10391191 block_h: usize,
1040- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1192+ dst: &mut [u16],
1193+ fctx: &crate::decode::FrameCtx,
10411194 ) {
10421195 predict_with_filter(
10431196 reference,
@@ -1054,7 +1207,8 @@ pub(crate) fn predict(
10541207 // `Regular` (the decoder's own inter path calls
10551208 // `predict_with_filters` with the kernels it parsed).
10561209 fctx.interp_filter.get(),
1057- dst, fctx,
1210+ dst,
1211+ fctx,
10581212 );
10591213 }
10601214
@@ -1072,7 +1226,8 @@ pub(crate) fn predict_with_filter(
10721226 block_w: usize,
10731227 block_h: usize,
10741228 filter_kind: InterpFilterKind,
1075- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1229+ dst: &mut [u16],
1230+ fctx: &crate::decode::FrameCtx,
10761231 ) {
10771232 predict_with_filters(
10781233 reference,
@@ -1085,7 +1240,8 @@ pub(crate) fn predict_with_filter(
10851240 block_h,
10861241 filter_kind,
10871242 filter_kind,
1088- dst, fctx,
1243+ dst,
1244+ fctx,
10891245 );
10901246 }
10911247
@@ -1105,11 +1261,24 @@ pub(crate) fn predict_with_filters(
11051261 block_h: usize,
11061262 h_kind: InterpFilterKind,
11071263 v_kind: InterpFilterKind,
1108- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1264+ dst: &mut [u16],
1265+ fctx: &crate::decode::FrameCtx,
11091266 ) {
11101267 predict_with_filters_kern(
1111- reference, stride, true_width, true_height, x_q4, y_q4, block_w,
1112- block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1268+ reference,
1269+ stride,
1270+ true_width,
1271+ true_height,
1272+ x_q4,
1273+ y_q4,
1274+ block_w,
1275+ block_h,
1276+ block_w,
1277+ block_h,
1278+ h_kind,
1279+ v_kind,
1280+ dst,
1281+ fctx,
11131282 );
11141283 }
11151284
@@ -1135,7 +1304,8 @@ pub(crate) fn predict_with_filters_kern(
11351304 kern_h: usize,
11361305 h_kind: InterpFilterKind,
11371306 v_kind: InterpFilterKind,
1138- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1307+ dst: &mut [u16],
1308+ fctx: &crate::decode::FrameCtx,
11391309 ) {
11401310 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
11411311 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1173,7 +1343,9 @@ pub(crate) fn predict_with_filters_kern(
11731343 let out = &mut dst[row * block_w..(row + 1) * block_w];
11741344 // lane-perf2: an interior row is one contiguous copy.
11751345 if x0 >= 0 && x0 as usize + block_w <= true_width {
1176- if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) {
1346+ if let Some(src) =
1347+ reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w)
1348+ {
11771349 // The common widths get a constant-length copy: at 8
11781350 // samples a `memcpy` call costs more than the move it
11791351 // makes, and 8x8 is the most common inter block on real
@@ -1219,15 +1391,23 @@ pub(crate) fn predict_with_filters_kern(
12191391 // block's own first row where the pass would have put the 4th.
12201392 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
12211393 let max = crate::decode::sample_max(fctx);
1394+ // lane-av112bit: the frame's rounding pair (libaom `get_conv_params_no_round`
1395+ // via [`round_pair`]) -- 3/11 at 8 and 10 bits, 5/9 at 12.
1396+ let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
12221397 // lane-mc2: a whole-pel horizontal position makes the horizontal pass the
1223- // identity tap, whose output is `s << 4` (`Round2(128 * s, InterRound0)`
1224- // with the tap 128). The vertical pass then computes
1225- // `Round2(sum(tap * (s << 4)), InterRound1)`, which is the same 8-tap sum
1226- // taken straight off the reference rows with every tap scaled by 16 --
1227- // bit-identical, and it skips materialising `block_h + 7` intermediate
1228- // rows. Interior blocks only; an edge block still needs the clamped read.
1398+ // identity tap, whose output is `(128 >> round0) * s` (`Round2(128 * s,
1399+ // round0)` with the tap 128). The vertical pass then computes
1400+ // `Round2(sum(tap * ((128 >> round0) * s)), round1)`, which is the same
1401+ // 8-tap sum taken straight off the reference rows with every tap scaled
1402+ // by `128 >> round0` -- bit-identical (128 is a multiple of `2^round0` at
1403+ // every supported depth), and it skips materialising `block_h + 7`
1404+ // intermediate rows. Interior blocks only; an edge block still needs the
1405+ // clamped read.
12291406 if xfrac != 0 || yfrac == 0 {
12301407 // fall through to the two-pass path
1408+ if xfrac != 0 || yfrac != 0 {
1409+ hit!(MC_SUBPEL_HITS);
1410+ }
12311411 } else {
12321412 let top = y0 - 3;
12331413 if top >= 0
@@ -1239,15 +1419,25 @@ pub(crate) fn predict_with_filters_kern(
12391419 if base + (block_h + 6) * stride + block_w <= reference.len() {
12401420 let mut v16 = [0i32; 8];
12411421 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1242- *o = t * 16;
1422+ *o = t * (128 >> round0);
12431423 }
12441424 // SAFETY: samples are below `2^15` at every supported bit
12451425 // depth, so the same bytes read as `i16` are the same values;
12461426 // the length is unchanged.
12471427 #[allow(unsafe_code)]
1248- let src: &[i16] =
1249- unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };
1250- vpass_row_u16(&src[base..], block_w, stride, block_h, &v16, max, dst);
1428+ let src: &[i16] = unsafe {
1429+ std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len())
1430+ };
1431+ vpass_row_u16(
1432+ &src[base..],
1433+ block_w,
1434+ stride,
1435+ block_h,
1436+ &v16,
1437+ max,
1438+ dst,
1439+ round1,
1440+ );
12511441 #[cfg(test)]
12521442 crate::encode::stage_since(1, stage_t);
12531443 return;
@@ -1256,17 +1446,36 @@ pub(crate) fn predict_with_filters_kern(
12561446 }
12571447 with_scratch(rows, block_w, |intermediate, _acc| {
12581448 horizontal_pass_unscaled(
1259- reference, stride, true_width, true_height, x0,
1260- if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
1449+ reference,
1450+ stride,
1451+ true_width,
1452+ true_height,
1453+ x0,
1454+ if yfrac == 0 { y0 + 3 } else { y0 },
1455+ h_filter,
1456+ block_w,
1457+ rows,
12611458 intermediate,
1459+ round0,
12621460 );
12631461 if yfrac == 0 {
1462+ // The vertical filter is the identity tap here:
1463+ // `Round2(128 * a, round1) == Round2(a, round1 - 7)` exactly.
12641464 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1265- *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
1465+ *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16;
12661466 }
12671467 return;
12681468 }
1269- vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);
1469+ vpass_row_u16(
1470+ intermediate,
1471+ block_w,
1472+ block_w,
1473+ block_h,
1474+ v_filter,
1475+ max,
1476+ dst,
1477+ round1,
1478+ );
12701479 });
12711480
12721481 #[cfg(test)]
@@ -1304,6 +1513,13 @@ pub fn predict_scaled_hits() -> usize {
13041513 }
13051514
13061515 thread_local! {
1516+ /// lane-av112bit: how many inter predictions took the two-pass SUBPEL
1517+ /// path (a non-zero horizontal or vertical fraction) -- the 12-bit
1518+ /// inter gate's proof that the frame's own `round_0`/`round_1` actually
1519+ /// ran, not just the whole-pel identity copy (class
1520+ /// `gate-blind-to-feature`).
1521+ pub(crate) static MC_SUBPEL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1522+
13071523 /// lane-hbdinter: how many inter predictions this thread has produced
13081524 /// (single-reference, scaled, and the compound intermediate entry). The
13091525 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
@@ -1343,6 +1559,11 @@ pub fn inter_pred_hits() -> usize {
13431559 INTER_PRED_HITS.with(|c| c.get())
13441560 }
13451561
1562+/// Current value of [`MC_SUBPEL_HITS`].
1563+pub(crate) fn mc_subpel_hits() -> usize {
1564+ MC_SUBPEL_HITS.with(|c| c.get())
1565+}
1566+
13461567 fn round_pow2_64(value: i64, shift: u32) -> i64 {
13471568 if shift == 0 {
13481569 value
@@ -1386,6 +1607,7 @@ fn horizontal_scaled_pass(
13861607 rows: usize,
13871608 h_kind: InterpFilterKind,
13881609 intermediate: &mut [i16],
1610+ round0: u32,
13891611 ) {
13901612 let x_step_qn = round_pow2_64(x_scale_fp, 4);
13911613 let off = (x_scale_fp - REF_NO_SCALE) * 8;
@@ -1407,7 +1629,7 @@ fn horizontal_scaled_pass(
14071629 let x = int_pel + t as i32 - 3;
14081630 sum += tap * sample(reference, stride, true_width, true_height, x, y);
14091631 }
1410- intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;
1632+ intermediate[r * block_w + c] = round2(sum, round0) as i16;
14111633 }
14121634 }
14131635 }
@@ -1439,11 +1661,16 @@ fn horizontal_pass(
14391661 rows: usize,
14401662 h_kind: InterpFilterKind,
14411663 intermediate: &mut [i16],
1664+ round0: u32,
14421665 ) {
14431666 if x_scale_fp == REF_NO_SCALE {
14441667 let (h_wide, h_narrow) = h_kind.tables();
14451668 let xfrac = x_q4.rem_euclid(16) as usize;
1446- let taps = if kern_w <= 4 { &h_narrow[xfrac] } else { &h_wide[xfrac] };
1669+ let taps = if kern_w <= 4 {
1670+ &h_narrow[xfrac]
1671+ } else {
1672+ &h_wide[xfrac]
1673+ };
14471674 horizontal_pass_unscaled(
14481675 reference,
14491676 stride,
@@ -1455,12 +1682,24 @@ fn horizontal_pass(
14551682 block_w,
14561683 rows,
14571684 intermediate,
1685+ round0,
14581686 );
14591687 return;
14601688 }
14611689 horizontal_scaled_pass(
1462- reference, stride, true_width, true_height, x_q4, y0, x_scale_fp, block_w, kern_w,
1463- rows, h_kind, intermediate,
1690+ reference,
1691+ stride,
1692+ true_width,
1693+ true_height,
1694+ x_q4,
1695+ y0,
1696+ x_scale_fp,
1697+ block_w,
1698+ kern_w,
1699+ rows,
1700+ h_kind,
1701+ intermediate,
1702+ round0,
14641703 );
14651704 }
14661705
@@ -1491,11 +1730,25 @@ pub(crate) fn predict_scaled(
14911730 block_h: usize,
14921731 h_kind: InterpFilterKind,
14931732 v_kind: InterpFilterKind,
1494- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1733+ dst: &mut [u16],
1734+ fctx: &crate::decode::FrameCtx,
14951735 ) {
14961736 predict_scaled_kern(
1497- reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1498- block_w, block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1737+ reference,
1738+ stride,
1739+ true_width,
1740+ true_height,
1741+ x_q4,
1742+ y_q4,
1743+ x_scale_fp,
1744+ block_w,
1745+ block_h,
1746+ block_w,
1747+ block_h,
1748+ h_kind,
1749+ v_kind,
1750+ dst,
1751+ fctx,
14991752 );
15001753 }
15011754
@@ -1516,7 +1769,8 @@ pub(crate) fn predict_scaled_kern(
15161769 kern_h: usize,
15171770 h_kind: InterpFilterKind,
15181771 v_kind: InterpFilterKind,
1519- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1772+ dst: &mut [u16],
1773+ fctx: &crate::decode::FrameCtx,
15201774 ) {
15211775 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
15221776 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1539,19 +1793,41 @@ pub(crate) fn predict_scaled_kern(
15391793
15401794 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
15411795 let max = crate::decode::sample_max(fctx);
1796+ let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
15421797 with_scratch(rows, block_w, |intermediate, _acc| {
15431798 horizontal_pass(
1544- reference, stride, true_width, true_height, x_q4,
1545- if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
1546- kern_w, rows, h_kind, intermediate,
1799+ reference,
1800+ stride,
1801+ true_width,
1802+ true_height,
1803+ x_q4,
1804+ if yfrac == 0 { y0 + 3 } else { y0 },
1805+ x_scale_fp,
1806+ block_w,
1807+ kern_w,
1808+ rows,
1809+ h_kind,
1810+ intermediate,
1811+ round0,
15471812 );
15481813 if yfrac == 0 {
1814+ // Identity vertical tap: `Round2(128 * a, round1) ==
1815+ // Round2(a, round1 - 7)` exactly.
15491816 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1550- *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
1817+ *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16;
15511818 }
15521819 return;
15531820 }
1554- vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);
1821+ vpass_row_u16(
1822+ intermediate,
1823+ block_w,
1824+ block_w,
1825+ block_h,
1826+ v_filter,
1827+ max,
1828+ dst,
1829+ round1,
1830+ );
15551831 });
15561832 }
15571833
@@ -1572,17 +1848,39 @@ pub(crate) fn predict_maybe_scaled(
15721848 block_h: usize,
15731849 h_kind: InterpFilterKind,
15741850 v_kind: InterpFilterKind,
1575- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1851+ dst: &mut [u16],
1852+ fctx: &crate::decode::FrameCtx,
15761853 ) {
15771854 if x_scale_fp == REF_NO_SCALE {
15781855 predict_with_filters(
1579- reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind,
1580- v_kind, dst, fctx,
1856+ reference,
1857+ stride,
1858+ true_width,
1859+ true_height,
1860+ x_q4,
1861+ y_q4,
1862+ block_w,
1863+ block_h,
1864+ h_kind,
1865+ v_kind,
1866+ dst,
1867+ fctx,
15811868 );
15821869 } else {
15831870 predict_scaled(
1584- reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w,
1585- block_h, h_kind, v_kind, dst, fctx,
1871+ reference,
1872+ stride,
1873+ true_width,
1874+ true_height,
1875+ x_q4,
1876+ y_q4,
1877+ x_scale_fp,
1878+ block_w,
1879+ block_h,
1880+ h_kind,
1881+ v_kind,
1882+ dst,
1883+ fctx,
15861884 );
15871885 }
15881886 }
@@ -1620,7 +1918,7 @@ const DIST_PRECISION_BITS: u32 = 4;
16201918 /// Panics when `dst` is not `block_w * block_h` long, or the reference is
16211919 /// empty.
16221920 #[allow(clippy::too_many_arguments)]
1623-pub fn predict_compound_intermediate(
1921+pub(crate) fn predict_compound_intermediate(
16241922 reference: &[u16],
16251923 stride: usize,
16261924 true_width: usize,
@@ -1633,17 +1931,31 @@ pub fn predict_compound_intermediate(
16331931 h_kind: InterpFilterKind,
16341932 v_kind: InterpFilterKind,
16351933 dst: &mut [i32],
1934+ fctx: &crate::decode::FrameCtx,
16361935 ) {
16371936 predict_compound_intermediate_kern(
1638- reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1639- block_w, block_h, block_w, block_h, h_kind, v_kind, dst,
1937+ reference,
1938+ stride,
1939+ true_width,
1940+ true_height,
1941+ x_q4,
1942+ y_q4,
1943+ x_scale_fp,
1944+ block_w,
1945+ block_h,
1946+ block_w,
1947+ block_h,
1948+ h_kind,
1949+ v_kind,
1950+ dst,
1951+ fctx,
16401952 );
16411953 }
16421954
16431955 /// [`predict_compound_intermediate`] with the 4-tap decision from the block's
16441956 /// true dims (see [`predict_with_filters_kern`]).
16451957 #[allow(clippy::too_many_arguments)]
1646-pub fn predict_compound_intermediate_kern(
1958+pub(crate) fn predict_compound_intermediate_kern(
16471959 reference: &[u16],
16481960 stride: usize,
16491961 true_width: usize,
@@ -1658,6 +1970,7 @@ pub fn predict_compound_intermediate_kern(
16581970 h_kind: InterpFilterKind,
16591971 v_kind: InterpFilterKind,
16601972 dst: &mut [i32],
1973+ fctx: &crate::decode::FrameCtx,
16611974 ) {
16621975 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
16631976 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1682,10 +1995,15 @@ pub fn predict_compound_intermediate_kern(
16821995 };
16831996
16841997 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1998+ // lane-av112bit: the horizontal pass shares `predict_with_filters_kern`'s
1999+ // `round_0` (the compound VERTICAL round below is `INTER_ROUND_1_COMPOUND`
2000+ // at every bit depth), so the identity-tap gain moves with it the same way.
2001+ let (round0, _round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
16852002 // lane-mc2: the unscaled whole-pel horizontal position is the identity
1686- // tap, whose intermediate is `s << 4`, so the vertical pass is the same
1687- // 8-tap sum taken straight off the reference rows with the taps scaled by
1688- // 16 (see `predict_with_filters_kern`). Interior blocks only.
2003+ // tap, whose intermediate is `(128 >> round0) * s`, so the vertical pass
2004+ // is the same 8-tap sum taken straight off the reference rows with the
2005+ // taps scaled by that gain (see `predict_with_filters_kern`). Interior
2006+ // blocks only.
16892007 let x0 = x_q4.div_euclid(16);
16902008 if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 {
16912009 let top = y0 - 3;
@@ -1698,13 +2016,14 @@ pub fn predict_compound_intermediate_kern(
16982016 if base + (block_h + 6) * stride + block_w <= reference.len() {
16992017 let mut v16 = [0i32; 8];
17002018 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1701- *o = t * 16;
2019+ *o = t * (128 >> round0);
17022020 }
17032021 // SAFETY: samples are below `2^15` at every supported bit
17042022 // depth, so the same bytes read as `i16` are the same values.
17052023 #[allow(unsafe_code)]
1706- let src: &[i16] =
1707- unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };
2024+ let src: &[i16] = unsafe {
2025+ std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len())
2026+ };
17082027 vpass_row(&src[base..], block_w, stride, block_h, &v16, dst);
17092028 for d in dst.iter_mut() {
17102029 *d = round2(*d, INTER_ROUND_1_COMPOUND);
@@ -1715,9 +2034,19 @@ pub fn predict_compound_intermediate_kern(
17152034 }
17162035 with_scratch(rows, block_w, |intermediate, _acc| {
17172036 horizontal_pass(
1718- reference, stride, true_width, true_height, x_q4,
1719- if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
1720- kern_w, rows, h_kind, intermediate,
2037+ reference,
2038+ stride,
2039+ true_width,
2040+ true_height,
2041+ x_q4,
2042+ if yfrac == 0 { y0 + 3 } else { y0 },
2043+ x_scale_fp,
2044+ block_w,
2045+ kern_w,
2046+ rows,
2047+ h_kind,
2048+ intermediate,
2049+ round0,
17212050 );
17222051 if yfrac == 0 {
17232052 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
@@ -1745,10 +2074,16 @@ pub(crate) fn combine_compound(
17452074 pred1: &[i32],
17462075 fwd_weight: i32,
17472076 bck_weight: i32,
1748- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
2077+ dst: &mut [u16],
2078+ fctx: &crate::decode::FrameCtx,
17492079 ) {
17502080 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
17512081 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
2082+ // lane-av112bit: `round_bits` is `2*FILTER_BITS - round_0 - round_1`
2083+ // with the frame's own `round_0`, i.e. `INTER_POST_ROUND` minus
2084+ // [`round_delta`] -- the CONV_BUF gain drops from 16x to 4x at 12-bit
2085+ // (`round_0` 5, compound `round_1` 7) and this final round absorbs it.
2086+ let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx)));
17522087 for i in 0..dst.len() {
17532088 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
17542089 // applies the two shifts SEPARATELY: a truncating `>>
@@ -1758,7 +2093,7 @@ pub(crate) fn combine_compound(
17582093 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
17592094 // dropped low 4 bits are non-zero.
17602095 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
1761- dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)
2096+ dst[i] = round2(sum >> DIST_PRECISION_BITS, post_round)
17622097 .clamp(0, crate::decode::sample_max(fctx)) as u16;
17632098 }
17642099 }
@@ -1773,15 +2108,22 @@ pub(crate) fn combine_compound(
17732108 /// produces give the identical `diff` libaom computes. `round` is
17742109 /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
17752110 /// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
1776-pub(crate) fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8], fctx: &crate::decode::FrameCtx) {
2111+pub(crate) fn diffwtd_mask(
2112+ pred0: &[i32],
2113+ pred1: &[i32],
2114+ inv: bool,
2115+ mask: &mut [u8],
2116+ fctx: &crate::decode::FrameCtx,
2117+) {
17772118 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
17782119 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
17792120 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
17802121 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
1781- // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
1782- // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
1783- // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
1784- let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
2122+ // bit-depth headroom the CONV_BUF domain carries, minus the [`round_delta`]
2123+ // that moves `round_0` itself at 12-bit (`convolve.h:83`'s
2124+ // `intbufrange > 16`; at 12-bit this is 14 - 5 - 7 + 4 == 6).
2125+ let bd = u32::from(crate::decode::bit_depth(fctx));
2126+ let round = INTER_POST_ROUND + bd.saturating_sub(8) - round_delta(bd);
17852127 for i in 0..mask.len() {
17862128 let diff = round2((pred0[i] - pred1[i]).abs(), round);
17872129 let m = (38 + diff / 16).clamp(0, 64);
@@ -1808,11 +2150,13 @@ pub(crate) fn blend_masked_compound(
18082150 w: usize,
18092151 h: usize,
18102152 subsampled: bool,
1811- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
2153+ dst: &mut [u16],
2154+ fctx: &crate::decode::FrameCtx,
18122155 ) {
18132156 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
18142157 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
18152158 assert_eq!(dst.len(), w * h, "the destination is the block");
2159+ let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx)));
18162160 for i in 0..h {
18172161 for j in 0..w {
18182162 let m = if subsampled {
@@ -1828,7 +2172,12 @@ pub(crate) fn blend_masked_compound(
18282172 i32::from(mask[i * mask_stride + j])
18292173 };
18302174 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
1831- dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max(fctx)) as u16;
2175+ // `post_round` above: `INTER_POST_ROUND - round_delta` -- see
2176+ // [`combine_compound`] (the same CONV_BUF gain absorption; the
2177+ // `>> 6` above is bit-depth free because the CONV_BUF relative
2178+ // weights are).
2179+ dst[i * w + j] =
2180+ round2(res, post_round).clamp(0, crate::decode::sample_max(fctx)) as u16;
18322181 }
18332182 }
18342183 }
@@ -1860,6 +2209,7 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
18602209 InterpFilterKind::Regular,
18612210 InterpFilterKind::Regular,
18622211 &mut pred0,
2212+ fctx,
18632213 );
18642214 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
18652215
@@ -1872,8 +2222,8 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
18722222 #[cfg(test)]
18732223 mod tests {
18742224 use super::{
1875- InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter,
1876- predict_with_filters,
2225+ predict, predict_scaled, predict_with_filter, predict_with_filters, InterpFilterKind,
2226+ REF_NO_SCALE,
18772227 };
18782228
18792229 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
@@ -1886,7 +2236,7 @@ mod tests {
18862236 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
18872237 #[test]
18882238 fn smooth_filter_matches_aomdec_chroma_inter_block() {
1889- let fctx = &crate::decode::FrameCtx::new();
2239+ let fctx = &crate::decode::FrameCtx::new();
18902240 #[rustfmt::skip]
18912241 let window: [[u8; 24]; 24] = [
18922242 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
@@ -1945,7 +2295,8 @@ mod tests {
19452295 16,
19462296 16,
19472297 InterpFilterKind::Smooth,
1948- &mut dst, fctx,
2298+ &mut dst,
2299+ fctx,
19492300 );
19502301 #[rustfmt::skip]
19512302 let expected_row0: [u16; 16] =
@@ -1996,7 +2347,7 @@ mod tests {
19962347
19972348 #[test]
19982349 fn integer_mv_is_identity() {
1999- let fctx = &crate::decode::FrameCtx::new();
2350+ let fctx = &crate::decode::FrameCtx::new();
20002351 let width = 12;
20012352 let height = 12;
20022353 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
@@ -2010,7 +2361,8 @@ mod tests {
20102361 4 * 16,
20112362 6,
20122363 6,
2013- &mut dst, fctx,
2364+ &mut dst,
2365+ fctx,
20142366 );
20152367 for row in 0..6 {
20162368 for col in 0..6 {
@@ -2025,7 +2377,7 @@ mod tests {
20252377
20262378 #[test]
20272379 fn half_pel_reproduces_the_ramp_midpoint() {
2028- let fctx = &crate::decode::FrameCtx::new();
2380+ let fctx = &crate::decode::FrameCtx::new();
20292381 // Step 2 so every half-pel position lands on an exact integer.
20302382 let width = 16;
20312383 let height = 16;
@@ -2043,7 +2395,8 @@ mod tests {
20432395 5 * 16,
20442396 4,
20452397 4,
2046- &mut dst, fctx,
2398+ &mut dst,
2399+ fctx,
20472400 );
20482401 for row in 0..4 {
20492402 for col in 0..4 {
@@ -2059,7 +2412,7 @@ mod tests {
20592412
20602413 #[test]
20612414 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
2062- let fctx = &crate::decode::FrameCtx::new();
2415+ let fctx = &crate::decode::FrameCtx::new();
20632416 let width = 20;
20642417 let height = 20;
20652418 let reference = vec![142u16; width * height];
@@ -2075,7 +2428,8 @@ mod tests {
20752428 5 * 16 + yfrac,
20762429 5,
20772430 5,
2078- &mut dst, fctx,
2431+ &mut dst,
2432+ fctx,
20792433 );
20802434 assert!(
20812435 dst.iter().all(|&v| v == 142),
@@ -2087,7 +2441,7 @@ mod tests {
20872441
20882442 #[test]
20892443 fn horizontal_and_vertical_only_filtering_differ() {
2090- let fctx = &crate::decode::FrameCtx::new();
2444+ let fctx = &crate::decode::FrameCtx::new();
20912445 // A plane linear in both x and y with different, even coefficients so
20922446 // each axis's half-pel interpolation lands on an exact integer: this
20932447 // pins the actual value each pass produces, not just that the two
@@ -2109,7 +2463,8 @@ mod tests {
21092463 3 * 16,
21102464 4,
21112465 4,
2112- &mut horiz, fctx,
2466+ &mut horiz,
2467+ fctx,
21132468 );
21142469 let mut vert = vec![0u16; 4 * 4];
21152470 predict(
@@ -2121,7 +2476,8 @@ mod tests {
21212476 3 * 16 + 8,
21222477 4,
21232478 4,
2124- &mut vert, fctx,
2479+ &mut vert,
2480+ fctx,
21252481 );
21262482
21272483 for row in 0..4 {
@@ -2148,7 +2504,7 @@ mod tests {
21482504
21492505 #[test]
21502506 fn mv_past_the_edge_clamps_instead_of_panicking() {
2151- let fctx = &crate::decode::FrameCtx::new();
2507+ let fctx = &crate::decode::FrameCtx::new();
21522508 let width = 8;
21532509 let height = 8;
21542510 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
@@ -2164,7 +2520,8 @@ mod tests {
21642520 -50 * 16 + 5,
21652521 4,
21662522 4,
2167- &mut dst, fctx,
2523+ &mut dst,
2524+ fctx,
21682525 );
21692526 let expected = reference[0]; // the whole plane clamps to the top-left corner
21702527 assert!(
@@ -2182,7 +2539,8 @@ mod tests {
21822539 50 * 16 + 5,
21832540 4,
21842541 4,
2185- &mut dst2, fctx,
2542+ &mut dst2,
2543+ fctx,
21862544 );
21872545 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
21882546 assert!(
@@ -2193,7 +2551,7 @@ mod tests {
21932551
21942552 #[test]
21952553 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
2196- let fctx = &crate::decode::FrameCtx::new();
2554+ let fctx = &crate::decode::FrameCtx::new();
21972555 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
21982556 // must reduce predict_scaled's per-column scaled walk to the exact
21992557 // same int_pel/filter_idx sequence predict_with_filters computes from
@@ -2217,7 +2575,8 @@ mod tests {
22172575 8,
22182576 InterpFilterKind::Regular,
22192577 InterpFilterKind::Regular,
2220- &mut expected, fctx,
2578+ &mut expected,
2579+ fctx,
22212580 );
22222581 let mut got = vec![0u16; block_w * 8];
22232582 predict_scaled(
@@ -2232,7 +2591,8 @@ mod tests {
22322591 8,
22332592 InterpFilterKind::Regular,
22342593 InterpFilterKind::Regular,
2235- &mut got, fctx,
2594+ &mut got,
2595+ fctx,
22362596 );
22372597 assert_eq!(
22382598 got, expected,
@@ -2272,26 +2632,52 @@ mod tests {
22722632 for frac in 0..16usize {
22732633 let taps = &table[frac];
22742634 let t16 = [
2275- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
2276- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
2635+ taps[0] as i16,
2636+ taps[1] as i16,
2637+ taps[2] as i16,
2638+ taps[3] as i16,
2639+ taps[4] as i16,
2640+ taps[5] as i16,
2641+ taps[6] as i16,
2642+ taps[7] as i16,
22772643 ];
22782644 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
22792645 let src: Vec<u16> = (0..w + 7)
22802646 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
22812647 .collect();
22822648 let mut want = vec![0i16; w];
2283- super::hpass_contig_scalar(&src, &t16, &mut want);
2649+ super::hpass_contig_scalar(&src, &t16, &mut want, 3);
22842650 let mut got = vec![0i16; w];
2285- super::hpass_contig(&src, &t16, &mut got);
2651+ super::hpass_contig(&src, &t16, &mut got, 3);
22862652 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
22872653 #[cfg(target_arch = "x86_64")]
22882654 {
22892655 let mut sse = vec![0i16; w];
2290- unsafe { super::simd::hpass_sse2(&src, 0, 1, sse.len(), &t16, &mut sse) };
2656+ unsafe {
2657+ super::simd::hpass_sse2(
2658+ &src,
2659+ 0,
2660+ 1,
2661+ sse.len(),
2662+ &t16,
2663+ &mut sse,
2664+ 3,
2665+ )
2666+ };
22912667 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
22922668 if std::arch::is_x86_feature_detected!("avx2") {
22932669 let mut avx = vec![0i16; w];
2294- unsafe { super::simd::hpass_avx2(&src, 0, 1, avx.len(), &t16, &mut avx) };
2670+ unsafe {
2671+ super::simd::hpass_avx2(
2672+ &src,
2673+ 0,
2674+ 1,
2675+ avx.len(),
2676+ &t16,
2677+ &mut avx,
2678+ 3,
2679+ )
2680+ };
22952681 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
22962682 }
22972683 }
@@ -2308,10 +2694,11 @@ mod tests {
23082694 /// is a claim about the FILTER TABLES, not about a sample: every kernel's
23092695 /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
23102696 /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored
2311- /// value is that over `1 << INTER_ROUND_0`. This enumerates all four
2697+ /// value is that over `1 << round_0`. This enumerates all four
23122698 /// filter kinds, both their wide and narrow tables and all 16 phases at
2313- /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses
2314- /// 12-bit by name) and pins the result inside `i16` -- so the SIMD
2699+ /// the deepest sample this decoder accepts (12-bit now -- lane-av112bit
2700+ /// lifted the refusal, with `round_0` at 5 there and 3 at 8/10-bit) and
2701+ /// pins the result inside `i16` -- so the SIMD
23152702 /// stores' `packs_epi32` never saturates on a motion-compensation path.
23162703 #[test]
23172704 fn horizontal_intermediate_fits_i16() {
@@ -2321,23 +2708,26 @@ mod tests {
23212708 InterpFilterKind::Sharp,
23222709 InterpFilterKind::Bilinear,
23232710 ];
2324- let max_sample = 1023i32; // 10-bit
2325- let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
2326- for &kind in &kinds {
2327- let (wide, narrow) = kind.tables();
2328- for table in [wide, narrow] {
2329- for taps in table {
2330- let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
2331- let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
2332- worst_hi = worst_hi.max(super::round2(max_sample * pos, super::INTER_ROUND_0));
2333- worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0));
2711+ // (max sample, the frame's `round_0`) per supported bit depth.
2712+ for (max_sample, round0) in [(255i32, 3u32), (1023, 3), (4095, 5)] {
2713+ let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
2714+ for &kind in &kinds {
2715+ let (wide, narrow) = kind.tables();
2716+ for table in [wide, narrow] {
2717+ for taps in table {
2718+ let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
2719+ let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
2720+ worst_hi = worst_hi.max(super::round2(max_sample * pos, round0));
2721+ worst_lo = worst_lo.min(super::round2(max_sample * neg, round0));
2722+ }
23342723 }
23352724 }
2725+ assert!(
2726+ worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
2727+ "the {max_sample}-sample (round_0 {round0}) intermediate range \
2728+ [{worst_lo}, {worst_hi}] must fit i16"
2729+ );
23362730 }
2337- assert!(
2338- worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
2339- "the 10-bit intermediate range [{worst_lo}, {worst_hi}] must fit i16"
2340- );
23412731 }
23422732
23432733 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
@@ -2368,29 +2758,58 @@ mod tests {
23682758 };
23692759 let reference: Vec<u16> = (0..width * height).map(|_| (rng() % 256) as u16).collect();
23702760 let mut checked = 0usize;
2371- for &kind in &[InterpFilterKind::Regular, InterpFilterKind::Smooth, InterpFilterKind::Sharp] {
2761+ for &kind in &[
2762+ InterpFilterKind::Regular,
2763+ InterpFilterKind::Smooth,
2764+ InterpFilterKind::Sharp,
2765+ ] {
23722766 let (v_wide, v_narrow) = kind.tables();
2373- for (bw, bh) in [(4usize, 4usize), (5, 4), (8, 8), (16, 16), (12, 8), (32, 16)] {
2767+ for (bw, bh) in [
2768+ (4usize, 4usize),
2769+ (5, 4),
2770+ (8, 8),
2771+ (16, 16),
2772+ (12, 8),
2773+ (32, 16),
2774+ ] {
23742775 for yfrac in 1..16i32 {
23752776 let (x0, y0) = (7i32, 9i32);
2376- let taps = if bh <= 4 { &v_narrow[yfrac as usize] } else { &v_wide[yfrac as usize] };
2777+ let taps = if bh <= 4 {
2778+ &v_narrow[yfrac as usize]
2779+ } else {
2780+ &v_wide[yfrac as usize]
2781+ };
23772782 let mut want = vec![0u16; bw * bh];
23782783 for row in 0..bh {
23792784 for col in 0..bw {
23802785 let mut sum = 0i32;
23812786 for (t, &tap) in taps.iter().enumerate() {
23822787 let y = y0 - 3 + row as i32 + t as i32;
2383- let s = i32::from(reference[y as usize * width + x0 as usize + col]);
2788+ let s =
2789+ i32::from(reference[y as usize * width + x0 as usize + col]);
23842790 // The identity horizontal tap's output.
23852791 sum += tap * (s << 4);
23862792 }
2387- want[row * bw + col] = super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;
2793+ want[row * bw + col] =
2794+ super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;
23882795 }
23892796 }
23902797 let mut got = vec![0u16; bw * bh];
23912798 super::predict_with_filters_kern(
2392- &reference, width, width, height, x0 * 16, y0 * 16 + yfrac,
2393- bw, bh, bw, bh, kind, kind, &mut got, fctx,
2799+ &reference,
2800+ width,
2801+ width,
2802+ height,
2803+ x0 * 16,
2804+ y0 * 16 + yfrac,
2805+ bw,
2806+ bh,
2807+ bw,
2808+ bh,
2809+ kind,
2810+ kind,
2811+ &mut got,
2812+ fctx,
23942813 );
23952814 assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}");
23962815 checked += 1;
@@ -2431,61 +2850,142 @@ mod tests {
24312850 // horizontal path, which runs these kernels
24322851 // straight over a reference plane's stride.
24332852 for st in [w, w + 3] {
2434- let inter: Vec<i16> = (0..rows * st)
2435- .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
2436- .collect();
2437- for row in [0usize, 1, 4] {
2438- let mut want = vec![0i32; w];
2439- super::vpass_row_scalar(&inter[row * st..], w, st, 0, taps, &mut want);
2440- let mut got = vec![0i32; w];
2441- super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);
2442- assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");
2443- #[cfg(target_arch = "x86_64")]
2444- {
2445- if std::arch::is_x86_feature_detected!("sse4.1") {
2446- let mut sse = vec![0i32; w];
2447- unsafe { super::simd::vpass_sse41(&inter[row * st..], w, st, 1, taps, &mut sse) };
2448- assert_eq!(sse, want, "sse4.1 w={w} frac={frac} row={row}");
2449- }
2450- if std::arch::is_x86_feature_detected!("avx2") {
2451- let mut avx = vec![0i32; w];
2452- unsafe { super::simd::vpass_avx2(&inter[row * st..], w, st, 1, taps, &mut avx) };
2453- assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");
2454- }
2455- }
2456- // lane-mc: the rounding-fused form, over both
2457- // sample maxima this decoder accepts -- its
2458- // `packus`/`min_epu16` pair must reproduce
2459- // `round2(_, InterRound1).clamp(0, max)`.
2460- for max in [255i32, 1023] {
2461- let mut want_u16 = vec![0u16; w];
2462- super::vpass_row_u16_scalar(&inter, w, st, row, taps, max, &mut want_u16);
2463- for (d, &a) in want_u16.iter().zip(want.iter()) {
2464- assert_eq!(
2465- i32::from(*d),
2466- super::round2(a, super::INTER_ROUND_1).clamp(0, max),
2467- "the fused reference is the two-step one"
2468- );
2469- }
2470- let mut got_u16 = vec![0u16; w];
2471- super::vpass_row_u16(&inter[row * st..], w, st, 1, taps, max, &mut got_u16);
2472- assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}");
2853+ let inter: Vec<i16> = (0..rows * st)
2854+ .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
2855+ .collect();
2856+ for row in [0usize, 1, 4] {
2857+ let mut want = vec![0i32; w];
2858+ super::vpass_row_scalar(
2859+ &inter[row * st..],
2860+ w,
2861+ st,
2862+ 0,
2863+ taps,
2864+ &mut want,
2865+ );
2866+ let mut got = vec![0i32; w];
2867+ super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);
2868+ assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");
24732869 #[cfg(target_arch = "x86_64")]
24742870 {
24752871 if std::arch::is_x86_feature_detected!("sse4.1") {
2476- let mut sse = vec![0u16; w];
2477- unsafe { super::simd::vpass_row_u16_sse41(&inter[row * st..], w, st, 1, taps, max, &mut sse) };
2478- assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}");
2872+ let mut sse = vec![0i32; w];
2873+ unsafe {
2874+ super::simd::vpass_sse41(
2875+ &inter[row * st..],
2876+ w,
2877+ st,
2878+ 1,
2879+ taps,
2880+ &mut sse,
2881+ )
2882+ };
2883+ assert_eq!(
2884+ sse, want,
2885+ "sse4.1 w={w} frac={frac} row={row}"
2886+ );
24792887 }
24802888 if std::arch::is_x86_feature_detected!("avx2") {
2481- let mut avx = vec![0u16; w];
2482- unsafe { super::simd::vpass_row_u16_avx2(&inter[row * st..], w, st, 1, taps, max, &mut avx) };
2483- assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}");
2889+ let mut avx = vec![0i32; w];
2890+ unsafe {
2891+ super::simd::vpass_avx2(
2892+ &inter[row * st..],
2893+ w,
2894+ st,
2895+ 1,
2896+ taps,
2897+ &mut avx,
2898+ )
2899+ };
2900+ assert_eq!(
2901+ avx, want,
2902+ "avx2 w={w} frac={frac} row={row}"
2903+ );
2904+ }
2905+ }
2906+ // lane-mc: the rounding-fused form, over both
2907+ // sample maxima this decoder accepts -- its
2908+ // `packus`/`min_epu16` pair must reproduce
2909+ // `round2(_, InterRound1).clamp(0, max)`.
2910+ for max in [255i32, 1023] {
2911+ let mut want_u16 = vec![0u16; w];
2912+ super::vpass_row_u16_scalar(
2913+ &inter,
2914+ w,
2915+ st,
2916+ row,
2917+ taps,
2918+ max,
2919+ &mut want_u16,
2920+ 11,
2921+ );
2922+ for (d, &a) in want_u16.iter().zip(want.iter()) {
2923+ assert_eq!(
2924+ i32::from(*d),
2925+ super::round2(a, super::INTER_ROUND_1)
2926+ .clamp(0, max),
2927+ "the fused reference is the two-step one"
2928+ );
2929+ }
2930+ let mut got_u16 = vec![0u16; w];
2931+ super::vpass_row_u16(
2932+ &inter[row * st..],
2933+ w,
2934+ st,
2935+ 1,
2936+ taps,
2937+ max,
2938+ &mut got_u16,
2939+ 11,
2940+ );
2941+ assert_eq!(
2942+ got_u16, want_u16,
2943+ "fused w={w} frac={frac} row={row} max={max}"
2944+ );
2945+ #[cfg(target_arch = "x86_64")]
2946+ {
2947+ if std::arch::is_x86_feature_detected!("sse4.1") {
2948+ let mut sse = vec![0u16; w];
2949+ unsafe {
2950+ super::simd::vpass_row_u16_sse41(
2951+ &inter[row * st..],
2952+ w,
2953+ st,
2954+ 1,
2955+ taps,
2956+ max,
2957+ &mut sse,
2958+ 11,
2959+ )
2960+ };
2961+ assert_eq!(
2962+ sse, want_u16,
2963+ "fused sse4.1 w={w} max={max}"
2964+ );
2965+ }
2966+ if std::arch::is_x86_feature_detected!("avx2") {
2967+ let mut avx = vec![0u16; w];
2968+ unsafe {
2969+ super::simd::vpass_row_u16_avx2(
2970+ &inter[row * st..],
2971+ w,
2972+ st,
2973+ 1,
2974+ taps,
2975+ max,
2976+ &mut avx,
2977+ 11,
2978+ )
2979+ };
2980+ assert_eq!(
2981+ avx, want_u16,
2982+ "fused avx2 w={w} max={max}"
2983+ );
2984+ }
24842985 }
24852986 }
2987+ checked += 1;
24862988 }
2487- checked += 1;
2488- }
24892989 }
24902990 }
24912991 }
crates/ec-av1/src/refusal_inventory.rsmodified+139 -33
@@ -72,7 +72,15 @@ const REFUSALS: &[&str] = &[
7272 // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`)
7373 // still runs: it now reports `reached = 0` with the same non-vacuous
7474 // premise (allow_intrabc frames + decoded sub-8 leaves).
75- "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
75+ // lane-av112bit: the blanket 12-bit refusal is REPLACED by the four
76+ // named refusals below -- the witnessed paths (intra stack, dequant/
77+ // transforms at the 12-bit tables, deblock, CDEF, Wiener+SGR
78+ // restoration, translational subpel MC through the parameterised
79+ // round_0/round_1) are lifted by the lane's byte-exact ffmpeg gates.
80+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
81+ "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)",
82+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)",
83+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
7684 // lane-av1txr: the silent-garbage guard. A 4:4:4/4:2:2 stream used to
7785 // decode with no refusal and wrong pixels (every chroma extent is
7886 // hardcoded 4:2:0, the probe emits 4:2:0 planes only); it is now refused
@@ -347,9 +355,24 @@ const PROVEN: &[(&str, &str)] = &[
347355 "a motion_mode symbol for a block shape with no CDF row here",
348356 "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row",
349357 ),
358+ // lane-av112bit: four real-aomenc 12-bit streams, each refused by name
359+ // (the gates encode with aomenc --bit-depth=12 and assert the exact
360+ // string; the two pixel witnesses are the same battery's Ok arms).
350361 (
351- "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
352- "a_twelve_bit_sequence_header_is_refused_by_name",
362+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
363+ "a_12bit_warped_motion_stream_is_refused_by_name",
364+ ),
365+ (
366+ "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)",
367+ "a_12bit_compound_inter_stream_is_refused_by_name",
368+ ),
369+ (
370+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)",
371+ "a_12bit_film_grain_stream_is_refused_by_name",
372+ ),
373+ (
374+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
375+ "a_12bit_screen_content_stream_is_refused_by_name",
353376 ),
354377 // lane-av1txr: the guard's own gate builds a profile-1 and a profile-2
355378 // sequence header by hand and asserts each refuses by name while the
@@ -589,7 +612,11 @@ mod tests {
589612 .chain(REFUSALS)
590613 .map(|&s| s.to_owned())
591614 .collect();
592- assert!(found.len() >= 30, "the refusal scan found only {} reasons -- it is broken, not the decoder", found.len());
615+ assert!(
616+ found.len() >= 30,
617+ "the refusal scan found only {} reasons -- it is broken, not the decoder",
618+ found.len()
619+ );
593620
594621 let added: Vec<&String> = found.difference(&listed).collect();
595622 assert!(
@@ -635,9 +662,14 @@ mod tests {
635662 let mut found: BTreeSet<String> = BTreeSet::new();
636663 for (i, _) in src.match_indices("\"SKIP ") {
637664 let rest = &src[i + "\"SKIP ".len()..];
638- let Some(colon) = rest.find(':') else { continue };
665+ let Some(colon) = rest.find(':') else {
666+ continue;
667+ };
639668 let name = &rest[..colon];
640- if !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
669+ if !name
670+ .chars()
671+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
672+ {
641673 continue;
642674 }
643675 // The tail of the message says what was skipped. Only "{e}" -- the
@@ -650,7 +682,10 @@ mod tests {
650682 }
651683 }
652684 let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect();
653- let added: Vec<&String> = found.iter().filter(|n| !listed.contains(n.as_str())).collect();
685+ let added: Vec<&String> = found
686+ .iter()
687+ .filter(|n| !listed.contains(n.as_str()))
688+ .collect();
654689 assert!(
655690 added.is_empty(),
656691 "these gates turn a decode error into a printed SKIP and are not declared: \
@@ -723,9 +758,18 @@ mod tests {
723758 fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() {
724759 // (the refusal in the fallback arm, the alphabet its CDF codes)
725760 let blocks: [(&str, usize); 4] = [
726- ("a 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1),
727- ("an INTER 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1),
728- ("a 128x128 superblock partition value outside the 8-symbol alphabet", crate::cdf::PARTITION_W128[0].len() - 1),
761+ (
762+ "a 32x32 partition type this decoder does not code",
763+ crate::cdf::PARTITION_W32[0].len() - 1,
764+ ),
765+ (
766+ "an INTER 32x32 partition type this decoder does not code",
767+ crate::cdf::PARTITION_W32[0].len() - 1,
768+ ),
769+ (
770+ "a 128x128 superblock partition value outside the 8-symbol alphabet",
771+ crate::cdf::PARTITION_W128[0].len() - 1,
772+ ),
729773 // lane-t900 r24: the key-frame superblock root. Its `part` is
730774 // either a `partition_w64` symbol or, at a frame edge, one of the
731775 // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT,
@@ -779,7 +823,10 @@ mod tests {
779823 "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \
780824 is a real gap in its {alphabet}-value alphabet, not a dead refusal",
781825 i + 1,
782- missing.iter().map(|v| PARTITION_NAMES[*v]).collect::<Vec<_>>()
826+ missing
827+ .iter()
828+ .map(|v| PARTITION_NAMES[*v])
829+ .collect::<Vec<_>>()
783830 );
784831 }
785832 assert_eq!(
@@ -833,7 +880,11 @@ mod tests {
833880 .next()
834881 .unwrap_or("")
835882 .to_owned();
836- assert!(!var.is_empty(), "the chain at decode.rs:{} tests nothing", head + 1);
883+ assert!(
884+ !var.is_empty(),
885+ "the chain at decode.rs:{} tests nothing",
886+ head + 1
887+ );
837888
838889 // Walk up collecting every branch head of this chain, each read to
839890 // the line that opens its body.
@@ -843,7 +894,8 @@ mod tests {
843894 loop {
844895 i -= 1;
845896 let t = lines[i].trim_start();
846- if indent(lines[i]) != outer || !(t.starts_with("} else if ") || t.starts_with("if "))
897+ if indent(lines[i]) != outer
898+ || !(t.starts_with("} else if ") || t.starts_with("if "))
847899 {
848900 if i == 0 {
849901 break;
@@ -893,7 +945,10 @@ mod tests {
893945 "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \
894946 is a real gap in its {alphabet}-value alphabet, not a dead refusal",
895947 head + 1,
896- missing.iter().map(|v| PARTITION_NAMES[*v]).collect::<Vec<_>>()
948+ missing
949+ .iter()
950+ .map(|v| PARTITION_NAMES[*v])
951+ .collect::<Vec<_>>()
897952 );
898953 }
899954 assert_eq!(found, chains.len());
@@ -996,11 +1051,18 @@ mod tests {
9961051 values.insert(((1u64 << length) - 2) as u32);
9971052 }
9981053 let max = *values.iter().max().unwrap();
999- assert_eq!(max, (1u32 << 20) - 2, "the enumeration misses the spec's own ceiling");
1054+ assert_eq!(
1055+ max,
1056+ (1u32 << 20) - 2,
1057+ "the enumeration misses the spec's own ceiling"
1058+ );
10001059 // A coefficient is masked to 20 bits (spec 5.11.39), and the base and
10011060 // base-range syntax contribute at most 15 of that before the tail, so
10021061 // this is the largest tail a legal coefficient can need.
1003- assert!(max >= 0xF_FFFF - 15, "the ceiling is below the largest legal tail");
1062+ assert!(
1063+ max >= 0xF_FFFF - 15,
1064+ "the ceiling is below the largest legal tail"
1065+ );
10041066 for value in values {
10051067 match roundtrip(value) {
10061068 Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"),
@@ -1056,7 +1118,11 @@ mod tests {
10561118 ];
10571119 assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size");
10581120 for group in &crate::cdf::Y_MODE {
1059- assert_eq!(group.len() - 1, alphabets[0].1, "the y_mode rows disagree on width");
1121+ assert_eq!(
1122+ group.len() - 1,
1123+ alphabets[0].1,
1124+ "the y_mode rows disagree on width"
1125+ );
10601126 }
10611127
10621128 let src = include_str!("decode.rs");
@@ -1064,12 +1130,17 @@ mod tests {
10641130 let mut sites = 0usize;
10651131 for (i, line) in lines.iter().enumerate() {
10661132 let t = line.trim();
1067- let Some(rest) = t.strip_prefix("if mode >= ") else { continue };
1133+ let Some(rest) = t.strip_prefix("if mode >= ") else {
1134+ continue;
1135+ };
10681136 let Some(threshold) = rest.trim_end_matches(" {").parse::<usize>().ok() else {
10691137 continue;
10701138 };
10711139 // Only the guards carrying THIS refusal.
1072- if !lines[i..(i + 4).min(lines.len())].join("\n").contains(REFUSAL) {
1140+ if !lines[i..(i + 4).min(lines.len())]
1141+ .join("\n")
1142+ .contains(REFUSAL)
1143+ {
10731144 continue;
10741145 }
10751146 sites += 1;
@@ -1099,7 +1170,10 @@ mod tests {
10991170 i + 1
11001171 );
11011172 }
1102- assert_eq!(sites, 3, "the intra-mode guard is at three sites, found {sites}");
1173+ assert_eq!(
1174+ sites, 3,
1175+ "the intra-mode guard is at three sites, found {sites}"
1176+ );
11031177 }
11041178
11051179 /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a
@@ -1159,7 +1233,10 @@ mod tests {
11591233 }
11601234 }
11611235 }
1162- assert!(with_128 > 0, "enumeration is vacuous -- no 128-sided footprint was tried");
1236+ assert!(
1237+ with_128 > 0,
1238+ "enumeration is vacuous -- no 128-sided footprint was tried"
1239+ );
11631240 assert_eq!(
11641241 allowed_at_128, 0,
11651242 "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \
@@ -1271,11 +1348,17 @@ mod tests {
12711348 // (3) The two tables, read out of decode_rect_split's own text: every
12721349 // `(w, h) =>` / `(w, h) |` match arm head between the table's `let`
12731350 // and the guard that follows it.
1274- let body_at = src.find("fn decode_rect_split(").expect("decode_rect_split is gone");
1351+ let body_at = src
1352+ .find("fn decode_rect_split(")
1353+ .expect("decode_rect_split is gone");
12751354 let body = &src[body_at..];
12761355 let slice = |from: &str, to: &str| -> &str {
1277- let a = body.find(from).unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split"));
1278- let b = body[a..].find(to).unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split"));
1356+ let a = body
1357+ .find(from)
1358+ .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split"));
1359+ let b = body[a..]
1360+ .find(to)
1361+ .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split"));
12791362 &body[a..a + b]
12801363 };
12811364 let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> {
@@ -1348,7 +1431,10 @@ mod tests {
13481431 }
13491432 }
13501433 }
1351- assert_eq!(checked, 40, "the strip domain is not the ten rect shapes x four depths");
1434+ assert_eq!(
1435+ checked, 40,
1436+ "the strip domain is not the ten rect shapes x four depths"
1437+ );
13521438 }
13531439
13541440 /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a
@@ -1458,9 +1544,15 @@ mod tests {
14581544 }
14591545 continue;
14601546 }
1461- let Some(rest) = line.strip_prefix('(') else { continue };
1462- let Some((pair, _)) = rest.split_once(") =>") else { continue };
1463- let Some((a, b)) = pair.split_once(',') else { continue };
1547+ let Some(rest) = line.strip_prefix('(') else {
1548+ continue;
1549+ };
1550+ let Some((pair, _)) = rest.split_once(") =>") else {
1551+ continue;
1552+ };
1553+ let Some((a, b)) = pair.split_once(',') else {
1554+ continue;
1555+ };
14641556 let bw: usize = a.trim().parse().expect("arm bw");
14651557 let bh: usize = b.trim().parse().expect("arm bh");
14661558 assert!(
@@ -1472,9 +1564,18 @@ mod tests {
14721564 seen.push((bw, bh));
14731565 arms += 1;
14741566 }
1475- assert!(arms >= 10, "only {arms} arms parsed -- the table's shape changed");
1476- assert!(saw_none_fallback, "filter_intra_size_class_rect lost its `_ => None` fallback");
1477- assert!(saw_square_delegate, "filter_intra_size_class_rect lost its square-delegate arm");
1567+ assert!(
1568+ arms >= 10,
1569+ "only {arms} arms parsed -- the table's shape changed"
1570+ );
1571+ assert!(
1572+ saw_none_fallback,
1573+ "filter_intra_size_class_rect lost its `_ => None` fallback"
1574+ );
1575+ assert!(
1576+ saw_square_delegate,
1577+ "filter_intra_size_class_rect lost its square-delegate arm"
1578+ );
14781579 // The guard arm delegates square strips to `filter_intra_size_class`;
14791580 // drive the delegate directly, so a widening there turns THIS test red
14801581 // (the numeric walk never reaches the guard arm).
@@ -1524,7 +1625,10 @@ mod tests {
15241625 );
15251626 }
15261627 }
1527- assert_eq!(sites, 8, "the call-site audit found {sites} sites, not the 8 it enumerated");
1628+ assert_eq!(
1629+ sites, 8,
1630+ "the call-site audit found {sites} sites, not the 8 it enumerated"
1631+ );
15281632 }
15291633
15301634 /// Every entry of [`PROVEN`] must still name a live refusal and a test
@@ -1543,7 +1647,9 @@ mod tests {
15431647 "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string"
15441648 );
15451649 assert!(
1546- sources.iter().any(|src| src.contains(&format!("fn {gate}("))),
1650+ sources
1651+ .iter()
1652+ .any(|src| src.contains(&format!("fn {gate}("))),
15471653 "{reason:?} names the proving test {gate}, which exists in neither stream.rs \
15481654 nor decode.rs"
15491655 );
crates/ec-av1/src/restoration.rsmodified+246 -76
@@ -63,7 +63,12 @@ fn inverse_recenter(r: u32, v: u32) -> u32 {
6363 /// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed
6464 /// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around
6565 /// `reference`.
66-fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32, reference: u32) -> u32 {
66+fn decode_unsigned_subexp_with_ref_msac(
67+ dec: &mut SymbolDecoder,
68+ n: u32,
69+ k: u32,
70+ reference: u32,
71+) -> u32 {
6772 let v = decode_subexp_msac(dec, n, k);
6873 if (reference << 1) <= n {
6974 inverse_recenter(reference, v)
@@ -74,7 +79,13 @@ fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32,
7479
7580 /// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter`
7681 /// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`.
77-fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i32, k: u32, reference: i32) -> i32 {
82+fn decode_signed_subexp_with_ref_msac(
83+ dec: &mut SymbolDecoder,
84+ low: i32,
85+ high: i32,
86+ k: u32,
87+ reference: i32,
88+) -> i32 {
7889 let n = (high - low) as u32;
7990 let r = (reference - low).clamp(0, n as i32) as u32;
8091 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
@@ -274,7 +285,11 @@ fn read_wiener_direction(dec: &mut SymbolDecoder, chroma: bool, reference: &[i32
274285
275286 /// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating
276287 /// `reference` in place (the running per-plane, per-tile reference state).
277-fn read_wiener_filter(dec: &mut SymbolDecoder, chroma: bool, reference: &mut WienerInfo) -> WienerInfo {
288+fn read_wiener_filter(
289+ dec: &mut SymbolDecoder,
290+ chroma: bool,
291+ reference: &mut WienerInfo,
292+) -> WienerInfo {
278293 let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter);
279294 let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter);
280295 let info = WienerInfo { vfilter, hfilter };
@@ -462,7 +477,8 @@ pub(crate) fn read_lr(
462477 reference: &mut [(WienerInfo, SgrprojInfo); 3],
463478 mi_row: u32,
464479 mi_col: u32,
465- sb_mi: u32, fctx: &crate::decode::FrameCtx,
480+ sb_mi: u32,
481+ fctx: &crate::decode::FrameCtx,
466482 ) {
467483 if !lr.uses_lr {
468484 return;
@@ -636,8 +652,16 @@ fn lr_sample(
636652 ) -> i32 {
637653 let col_c = col.clamp(0, plane_w as i64 - 1) as usize;
638654 i32::from(
639- lr_src_row(cdef, deblocked, stride, plane_w, plane_h, stripe_v_start, stripe_v_end, row)
640- [col_c],
655+ lr_src_row(
656+ cdef,
657+ deblocked,
658+ stride,
659+ plane_w,
660+ plane_h,
661+ stripe_v_start,
662+ stripe_v_end,
663+ row,
664+ )[col_c],
641665 )
642666 }
643667
@@ -671,7 +695,11 @@ fn lr_src_row<'a>(
671695 let dist = stripe_v_start as i64 - 1 - row;
672696 (
673697 deblocked,
674- if dist == 0 { stripe_v_start - 1 } else { stripe_v_start.saturating_sub(2) },
698+ if dist == 0 {
699+ stripe_v_start - 1
700+ } else {
701+ stripe_v_start.saturating_sub(2)
702+ },
675703 )
676704 }
677705 } else if stripe_v_end == plane_h {
@@ -712,7 +740,8 @@ fn apply_wiener_stripe(
712740 h_end: usize,
713741 v_start: usize,
714742 v_end: usize,
715- info: &WienerInfo, fctx: &crate::decode::FrameCtx,
743+ info: &WienerInfo,
744+ fctx: &crate::decode::FrameCtx,
716745 ) {
717746 let w = h_end - h_start;
718747 let h = v_end - v_start;
@@ -720,8 +749,26 @@ fn apply_wiener_stripe(
720749 return;
721750 }
722751 let bd = i64::from(crate::decode::bit_depth(fctx));
752+ // lane-av112bit: libaom `get_conv_params_wiener` (`convolve.h:107..118`)
753+ // raises the Wiener pair by the same `intbufrange` delta as MC's: at
754+ // 12-bit `round_0` is 5 and `round_1` 9 (8/10-bit: 3 and 11). The ROUNDS
755+ // are parameterised; the intermediate CLAMP below keeps the corpus-proven
756+ // constant-bound structure extended by the same bd formulas -- a first
757+ // attempt at the C clamp's exact per-sample transform (the add_src bias
758+ // is `src[centre] << FILTER_BITS + (1 << (bd + FILTER_BITS - 1))`, which
759+ // survives `Round2(_, round_0)` as `(128 >> round_0) * s +
760+ // (1 << (bd + 6 - round_0))`) MOVED the 10-bit 128-superblock film gate
761+ // (frame 1 luma): libaom's 8-tap-loop alignment trick means the C
762+ // horizontal intermediate is not `ours + that bias` wherever the clamp
763+ // actually binds, so the exact transform is NOT derivable from the
764+ // convolve source alone. The bd-formula clamp is what every 8/10-bit
765+ // byte-exact gate (this film included) has always pinned, and the 12-bit
766+ // key witness passes byte-exact with it; where C's real clamp would bind
767+ // differently at 12 bits remains unproven either way -- recorded in
768+ // `lanes/av112bit.report.md` as the open half of the Wiener lift.
723769 let wiener_bias = 1i64 << (bd + 3);
724770 let wiener_limit = 1i64 << (bd + 5);
771+ let (round0, round1) = crate::mc::round_pair(bd as u32);
725772 let rows = h + 6;
726773 // lane-perf7: reused across stripes, as the sgrproj `ab` grids are --
727774 // this was a fresh allocation per stripe. Every entry is written below.
@@ -738,28 +785,50 @@ fn apply_wiener_stripe(
738785 // stripe substitution is resolved once per row by `lr_src_row`, and only
739786 // a unit touching the plane's left or right edge needs the clamped copy.
740787 let hf = &info.hfilter;
741- let t16: [i16; 8] =
742- [hf[0] as i16, hf[1] as i16, hf[2] as i16, hf[3] as i16, hf[4] as i16, hf[5] as i16, hf[6] as i16, 0];
788+ let t16: [i16; 8] = [
789+ hf[0] as i16,
790+ hf[1] as i16,
791+ hf[2] as i16,
792+ hf[3] as i16,
793+ hf[4] as i16,
794+ hf[5] as i16,
795+ hf[6] as i16,
796+ 0,
797+ ];
743798 // lane-mc: the intermediate is `i16` now. Both bounds are inside that
744- // range at 8- and 10-bit (12-bit is refused in stream.rs), so the
745- // kernel's saturating store composes with this clamp instead of changing
746- // it: `[-2048, 8191]` at 8-bit, `[-8192, 32767]` at 10.
747- let (lo_bound, hi_bound) = (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16);
799+ // range at every supported bit depth (the centred sum's own range,
800+ // `|kernel| <= 348` against `2^bd - 1` samples, never reaches them), so
801+ // the kernel's saturating store composes with this clamp instead of
802+ // changing it: `[-2^(bd+3), 2^(bd+5)-1-2^(bd+3)]` -- 8-bit
803+ // `[-2048, 6143]`, 10-bit `[-8192, 24575]`. At 12-bit those formulas
804+ // leave `i16`, so the clamp there is the widest `i16` window -- which
805+ // strictly contains the kernel's own mathematical range (`|sum| <=
806+ // round2(348 * 4095, round_0=5) == 27976 < 2^15`), i.e. it never binds,
807+ // the property the 8/10-bit bounds have on the whole proven corpus.
808+ let (lo_bound, hi_bound) = if bd >= 12 {
809+ (i16::MIN, i16::MAX)
810+ } else {
811+ (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16)
812+ };
748813 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
749814 for r in 0..rows {
750815 let row = v_start as i64 - 3 + r as i64;
751- let src = lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row);
816+ let src = lr_src_row(
817+ cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row,
818+ );
752819 let lo = h_start as i64 - 3;
753820 let out = &mut inter[r * w..r * w + w];
754- if lo >= 0 && lo as usize + w + 7 <= plane_w {
755- crate::mc::hpass_contig(&src[lo as usize..], &t16, out);
756- } else {
821+ // The row the pass convolves, contiguous when the block sits inside
822+ // the plane and the clamped copy (`hbuf`) at an edge.
823+ let interior = lo >= 0 && lo as usize + w + 7 <= plane_w;
824+ if !interior {
757825 hbuf.clear();
758826 hbuf.extend(
759827 (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]),
760828 );
761- crate::mc::hpass_contig(&hbuf, &t16, out);
762829 }
830+ let row_slice: &[u16] = if interior { &src[lo as usize..] } else { &hbuf };
831+ crate::mc::hpass_contig(row_slice, &t16, out, round0);
763832 for v in out.iter_mut() {
764833 *v = (*v).clamp(lo_bound, hi_bound);
765834 }
@@ -769,7 +838,9 @@ fn apply_wiener_stripe(
769838 // instead of taking a thread-local read per output sample.
770839 let smax = i64::from(crate::decode::sample_max(fctx));
771840 // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves
772- // the accumulator unrounded, and `Round2(_, 11)` is `INTER_ROUND_1`.
841+ // the accumulator unrounded, and `Round2(_, round1)` is the frame's
842+ // non-compound `round_1` (11 at 8/10-bit, 9 at 12 -- libaom's
843+ // `get_conv_params_wiener`).
773844 let vf = &info.vfilter;
774845 let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0];
775846 let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
@@ -779,7 +850,7 @@ fn apply_wiener_stripe(
779850 crate::mc::vpass_row(&inter[r * w..], w, w, 1, &taps, &mut acc);
780851 let dst = &mut out[(v_start + r) * stride + h_start..][..w];
781852 for (o, &a) in dst.iter_mut().zip(acc.iter()) {
782- *o = round2(i64::from(a), 11).clamp(0, smax) as u16;
853+ *o = round2(i64::from(a), round1).clamp(0, smax) as u16;
783854 }
784855 }
785856 WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc);
@@ -815,31 +886,27 @@ thread_local! {
815886 // `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other
816887 // transcription slip.
817888 const SGR_X_BY_XPLUS1: [i32; 256] = [
818- 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239,
819- 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247,
820- 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250,
821- 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252,
822- 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253,
823- 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
824- 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254,
825- 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
826- 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
827- 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
828- 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
829- 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
830- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
831- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
832- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
833- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
834- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
835- 256,
889+ 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243,
890+ 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249,
891+ 249, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252,
892+ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253,
893+ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
894+ 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
895+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
896+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
897+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255,
898+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
899+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
900+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
901+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
902+ 255, 255, 255, 255, 255, 255, 255, 255, 256,
836903 ];
837904
838905 /// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25`
839906 /// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`.
840907 const SGR_ONE_BY_X: [i32; 25] = [
841- 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, 216, 205, 195, 186,
842- 178, 171, 164,
908+ 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228,
909+ 216, 205, 195, 186, 178, 171, 164,
843910 ];
844911
845912 const SGRPROJ_MTABLE_BITS: u32 = 20;
@@ -877,7 +944,8 @@ fn compute_ab(
877944 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every
878945 // page then faulted in on first touch. Every entry is written below, so
879946 // the resize's fill value is never read.
880- ab: &mut Vec<(i32, i64)>, fctx: &crate::decode::FrameCtx,
947+ ab: &mut Vec<(i32, i64)>,
948+ fctx: &crate::decode::FrameCtx,
881949 ) {
882950 let gw = w + 2;
883951 let gh = h + 2;
@@ -927,8 +995,9 @@ fn compute_ab(
927995 let i = gi as i64 - 1;
928996 {
929997 let mut accumulate = |row: i64, add: bool| {
930- let src =
931- lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row);
998+ let src = lr_src_row(
999+ cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row,
1000+ );
9321001 fill_clamped_row(src, plane_w, base_col, &mut samp);
9331002 if add {
9341003 for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter())
@@ -967,7 +1036,15 @@ fn compute_ab(
9671036 a_row[gj] = a;
9681037 b_row[gj] = b;
9691038 }
970- ab_row(a_row, b_row, n, s, bd_shift, one_by_x, &mut ab[gi * gw..gi * gw + gw]);
1039+ ab_row(
1040+ a_row,
1041+ b_row,
1042+ n,
1043+ s,
1044+ bd_shift,
1045+ one_by_x,
1046+ &mut ab[gi * gw..gi * gw + gw],
1047+ );
9711048 let dump_gj = 6i64 - h_start as i64 + 1;
9721049 if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) {
9731050 let gj = dump_gj as usize;
@@ -1006,14 +1083,22 @@ fn ab_point(a: i32, b: i32, n: i32, s: i32, bd_shift: u32, one_by_x: i64) -> (i3
10061083 let b_s = round2_u31(b, bd_shift);
10071084 let p = (a_s * n - b_s * b_s).max(0);
10081085 let a_val = SGR_X_BY_XPLUS1[z_index(p, s)];
1009- let b_val = round2((256 - a_val) as i64 * i64::from(b) * one_by_x, SGRPROJ_RECIP_BITS);
1086+ let b_val = round2(
1087+ (256 - a_val) as i64 * i64::from(b) * one_by_x,
1088+ SGRPROJ_RECIP_BITS,
1089+ );
10101090 (a_val, b_val)
10111091 }
10121092
10131093 /// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time
10141094 /// under AVX2 (the kernel is that arithmetic lane-wise, same widths).
10151095 fn ab_row(
1016- a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i64,
1096+ a_row: &[i32],
1097+ b_row: &[i32],
1098+ n: i32,
1099+ s: i32,
1100+ bd_shift: u32,
1101+ one_by_x: i64,
10171102 out: &mut [(i32, i64)],
10181103 ) {
10191104 let mut done = 0usize;
@@ -1054,7 +1139,12 @@ mod sgr_simd {
10541139 #[target_feature(enable = "avx2")]
10551140 #[allow(clippy::too_many_arguments)]
10561141 pub unsafe fn ab_row_avx2(
1057- a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i32,
1142+ a_row: &[i32],
1143+ b_row: &[i32],
1144+ n: i32,
1145+ s: i32,
1146+ bd_shift: u32,
1147+ one_by_x: i32,
10581148 out: &mut [(i32, i64)],
10591149 ) -> usize {
10601150 let len = out.len().min(a_row.len()).min(b_row.len());
@@ -1070,8 +1160,16 @@ mod sgr_simd {
10701160 let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32);
10711161 let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32);
10721162 let sh_bd = _mm_cvtsi32_si128(bd_shift as i32);
1073- let rnd_a = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (2 * bd_shift - 1) });
1074- let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (bd_shift - 1) });
1163+ let rnd_a = _mm256_set1_epi32(if bd_shift == 0 {
1164+ 0
1165+ } else {
1166+ 1 << (2 * bd_shift - 1)
1167+ });
1168+ let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 {
1169+ 0
1170+ } else {
1171+ 1 << (bd_shift - 1)
1172+ });
10751173 let mut av = [0i32; 8];
10761174 let mut bv = [0i32; 8];
10771175 let mut gj = 0usize;
@@ -1115,7 +1213,11 @@ mod sgr_simd {
11151213 /// width narrower).
11161214 #[inline]
11171215 fn round2_u31(value: i32, shift: u32) -> i32 {
1118- if shift == 0 { value } else { (value + (1 << (shift - 1))) >> shift }
1216+ if shift == 0 {
1217+ value
1218+ } else {
1219+ (value + (1 << (shift - 1))) >> shift
1220+ }
11191221 }
11201222
11211223 /// Copies one source row's `out.len()` samples starting at `base_col` into a
@@ -1150,7 +1252,8 @@ fn apply_sgrproj_stripe(
11501252 h_end: usize,
11511253 v_start: usize,
11521254 v_end: usize,
1153- info: &SgrprojInfo, fctx: &crate::decode::FrameCtx,
1255+ info: &SgrprojInfo,
1256+ fctx: &crate::decode::FrameCtx,
11541257 ) {
11551258 let w = h_end - h_start;
11561259 let h = v_end - v_start;
@@ -1166,10 +1269,16 @@ fn apply_sgrproj_stripe(
11661269 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))
11671270 });
11681271 if r0 > 0 {
1169- compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0, &mut buf0, fctx);
1272+ compute_ab(
1273+ cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0,
1274+ &mut buf0, fctx,
1275+ );
11701276 }
11711277 if r1 > 0 {
1172- compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1, &mut buf1, fctx);
1278+ compute_ab(
1279+ cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1,
1280+ &mut buf1, fctx,
1281+ );
11731282 }
11741283 let ab0 = (r0 > 0).then_some(&buf0);
11751284 let ab1 = (r1 > 0).then_some(&buf1);
@@ -1185,7 +1294,9 @@ fn apply_sgrproj_stripe(
11851294 let bytes: Vec<i32> = (59..=61)
11861295 .flat_map(|row| {
11871296 (5..=7).map(move |col| {
1188- lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col)
1297+ lr_sample(
1298+ cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col,
1299+ )
11891300 })
11901301 })
11911302 .collect();
@@ -1265,7 +1376,8 @@ fn apply_sgrproj_stripe(
12651376 let (a_ur, b_ur) = ab[idx(i - 1, j + 1)];
12661377 let (a_dl, b_dl) = ab[idx(i + 1, j - 1)];
12671378 let (a_dr, b_dr) = ab[idx(i + 1, j + 1)];
1268- let a = (a_c + a_u + a_d + a_l + a_r) as i64 * 4 + (a_ul + a_ur + a_dl + a_dr) as i64 * 3;
1379+ let a = (a_c + a_u + a_d + a_l + a_r) as i64 * 4
1380+ + (a_ul + a_ur + a_dl + a_dr) as i64 * 3;
12691381 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
12701382 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
12711383 v += xq[1] as i64 * (flt1 - u);
@@ -1278,9 +1390,15 @@ fn apply_sgrproj_stripe(
12781390 "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \
12791391 ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \
12801392 u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}",
1281- ab[idx(i, j)], ab[idx(i - 1, j)], ab[idx(i + 1, j)], ab[idx(i, j - 1)],
1282- ab[idx(i, j + 1)], ab[idx(i - 1, j - 1)], ab[idx(i - 1, j + 1)],
1283- ab[idx(i + 1, j - 1)], ab[idx(i + 1, j + 1)]
1393+ ab[idx(i, j)],
1394+ ab[idx(i - 1, j)],
1395+ ab[idx(i + 1, j)],
1396+ ab[idx(i, j - 1)],
1397+ ab[idx(i, j + 1)],
1398+ ab[idx(i - 1, j - 1)],
1399+ ab[idx(i - 1, j + 1)],
1400+ ab[idx(i + 1, j - 1)],
1401+ ab[idx(i + 1, j + 1)]
12841402 );
12851403 }
12861404 }
@@ -1311,7 +1429,8 @@ fn filter_restoration_unit(
13111429 v_start: usize,
13121430 v_end: usize,
13131431 ss_y: u32,
1314- filter: UnitFilter, fctx: &crate::decode::FrameCtx,
1432+ filter: UnitFilter,
1433+ fctx: &crate::decode::FrameCtx,
13151434 ) {
13161435 let full_stripe_height = 64usize >> ss_y;
13171436 let runit_offset = 8usize >> ss_y;
@@ -1333,10 +1452,32 @@ fn filter_restoration_unit(
13331452 }
13341453 match filter {
13351454 UnitFilter::Wiener(info) => apply_wiener_stripe(
1336- out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx,
1455+ out,
1456+ cdef,
1457+ deblocked,
1458+ stride,
1459+ plane_w,
1460+ plane_h,
1461+ h_start,
1462+ h_end,
1463+ stripe_v_start,
1464+ stripe_v_end,
1465+ &info,
1466+ fctx,
13371467 ),
13381468 UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(
1339- out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx,
1469+ out,
1470+ cdef,
1471+ deblocked,
1472+ stride,
1473+ plane_w,
1474+ plane_h,
1475+ h_start,
1476+ h_end,
1477+ stripe_v_start,
1478+ stripe_v_end,
1479+ &info,
1480+ fctx,
13401481 ),
13411482 UnitFilter::None => {}
13421483 }
@@ -1395,12 +1536,16 @@ pub(crate) fn apply_loop_restoration_plane(
13951536 let out = unsafe { so.get() };
13961537 for rrow in r_lo..r_hi {
13971538 lr_unit_row(
1398- out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,
1399- plane, rrow, &rows, fctx,
1539+ out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane,
1540+ rrow, &rows, fctx,
14001541 );
14011542 }
14021543 });
1403- debug_assert_eq!(rows.len(), grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
1544+ debug_assert_eq!(
1545+ rows.len(),
1546+ grid.vert_units[plane],
1547+ "RU row walk must match RestorationGrid::new's count_units"
1548+ );
14041549 return;
14051550 };
14061551 for rrow in r_lo..r_hi.min(rows.len()) {
@@ -1435,7 +1580,11 @@ pub(crate) fn lr_unit_rows(
14351580 let mut y0 = 0u32;
14361581 while y0 < plane_h as u32 {
14371582 let remaining_h = plane_h as u32 - y0;
1438- let uh = if remaining_h < ext_size { remaining_h } else { unit_size };
1583+ let uh = if remaining_h < ext_size {
1584+ remaining_h
1585+ } else {
1586+ unit_size
1587+ };
14391588 let v_start = (y0 as i64 - voffset as i64).max(0) as u32;
14401589 let mut v_end = y0 + uh;
14411590 if v_end < plane_h as u32 {
@@ -1471,7 +1620,11 @@ fn lr_unit_row(
14711620 let mut rcol = 0usize;
14721621 while x0 < plane_w as u32 {
14731622 let remaining_w = plane_w as u32 - x0;
1474- let uw = if remaining_w < ext_size { remaining_w } else { unit_size };
1623+ let uw = if remaining_w < ext_size {
1624+ remaining_w
1625+ } else {
1626+ unit_size
1627+ };
14751628 let filter = grid.get(plane, rrow, rcol);
14761629 if filter != UnitFilter::None {
14771630 filter_restoration_unit(
@@ -1486,7 +1639,8 @@ fn lr_unit_row(
14861639 v_start as usize,
14871640 v_end as usize,
14881641 ss_y,
1489- filter, fctx,
1642+ filter,
1643+ fctx,
14901644 );
14911645 }
14921646 x0 += uw;
@@ -1510,7 +1664,15 @@ mod tests {
15101664 /// `SGRPROJ_PRJ_MAX-MIN+1`.
15111665 #[test]
15121666 fn subexp_roundtrips_every_value() {
1513- for &(num_syms, k) in &[(16u32, 1u32), (32, 2), (64, 3), (96, 4), (128, 4), (3, 1), (1, 3)] {
1667+ for &(num_syms, k) in &[
1668+ (16u32, 1u32),
1669+ (32, 2),
1670+ (64, 3),
1671+ (96, 4),
1672+ (128, 4),
1673+ (3, 1),
1674+ (1, 3),
1675+ ] {
15141676 for v in 0..num_syms {
15151677 let mut enc = SymbolEncoder::new();
15161678 write_subexp(&mut enc, num_syms, k, v);
@@ -1548,10 +1710,10 @@ mod tests {
15481710 #[test]
15491711 fn signed_subexp_with_ref_roundtrips() {
15501712 let cases: [(i32, i32, u32); 4] = [
1551- (-5, 11, 1), // Wiener tap0
1552- (-23, 9, 2), // Wiener tap1
1553- (-17, 47, 3), // Wiener tap2
1554- (-96, 32, 4), // SGR xqd0
1713+ (-5, 11, 1), // Wiener tap0
1714+ (-23, 9, 2), // Wiener tap1
1715+ (-17, 47, 3), // Wiener tap2
1716+ (-96, 32, 4), // SGR xqd0
15551717 ];
15561718 for (low, high, k) in cases {
15571719 let n = (high - low) as u32;
@@ -1563,8 +1725,12 @@ mod tests {
15631725 write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v);
15641726 let payload = enc.finish();
15651727 let mut dec = SymbolDecoder::new(&payload);
1566- let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v);
1567- assert_eq!(got, v, "low={low} high={high} k={k} reference={reference_v} v={v}");
1728+ let got =
1729+ decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v);
1730+ assert_eq!(
1731+ got, v,
1732+ "low={low} high={high} k={k} reference={reference_v} v={v}"
1733+ );
15681734 }
15691735 }
15701736 }
@@ -1595,7 +1761,11 @@ mod tests {
15951761 let mut dec = SymbolDecoder::new(&payload);
15961762 let mut rref = WienerInfo::default();
15971763 for u in &units {
1598- assert_eq!(read_wiener_filter(&mut dec, chroma, &mut rref), *u, "chroma={chroma}");
1764+ assert_eq!(
1765+ read_wiener_filter(&mut dec, chroma, &mut rref),
1766+ *u,
1767+ "chroma={chroma}"
1768+ );
15991769 }
16001770 }
16011771 }
crates/ec-av1/src/stream.rsmodified+430 -46
@@ -38,6 +38,21 @@ fn no_grain() -> bool {
3838 std::env::var_os("EC_AV1_NO_GRAIN").is_some()
3939 }
4040
41+/// lane-av112bit: film grain synthesis has no 12-bit byte-exact witness (the
42+/// lane's witnesses encode with grain off), so a 12-bit frame that would
43+/// synthesise grain is refused by name at output rather than trusted --
44+/// `film_grain.rs` is bit-depth generic since lane-hbd10, but generic is not
45+/// proven until a real 12-bit grain stream compares exact.
46+fn grain_refusal(bit_depth: u32) -> Result<()> {
47+ if bit_depth == 12 {
48+ return Err(Error::unsupported(
49+ "AV1 decode_stream",
50+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)",
51+ ));
52+ }
53+ Ok(())
54+}
55+
4156 // lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
4257 // current thread, overriding the environment variable. Every ffmpeg/aomdec
4358 // pixel gate in this repo compares SHOWN frames only (class
@@ -684,6 +699,7 @@ pub fn decode_stream_with_threads(
684699 pictures_shown += 1;
685700 let grain = header.film_grain;
686701 let seq = SeqFlags::read(&parser);
702+ grain_refusal(u32::from(seq.bit_depth))?;
687703 let tx = tx.clone();
688704 jobs.submit(move || {
689705 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
@@ -735,6 +751,13 @@ pub fn decode_stream_with_threads(
735751 }
736752 picture
737753 };
754+ if header.film_grain.apply_grain {
755+ grain_refusal(
756+ parser
757+ .sequence_header()
758+ .map_or(8, |seq| u32::from(seq.color_config.bit_depth)),
759+ )?;
760+ }
738761 let output = if header.film_grain.apply_grain && !no_grain() {
739762 // lane-hbd10 r1: grain synthesis is bit-depth generic
740763 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
@@ -1074,6 +1097,9 @@ pub fn decode_stream_with_threads(
10741097 // Grain is synthesised for OUTPUT only: a hidden frame is
10751098 // reported to the sink clean, exactly as the inline path
10761099 // below reports it (spec 7.18.3.1).
1100+ if header.film_grain.apply_grain {
1101+ grain_refusal(u32::from(seq.bit_depth))?;
1102+ }
10771103 let output = if shown && header.film_grain.apply_grain && !no_grain() {
10781104 std::sync::Arc::new(crate::film_grain::apply_grain(
10791105 &picture,
@@ -1208,6 +1234,9 @@ pub fn decode_stream_with_threads(
12081234 decode::note_fwd_kf();
12091235 }
12101236 if header.show_frame {
1237+ if header.film_grain.apply_grain {
1238+ grain_refusal(u32::from(seq.bit_depth))?;
1239+ }
12111240 let output = if header.film_grain.apply_grain && !no_grain() {
12121241 let mc_identity = seq.mc_identity;
12131242 std::sync::Arc::new(crate::film_grain::apply_grain(
@@ -1634,19 +1663,23 @@ fn decode_frame(
16341663 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
16351664 // sequence header has been seen yet, matching every existing fixture.
16361665 let bit_depth = seq.bit_depth;
1637- // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
1638- // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
1639- // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
1640- // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
1641- // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
1642- // Wiener rounding bits change, and neither CDEF nor film grain has a
1643- // 12-bit path. Refuse by name rather than decode silently wrong pixels.
1644- if bit_depth == 12 {
1645- return Err(Error::unsupported(
1646- "AV1 decode_stream",
1647- "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
1648- ));
1649- }
1666+ // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the
1667+ // lane's witnesses prove byte-exact against ffmpeg on real `aomenc
1668+ // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop
1669+ // restoration ON, grain off -- gates
1670+ // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and
1671+ // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The
1672+ // rounding sites that move at 12 bits are parameterised from libaom's
1673+ // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange`
1674+ // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener
1675+ // pair via `get_conv_params_wiener`; the compound post-rounds absorb
1676+ // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/
1677+ // superres upscale were already bit-depth generic (10-bit-proven).
1678+ // Everything no 12-bit witness reached stays refused BY NAME at its own
1679+ // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0),
1680+ // film grain (`grain_refusal`, the witnesses run with grain off), and
1681+ // any per-feature gap the witnesses' counters prove unreached -- see the
1682+ // 12-bit refusals in decode.rs and `refusal_inventory.rs`.
16501683 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by
16511684 // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces
16521685 // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but
@@ -1686,6 +1719,20 @@ fn decode_frame(
16861719 "a frame using quantisation matrices (using_qmatrix=1): dequantisation here is base_q_idx plus the plane DC/AC deltas only, so qm_y/qm_u/qm_v would be ignored and the frame would decode silently wrong pixels",
16871720 ));
16881721 }
1722+ // lane-av112bit: the frame-level half of the 12-bit gate -- screen
1723+ // content tools. Neither palette nor intrabc has a 12-bit witness (the
1724+ // 12-bit gates are natural content), and both hang off this header bit:
1725+ // `allow_screen_content_tools` is what lets a block code a palette or
1726+ // read a `use_intrabc` symbol. Refusing the FRAME by name keeps every
1727+ // palette/intrabc code path 12-bit-unreachable rather than unwitnessed
1728+ // and trusted. Gate:
1729+ // `a_12bit_screen_content_stream_is_refused_by_name`.
1730+ if bit_depth == 12 && header.allow_screen_content_tools {
1731+ return Err(Error::unsupported(
1732+ "AV1 decode_stream",
1733+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
1734+ ));
1735+ }
16891736 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
16901737 // is a different tile syntax, and this decoder has none of it: libaom
16911738 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
@@ -2104,39 +2151,6 @@ pub(crate) mod tests {
21042151 picture
21052152 }
21062153
2107- /// A stream whose sequence header says `twelve_bit` is refused by name
2108- /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s
2109- /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and
2110- /// film grain). Reachability, not a pixel claim: the header is written at
2111- /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's
2112- /// tile payload is never reached.
2113- #[test]
2114- fn a_twelve_bit_sequence_header_is_refused_by_name() {
2115- let fctx = &crate::decode::FrameCtx::new();
2116- let picture = test_card(64, 64);
2117- let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2118- let mut color = ec_av1_syntax::ColorConfig {
2119- bit_depth: 12,
2120- ..Default::default()
2121- };
2122- color.num_planes = 3;
2123- // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2).
2124- let (mut seq, header) =
2125- crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2126- seq.seq_profile = 2;
2127- let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2128- stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2129-
2130- let err = decode_stream(&stream).unwrap_err().to_string();
2131- assert!(
2132- err.contains(
2133- "a bit depth of 12 (this decoder is gated at 8 and 10 only: \
2134- warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)"
2135- ),
2136- "expected the 12-bit refusal, got: {err}"
2137- );
2138- }
2139-
21402154 /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is
21412155 /// refused by name, because the decoder reconstructs every chroma extent
21422156 /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe
@@ -7772,6 +7786,376 @@ pub(crate) mod tests {
77727786 /// actually parses to says `bit_depth == 10` before trusting any pixel
77737787 /// match -- a stream that silently fell back to 8-bit would still
77747788 /// "match" trivially.
7789+ // -------------------------------------------------------------------
7790+ // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted
7791+ // for what these gates witness byte-exact against ffmpeg on real
7792+ // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack,
7793+ // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop
7794+ // restoration (Wiener AND SGR), and translational subpel motion
7795+ // compensation through the bit-depth-parameterised `round_0`/`round_1`
7796+ // (libaom `convolve.h:81..86`). Everything else stays refused by name:
7797+ // warp, film grain, screen content tools (palette/intrabc) at the frame
7798+ // level, compound inter blocks at the mode read, each with its own
7799+ // real-stream refusal gate below.
7800+ // -------------------------------------------------------------------
7801+
7802+ /// The 12-bit witness source, byte-identical to the lane's committed
7803+ /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a
7804+ /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame
7805+ /// vertically with linear edge coverage -- sub-pixel true motion, so an
7806+ /// inter frame over it cannot be coded whole-pel-only.
7807+ fn y4m_12bit_subpel_source(frames: usize) -> Vec<u8> {
7808+ const W: usize = 160;
7809+ const H: usize = 128;
7810+ let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0);
7811+ let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes();
7812+ for t in 0..frames {
7813+ let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64);
7814+ let (bx, by) = (ax + 24.0, ay + 20.0);
7815+ y4m.extend_from_slice(b"FRAME\n");
7816+ for j in 0..H as i64 {
7817+ for i in 0..W as i64 {
7818+ let g = (i * 190) / W as i64 + (j * 150) / H as i64;
7819+ let mut v = (g * 12
7820+ + if (i * 5 + j * 3 + t as i64) % 7 < 3 { 90 } else { 220 }
7821+ + if (60..110).contains(&i) && (70..110).contains(&j) { 640 } else { 0 })
7822+ as f64;
7823+ let c = cov(ax, bx, i) * cov(ay, by, j);
7824+ if c > 0.0 {
7825+ v = v * (1.0 - c) + 3500.0 * c;
7826+ }
7827+ y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes());
7828+ }
7829+ }
7830+ for (base, fx) in [(1900usize, 0usize), (2100, 1)] {
7831+ for j in 0..H / 2 {
7832+ for i in 0..W / 2 {
7833+ let v = if fx == 0 {
7834+ base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H)
7835+ } else {
7836+ base + (((j / 4 + t) % 5) * 140 + (i * 40) / W)
7837+ };
7838+ y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes());
7839+ }
7840+ }
7841+ }
7842+ }
7843+ y4m
7844+ }
7845+
7846+ /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so
7847+ /// every search runs; explicit CDEF/restoration ON). Warp/global-motion
7848+ /// are deliberately NOT spelled here: this aomenc honours the LAST
7849+ /// occurrence of these flags (measured), so a base pin plus an override
7850+ /// would silently take the base value -- each gate spells what it needs
7851+ /// exactly once.
7852+ fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec<u8> {
7853+ let limit = format!("--limit={frames}");
7854+ let mut args: Vec<&str> = vec![
7855+ "--codec=av1",
7856+ "--profile=2",
7857+ "--passes=1",
7858+ "--end-usage=q",
7859+ "--cq-level=20",
7860+ "--cpu-used=0",
7861+ "--threads=1",
7862+ "--row-mt=0",
7863+ "--sb-size=64",
7864+ "--lag-in-frames=0",
7865+ "--auto-alt-ref=0",
7866+ "--kf-max-dist=1000",
7867+ "--input-bit-depth=12",
7868+ "--bit-depth=12",
7869+ "--enable-cdef=1",
7870+ "--enable-restoration=1",
7871+ "--obu",
7872+ "-o",
7873+ "-",
7874+ "-",
7875+ &limit,
7876+ ];
7877+ // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
7878+ // of a flag, so the per-arm override goes BEFORE the base list.
7879+ args.splice(1..1, extra.iter().copied());
7880+ let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
7881+ assert!(
7882+ out.status.success(),
7883+ "aomenc refused the 12-bit fixture: {}",
7884+ String::from_utf8_lossy(&out.stderr)
7885+ );
7886+ out.stdout
7887+ }
7888+
7889+ /// Asserts the stream's sequence header really says 12-bit before any
7890+ /// pixel comparison is trusted.
7891+ fn assert_12bit_sequence_header(stream: &[u8], name: &str) {
7892+ let mut probe = Av1Parser::new();
7893+ let mut pos = 0usize;
7894+ while pos < stream.len() && probe.sequence_header().is_none() {
7895+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
7896+ pos += obu.total_size;
7897+ }
7898+ let seq = probe.sequence_header().expect("stream has a sequence header OBU");
7899+ assert_eq!(
7900+ seq.color_config.bit_depth, 12,
7901+ "{name}: aomenc did not actually write a 12-bit sequence header"
7902+ );
7903+ }
7904+
7905+ fn ffmpeg_decode_sequence_12bit(stream: &[u8], width: usize, height: usize, frames: usize) -> Vec<Pic> {
7906+ let out = run_with_stdin(
7907+ Command::new("ffmpeg").args([
7908+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
7909+ "yuv420p12le", "-",
7910+ ]),
7911+ stream,
7912+ );
7913+ assert!(
7914+ out.status.success(),
7915+ "ffmpeg refused the 12-bit stream: {}",
7916+ String::from_utf8_lossy(&out.stderr)
7917+ );
7918+ let (luma, chroma) = (width * height, width * height / 4);
7919+ let frame_bytes = (luma + 2 * chroma) * 2;
7920+ assert_eq!(
7921+ out.stdout.len(),
7922+ frame_bytes * frames,
7923+ "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}",
7924+ String::from_utf8_lossy(&out.stderr)
7925+ );
7926+ fn le16(bytes: &[u8]) -> Vec<u16> {
7927+ bytes
7928+ .chunks_exact(2)
7929+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
7930+ .collect()
7931+ }
7932+ (0..frames)
7933+ .map(|i| {
7934+ let base = i * frame_bytes;
7935+ Pic {
7936+ width,
7937+ height,
7938+ y: le16(&out.stdout[base..base + luma * 2]),
7939+ u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
7940+ v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
7941+ }
7942+ })
7943+ .collect()
7944+ }
7945+
7946+ /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off.
7947+ /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard-
7948+ /// assert fired: a CDEF index literal read (bits > 0) and at least one
7949+ /// Wiener or SGR restoration unit. Gauntlet for the parameterised
7950+ /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF,
7951+ /// the 12-bit dequant tables, bd-scaled SGR box sums.
7952+ #[test]
7953+ fn a_real_aomenc_12bit_stream_decodes_pixel_exact() {
7954+ const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact";
7955+ let _gate_lock = lock_gate_counters();
7956+ if !have_ffmpeg() {
7957+ eprintln!("SKIP {NAME}: no ffmpeg");
7958+ return;
7959+ }
7960+ if !have_aomenc() {
7961+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7962+ return;
7963+ }
7964+ let y4m = y4m_12bit_subpel_source(1);
7965+ let stream = encode_12bit(
7966+ &y4m,
7967+ 1,
7968+ &["--enable-warped-motion=0", "--enable-global-motion=0"],
7969+ );
7970+ assert_12bit_sequence_header(&stream, NAME);
7971+ let before_cdef = decode::cdef_idx_hits();
7972+ let before_lr =
7973+ crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
7974+ let frames = decode_stream(&stream)
7975+ .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}"));
7976+ assert_eq!(frames.len(), 1);
7977+ assert!(
7978+ decode::cdef_idx_hits() > before_cdef,
7979+ "{NAME}: no CDEF index literal was read -- CDEF is not exercised"
7980+ );
7981+ assert!(
7982+ crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
7983+ "{NAME}: no loop restoration unit was decoded -- LR is not exercised"
7984+ );
7985+ let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1);
7986+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (12-bit key)");
7987+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)");
7988+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)");
7989+ }
7990+
7991+ /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel
7992+ /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass
7993+ /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own
7994+ /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs
7995+ /// parameterisation -- really executed, and asserts
7996+ /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent
7997+ /// second reference, which is exactly why compound stays refused).
7998+ #[test]
7999+ fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() {
8000+ const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact";
8001+ let _gate_lock = lock_gate_counters();
8002+ if !have_ffmpeg() {
8003+ eprintln!("SKIP {NAME}: no ffmpeg");
8004+ return;
8005+ }
8006+ if !have_aomenc() {
8007+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8008+ return;
8009+ }
8010+ let y4m = y4m_12bit_subpel_source(2);
8011+ let stream = encode_12bit(
8012+ &y4m,
8013+ 2,
8014+ &["--enable-warped-motion=0", "--enable-global-motion=0"],
8015+ );
8016+ assert_12bit_sequence_header(&stream, NAME);
8017+ let before_subpel = crate::mc::mc_subpel_hits();
8018+ let before_compound = decode::compound_mode_hits();
8019+ let frames = decode_stream(&stream)
8020+ .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}"));
8021+ assert_eq!(frames.len(), 2);
8022+ assert!(
8023+ crate::mc::mc_subpel_hits() > before_subpel,
8024+ "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised"
8025+ );
8026+ assert_eq!(
8027+ decode::compound_mode_hits(),
8028+ before_compound,
8029+ "{NAME}: a compound mode symbol was read -- the single-reference premise is gone"
8030+ );
8031+ let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
8032+ for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8033+ assert_eq!(ours.y, reference.y, "frame {i} luma vs ffmpeg (12-bit inter)");
8034+ assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)");
8035+ assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)");
8036+ }
8037+ }
8038+
8039+ /// The 12-bit warp refusal, exercised on a REAL stream: the same source
8040+ /// and recipe with the warp tools ON -- aomenc picks a global warp model
8041+ /// on this content (measured: the decode refuses at the first warped
8042+ /// block) -- is refused by name.
8043+ #[test]
8044+ fn a_12bit_warped_motion_stream_is_refused_by_name() {
8045+ const NAME: &str = "a_12bit_warped_motion_stream_is_refused_by_name";
8046+ let _gate_lock = lock_gate_counters();
8047+ if !have_aomenc() {
8048+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8049+ return;
8050+ }
8051+ let y4m = y4m_12bit_subpel_source(6);
8052+ // Exactly the recipe measured to refuse at warp: warp ON, global
8053+ // motion NOT spelled (spelling it ON makes a GLOBAL_GLOBALMV
8054+ // compound block reach the compound refusal first), six frames --
8055+ // the warp model fires at the third frame.
8056+ let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
8057+ let err = decode_stream(&stream).unwrap_err().to_string();
8058+ assert!(
8059+ err.contains(
8060+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)"
8061+ ),
8062+ "{NAME}: expected the 12-bit warp refusal, got: {err}"
8063+ );
8064+ }
8065+
8066+ /// The 12-bit compound refusal, exercised on a REAL stream: six frames
8067+ /// with `--lag-in-frames=0` still diverge LAST from GOLDEN from frame 2
8068+ /// on (measured: aomenc codes compound blocks and the decode refuses at
8069+ /// the compound mode read).
8070+ #[test]
8071+ fn a_12bit_compound_inter_stream_is_refused_by_name() {
8072+ const NAME: &str = "a_12bit_compound_inter_stream_is_refused_by_name";
8073+ let _gate_lock = lock_gate_counters();
8074+ if !have_aomenc() {
8075+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8076+ return;
8077+ }
8078+ let y4m = y4m_12bit_subpel_source(6);
8079+ // Warp pinned OFF so the COMPOUND refusal is the one that can fire:
8080+ // with six frames, LAST diverges from GOLDEN from frame 2 on and
8081+ // aomenc codes compound blocks (measured).
8082+ let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=0"]);
8083+ let err = decode_stream(&stream).unwrap_err().to_string();
8084+ assert!(
8085+ err.contains(
8086+ "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)"
8087+ ),
8088+ "{NAME}: expected the 12-bit compound refusal, got: {err}"
8089+ );
8090+ }
8091+
8092+ /// The 12-bit film grain refusal: a real `--film-grain-test=1` stream
8093+ /// (grain params present AND applied) is refused by name at output.
8094+ #[test]
8095+ fn a_12bit_film_grain_stream_is_refused_by_name() {
8096+ const NAME: &str = "a_12bit_film_grain_stream_is_refused_by_name";
8097+ let _gate_lock = lock_gate_counters();
8098+ if !have_aomenc() {
8099+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8100+ return;
8101+ }
8102+ let y4m = y4m_12bit_subpel_source(1);
8103+ let stream = encode_12bit(&y4m, 1, &["--film-grain-test=1"]);
8104+ let err = decode_stream(&stream).unwrap_err().to_string();
8105+ assert!(
8106+ err.contains(
8107+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)"
8108+ ),
8109+ "{NAME}: expected the 12-bit grain refusal, got: {err}"
8110+ );
8111+ }
8112+
8113+ /// The 12-bit screen-content refusal: a real `--tune-content=screen
8114+ /// --enable-palette=1 --enable-intrabc=1` frame carries
8115+ /// `allow_screen_content_tools = 1` and is refused by name at the frame
8116+ /// gate -- palette and intrabc have no 12-bit witness.
8117+ #[test]
8118+ fn a_12bit_screen_content_stream_is_refused_by_name() {
8119+ const NAME: &str = "a_12bit_screen_content_stream_is_refused_by_name";
8120+ let _gate_lock = lock_gate_counters();
8121+ if !have_ffmpeg() {
8122+ eprintln!("SKIP {NAME}: no ffmpeg");
8123+ return;
8124+ }
8125+ if !have_aomenc() {
8126+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8127+ return;
8128+ }
8129+ let y4m = Command::new("ffmpeg")
8130+ .args([
8131+ "-v", "error", "-f", "lavfi", "-i", "smptebars=s=128x128:r=25",
8132+ "-pix_fmt", "yuv420p12le", "-strict", "-1", "-frames:v", "2",
8133+ "-f", "yuv4mpegpipe", "-",
8134+ ])
8135+ .stdin(Stdio::null())
8136+ .stdout(Stdio::piped())
8137+ .stderr(Stdio::piped())
8138+ .output()
8139+ .expect("ffmpeg failed to run");
8140+ assert!(
8141+ y4m.status.success(),
8142+ "ffmpeg failed to render the 12-bit screen fixture: {}",
8143+ String::from_utf8_lossy(&y4m.stderr)
8144+ );
8145+ let stream = encode_12bit(
8146+ &y4m.stdout,
8147+ 1,
8148+ &["--tune-content=screen", "--enable-palette=1", "--enable-intrabc=1"],
8149+ );
8150+ let err = decode_stream(&stream).unwrap_err().to_string();
8151+ assert!(
8152+ err.contains(
8153+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)"
8154+ ),
8155+ "{NAME}: expected the 12-bit screen content refusal, got: {err}"
8156+ );
8157+ }
8158+
77758159 #[test]
77768160 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
77778161 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
lanes/av112bit.report.mdadded+143 -0
@@ -0,0 +1,143 @@
1+# lane-av112bit — the 12-bit decode gate
2+
3+Base 73f3ac64, worktree `edith_codecs-av112b`. The charter: lift the blanket
4+`bit_depth == 12` refusal in `stream.rs` (`lanes/av1hdr.report.md` §4.2 named
5+the sites) exactly as far as real `aomenc --bit-depth=12` witnesses prove
6+byte-exactness against ffmpeg, and keep every unwitnessed 12-bit path refused
7+by name.
8+
9+## The libaom rule (what actually moves at 12 bits)
10+
11+`av1/common/convolve.h:68..100` (`get_conv_params_no_round`) and
12+`:107..118` (`get_conv_params_wiener`):
13+
14+```c
15+const int intbufrange = bd + FILTER_BITS - round_0 + 2;
16+if (intbufrange > 16) { round_0 += intbufrange - 16; if (!is_compound) round_1 -= intbufrange - 16; }
17+```
18+
19+i.e. `delta = bd - 10` (zero at 8/10-bit; 2 at 12-bit). Horizontal `round_0`
20+3 -> 5; non-compound vertical `round_1` 11 -> 9 (product, the filter gain,
21+unchanged); compound `round_1` stays 7, so the CONV_BUF gain drops from 16x
22+to 4x and every combine round absorbs the delta. Warp inherits the same
23+`round_0` (`warped_motion.c:295`, with the assert at `:310` pinning
24+`bd + FILTER_BITS + 2 - round_0 <= 16`) — §4.2's "`round_0 + max(...)` (5 at
25+bd 12)" and the retracted-reviewer note stand, expressed through the conv
26+params.
27+
28+## What changed (witnessed paths, lifted)
29+
30+- **`mc.rs`** — `round_delta`/`round_pair` implement the convolve.h rule.
31+ The shift is threaded through `hpass_row`/`hpass_contig`/`hpass_rows`/
32+ `hpass_avx2`/`hpass_sse2`, `vpass_row_u16` + AVX2/SSE4.1 kernels and
33+ scalars (the `srai` immediates became vector-count `sra`), the identity-tap
34+ fast paths (`gain = 128 >> round_0`, `t * (128 >> round_0)`,
35+ `round2(a, round_1 - 7)`), `horizontal_scaled_pass`, and
36+ `predict_compound_intermediate_kern` (which now takes `fctx`). The compound
37+ combines absorb the CONV_BUF gain drop:
38+ `combine_compound`/`blend_masked_compound` round by
39+ `INTER_POST_ROUND - delta`, `diffwtd_mask` by
40+ `INTER_POST_ROUND + (bd - 8) - delta` (the `reconinter.c:307` formula).
41+ `horizontal_intermediate_fits_i16` now pins the 12-bit bound
42+ (`round2(348 * 4095, 5) = 27976 < 2^15`); the SIMD tests already spanned
43+ 12-bit intermediates.
44+- **`restoration.rs`** — the Wiener stripe runs its horizontal pass at the
45+ frame's `round_0` and vertical at `round_1` (9 at 12-bit). SGR needed
46+ nothing: `compute_ab`/`ab_point` were already `bd_shift = bd - 8`
47+ parameterised (the lane-hbdinter fix), and the oracle's
48+ `calculate_intermediate_result` matches it exactly.
49+- Everything else 12-bit-relevant was already bit-depth generic and
50+ 10-bit-proven: the 12-bit dequant tables (`quant.rs`), deblock
51+ (`sclamp`/threshold `<< bd - 8`), CDEF (`coeff_shift = bd - 8`,
52+ `damping += coeff_shift`, exactly `av1_cdef_filter_fb`), film grain
53+ (`grain_center`/`scale_lut`/LUT expansion, lane-hbd10), superres upscale
54+ clamp, palette colour reads, `sample_max` clamps.
55+
56+## What stayed refused (unwitnessed, by name — real-stream gates)
57+
58+| refusal | site | gate (real aomenc stream) |
59+|---|---|---|
60+| `warped motion at 12 bits ...` | decode.rs warp decision sites (compound, 16x16+, 8x8 leaf), parse-time | `a_12bit_warped_motion_stream_is_refused_by_name` |
61+| `a compound inter block at 12 bits ...` | both leaves' `read_inter_compound_mode` callers | `a_12bit_compound_inter_stream_is_refused_by_name` |
62+| `film grain synthesis at 12 bits ...` | all four `apply_grain` output sites (`grain_refusal`) | `a_12bit_film_grain_stream_is_refused_by_name` |
63+| `a 12-bit frame with screen content tools ...` | stream.rs frame gate (`allow_screen_content_tools`) | `a_12bit_screen_content_stream_is_refused_by_name` |
64+
65+The screen-content gate covers palette **and** intrabc with one honest frame
66+level refusal: both hang off `allow_screen_content_tools`, neither has a
67+12-bit witness, and refusing the frame keeps both code paths 12-bit
68+unreachable instead of unwitnessed-and-trusted.
69+
70+OBMC, interintra, palette reads, intrabc copies and superres-scaled MC are
71+NOT separately gated: their arithmetic is bit-depth independent and their
72+bd-sensitive inputs (MC predictions, samples) are witnessed at 12 bits —
73+the composition of two proven pieces. The scaled-MC walk shares the exact
74+parameterised round path; the 10-bit superres gate pins the walk itself.
75+
76+## The witnesses
77+
78+Source (Rust `y4m_12bit_subpel_source`, byte-identical to the manual
79+generator): 160x128 C420p12, gradient + fine texture, a 24x20 box travelling
80+1.25 px/frame horizontally and 0.75 px/frame vertically with linear edge
81+coverage — sub-pixel true motion, so the inter frame cannot be coded
82+whole-pel-only (proven: `MC_SUBPEL_HITS > 0`, a new counter).
83+
84+Recipe (both witnesses): `aomenc --codec=av1 --profile=2 --bit-depth=12
85+--input-bit-depth=12 --passes=1 --end-usage=q --cq-level=20 --cpu-used=0
86+--threads=1 --row-mt=0 --sb-size=64 --lag-in-frames=0 --auto-alt-ref=0
87+--kf-max-dist=1000 --enable-cdef=1 --enable-restoration=1
88+--enable-warped-motion=0 --enable-global-motion=0 --obu --limit=<N>`,
89+N=1 (key) / N=2 (key + one P frame).
90+
91+- `crates/ec-av1/fixtures/av112bit-key.obu` — 923 bytes,
92+ sha256 `c74f62b57f71f7c36c49ea1feeb482786a2650e5c7f66610949b5f65fbbed8d1`
93+- `crates/ec-av1/fixtures/av112bit-inter.obu` — 4533 bytes,
94+ sha256 `e679d577e61b4a8bc99685355cca8c0473cfb637284b07786a6c53b1755553d9`
95+
96+Encoder: the local aom oracle build (`~/.cache/aom-oracle/build/aomenc`,
97+libaom src `92d4c37fbdd08944a0e721bbaeb13318f10aebb0`); reference decode
98+ffmpeg 8.1.2 (`yuv420p12le` rawvideo). The gates encode live from the
99+in-test generator and pixel-compare every plane of every frame against
100+ffmpeg's decode of the identical bytes; the committed fixtures are the same
101+recipe's output for provenance (the inter fixture byte-equals the manual
102+lane run, `cmp` clean).
103+
104+Gate asserts beyond the pixel match, so none can pass vacuously:
105+key — `cdef_idx_hits > 0` (CDEF index literals read) and Wiener+SGR unit
106+count advanced; inter — `MC_SUBPEL_HITS > 0` (the parameterised round pair
107+actually ran) and `compound_mode_hits` UNCHANGED (the single-reference
108+premise the compound refusal leans on).
109+
110+## Results
111+
112+- 12-bit battery (6 gates) green; the two witnesses byte-exact vs ffmpeg.
113+- 10-bit regression: `a_real_aomenc_10bit_stream_decodes_pixel_exact`,
114+ `a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact`,
115+ `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact`, and the three
116+ film fixture gates (`a_10bit_128sb_film_frames_with_warp_cdef_and_interintra...`,
117+ `a_10bit_film_frames_with_rect64_corner_tus...`,
118+ `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_reach...`) all
119+ green — the two charter-named film gates included.
120+- 8-bit spot regression (monochrome, lossless, real-aomenc arms) green.
121+- `refusal_inventory` + `gate_coverage` tests green (inventory diff = the
122+ capability delta above).
123+
124+## Open halves (recorded, not silently dropped)
125+
126+1. **Wiener intermediate clamp at 12 bits.** A first attempt replaced the
127+ corpus-proven constant clamp with the C clamp's exact per-sample
128+ transform (add_src bias surviving `Round2(_, round_0)`) — it MOVED
129+ `a_10bit_128sb_film_frames...` frame 1 luma: libaom's 8-tap-loop
130+ pointer-alignment trick means the C horizontal intermediate is not
131+ `ours + bias` wherever the clamp actually binds, so the exact transform
132+ is not derivable from the convolve source alone. The shipped code keeps
133+ the 8/10-bit-proven constant structure (`[-2^(bd+3), 2^(bd+5)-1-2^(bd+3)]`,
134+ i16-safe; at 12-bit the widest i16 window, which strictly contains the
135+ kernel's mathematical range and so never binds — the same property the
136+ 8/10-bit bounds have on the proven corpus). The 12-bit key witness is
137+ byte-exact with it; a stream whose intermediates would trip C's real
138+ clamp is unproven either way. Disposition: `accepted` (deferred to a
139+ lane that instruments the oracle's wiener path directly).
140+2. **Compound, warp, grain, palette, intrabc at 12 bits** — refused by name
141+ with real-stream gates; lifting each needs its own byte-exact witness
142+ (compound of every kind, warp at the 12-bit `round_0`, grain synthesis,
143+ screen content).