forge
Explore
Log in

Don't you dare go Hollow

Merge lane-av1-12bit and lane-av1-12bit-comp: 12-bit gate and compound lift

Browse files at this commit

60c70a0a060440f5778f1a36c44b9dba2e656a5bAhmet Kaan GümüşParent: 0dd0f4d70849e0
server-4 suite on the 12-bit commit: 611 passed, 0 failed, 60 ignored.
Local compound suite: 605 passed, 6 failed, 60 ignored. The 6 panics were
fs::write NotFound because TMPDIR did not exist. Re-ran those 6 by full name
with the temp dir present: 6 passed.

12 changed files +1724 -319

crates/ec-av1/fixtures/av112bit-compound-masked.obuadded+0 -0

Binary file changed

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

Binary file changed

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+48 -25
@@ -28,6 +28,16 @@ use ec_av1_syntax::{
28 };28 };
29 use ec_core::{Error, Result};29 use ec_core::{Error, Result};
30 30
31+// lane-av112bit: the 12-bit warp 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).
35+// lane-av112bitc lifted the compound pair of the same family: the compound
36+// combines absorb the CONV_BUF gain drop (`INTER_POST_ROUND - delta`, see
37+// `mc::combine_compound`) and the six-frame 12-bit compound witness is
38+// byte-exact vs ffmpeg. All sites are PARSE-time: a refused stream never
39+// builds a warp predictor.
40+
31 /// Per-frame decode state, one instance per decoded stream (lane-thread1).41 /// Per-frame decode state, one instance per decoded stream (lane-thread1).
32 ///42 ///
33 /// Every field here used to be a `thread_local!` static, which made a decode a43 /// Every field here used to be a `thread_local!` static, which made a decode a
@@ -5324,7 +5334,7 @@ thread_local! {
5324 }5334 }
5325 5335
5326 /// Current value of [`COMPOUND_MODE_HITS`].5336 /// Current value of [`COMPOUND_MODE_HITS`].
5327-#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live5337+#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
5328 pub(crate) fn compound_mode_hits() -> usize {5338 pub(crate) fn compound_mode_hits() -> usize {
5329 COMPOUND_MODE_HITS.with(|c| c.get())5339 COMPOUND_MODE_HITS.with(|c| c.get())
5330 }5340 }
@@ -29114,6 +29124,13 @@ fn decode_inter_block(
29114 let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1));29124 let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1));
29115 if warp0.is_some() || warp1.is_some() {29125 if warp0.is_some() || warp1.is_some() {
29116 hit!(COMPOUND_WARP_HITS);29126 hit!(COMPOUND_WARP_HITS);
29127+ // lane-av112bit: refused by name -- see `WARP_12BIT_REFUSAL`.
29128+ if bit_depth(fctx) == 12 {
29129+ return Err(Error::unsupported(
29130+ "AV1 tile decode",
29131+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
29132+ ));
29133+ }
29117 }29134 }
29118 // spec `get_ref_filter_type`: matches when EITHER of the29135 // spec `get_ref_filter_type`: matches when EITHER of the
29119 // neighbour's two references equals this block's own ref0 --29136 // neighbour's two references equals this block's own ref0 --
@@ -29576,8 +29593,7 @@ fn decode_inter_block(
29576 write_h,29593 write_h,
29577 h_filter,29594 h_filter,
29578 v_filter,29595 v_filter,
29579- &mut inter0_y,29596+ &mut inter0_y, fctx,);
29580- );
29581 // lane-cwarp r1: this reference's own GLOBAL warp replaces the29597 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
29582 // translational tap (libaom `av1_warp_plane` with29598 // translational tap (libaom `av1_warp_plane` with
29583 // `conv_params->is_compound`); the blend below is unchanged.29599 // `conv_params->is_compound`); the blend below is unchanged.
@@ -29603,8 +29619,7 @@ fn decode_inter_block(
29603 write_h,29619 write_h,
29604 h_filter,29620 h_filter,
29605 v_filter,29621 v_filter,
29606- &mut inter1_y,29622+ &mut inter1_y, fctx,);
29607- );
29608 // lane-cwarp r1: this reference's own GLOBAL warp replaces the29623 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
29609 // translational tap (libaom `av1_warp_plane` with29624 // translational tap (libaom `av1_warp_plane` with
29610 // `conv_params->is_compound`); the blend below is unchanged.29625 // `conv_params->is_compound`); the blend below is unchanged.
@@ -29652,8 +29667,7 @@ fn decode_inter_block(
29652 write_chroma_h,29667 write_chroma_h,
29653 h_filter,29668 h_filter,
29654 v_filter,29669 v_filter,
29655- &mut inter0_u,29670+ &mut inter0_u, fctx,);
29656- );
29657 // `av1_init_warp_params` bails when the PLANE's block is29671 // `av1_init_warp_params` bails when the PLANE's block is
29658 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma29672 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
29659 // block of an 8x8 luma block stays translational.29673 // block of an 8x8 luma block stays translational.
@@ -29681,8 +29695,7 @@ fn decode_inter_block(
29681 write_chroma_h,29695 write_chroma_h,
29682 h_filter,29696 h_filter,
29683 v_filter,29697 v_filter,
29684- &mut inter1_u,29698+ &mut inter1_u, fctx,);
29685- );
29686 // `av1_init_warp_params` bails when the PLANE's block is29699 // `av1_init_warp_params` bails when the PLANE's block is
29687 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma29700 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
29688 // block of an 8x8 luma block stays translational.29701 // block of an 8x8 luma block stays translational.
@@ -29726,8 +29739,7 @@ fn decode_inter_block(
29726 write_chroma_h,29739 write_chroma_h,
29727 h_filter,29740 h_filter,
29728 v_filter,29741 v_filter,
29729- &mut inter0_v,29742+ &mut inter0_v, fctx,);
29730- );
29731 // `av1_init_warp_params` bails when the PLANE's block is29743 // `av1_init_warp_params` bails when the PLANE's block is
29732 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma29744 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
29733 // block of an 8x8 luma block stays translational.29745 // block of an 8x8 luma block stays translational.
@@ -29755,8 +29767,7 @@ fn decode_inter_block(
29755 write_chroma_h,29767 write_chroma_h,
29756 h_filter,29768 h_filter,
29757 v_filter,29769 v_filter,
29758- &mut inter1_v,29770+ &mut inter1_v, fctx,);
29759- );
29760 // `av1_init_warp_params` bails when the PLANE's block is29771 // `av1_init_warp_params` bails when the PLANE's block is
29761 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma29772 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
29762 // block of an 8x8 luma block stays translational.29773 // block of an 8x8 luma block stays translational.
@@ -30806,6 +30817,15 @@ fn decode_inter_block(
30806 hit!(AFFINE_GM_HITS);30817 hit!(AFFINE_GM_HITS);
30807 }30818 }
30808 }30819 }
30820+ // lane-av112bit: a local `WARPED_CAUSAL` projection (set above) or
30821+ // a global warp model both land here with `warp_params` set --
30822+ // refused by name at 12 bits (see `WARP_12BIT_REFUSAL`).
30823+ if bit_depth(fctx) == 12 && warp_params.is_some() {
30824+ return Err(Error::unsupported(
30825+ "AV1 tile decode",
30826+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
30827+ ));
30828+ }
30809 if crate::envflags::env_flag!("EC_AV1_TELL") {30829 if crate::envflags::env_flag!("EC_AV1_TELL") {
30810 eprintln!(30830 eprintln!(
30811 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",30831 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
@@ -35086,8 +35106,7 @@ fn decode_inter_block8(
35086 SIDE,35106 SIDE,
35087 h_filter,35107 h_filter,
35088 v_filter,35108 v_filter,
35089- &mut inter0_y,35109+ &mut inter0_y, fctx,);
35090- );
35091 if let Some(wp) = &warp0_c {35110 if let Some(wp) = &warp0_c {
35092 crate::warp::warp_affine_compound(35111 crate::warp::warp_affine_compound(
35093 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,35112 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
@@ -35108,8 +35127,7 @@ fn decode_inter_block8(
35108 SIDE,35127 SIDE,
35109 h_filter,35128 h_filter,
35110 v_filter,35129 v_filter,
35111- &mut inter1_y,35130+ &mut inter1_y, fctx,);
35112- );
35113 if let Some(wp) = &warp1_c {35131 if let Some(wp) = &warp1_c {
35114 crate::warp::warp_affine_compound(35132 crate::warp::warp_affine_compound(
35115 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,35133 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
@@ -35148,8 +35166,7 @@ fn decode_inter_block8(
35148 CHROMA_SIDE,35166 CHROMA_SIDE,
35149 h_filter,35167 h_filter,
35150 v_filter,35168 v_filter,
35151- &mut inter0_u,35169+ &mut inter0_u, fctx,);
35152- );
35153 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];35170 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
35154 mc::predict_compound_intermediate(35171 mc::predict_compound_intermediate(
35155 &pu1.data,35172 &pu1.data,
@@ -35163,8 +35180,7 @@ fn decode_inter_block8(
35163 CHROMA_SIDE,35180 CHROMA_SIDE,
35164 h_filter,35181 h_filter,
35165 v_filter,35182 v_filter,
35166- &mut inter1_u,35183+ &mut inter1_u, fctx,);
35167- );
35168 let mut pred_u = refill(std::mem::take(&mut out[1]), CHROMA_SIDE * CHROMA_SIDE);35184 let mut pred_u = refill(std::mem::take(&mut out[1]), CHROMA_SIDE * CHROMA_SIDE);
35169 if let Some(mask_y) = mask_y {35185 if let Some(mask_y) = mask_y {
35170 mc::blend_masked_compound(35186 mc::blend_masked_compound(
@@ -35194,8 +35210,7 @@ fn decode_inter_block8(
35194 CHROMA_SIDE,35210 CHROMA_SIDE,
35195 h_filter,35211 h_filter,
35196 v_filter,35212 v_filter,
35197- &mut inter0_v,35213+ &mut inter0_v, fctx,);
35198- );
35199 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];35214 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
35200 mc::predict_compound_intermediate(35215 mc::predict_compound_intermediate(
35201 &pv1.data,35216 &pv1.data,
@@ -35209,8 +35224,7 @@ fn decode_inter_block8(
35209 CHROMA_SIDE,35224 CHROMA_SIDE,
35210 h_filter,35225 h_filter,
35211 v_filter,35226 v_filter,
35212- &mut inter1_v,35227+ &mut inter1_v, fctx,);
35213- );
35214 let mut pred_v = refill(std::mem::take(&mut out[2]), CHROMA_SIDE * CHROMA_SIDE);35228 let mut pred_v = refill(std::mem::take(&mut out[2]), CHROMA_SIDE * CHROMA_SIDE);
35215 if let Some(mask_y) = mask_y {35229 if let Some(mask_y) = mask_y {
35216 mc::blend_masked_compound(35230 mc::blend_masked_compound(
@@ -35764,6 +35778,15 @@ fn decode_inter_block8(
35764 hit!(AFFINE_GM_HITS);35778 hit!(AFFINE_GM_HITS);
35765 }35779 }
35766 }35780 }
35781+ // lane-av112bit: same 12-bit refusal as the 16x16+ leaf -- a local
35782+ // `WARPED_CAUSAL` projection or a global model both leave
35783+ // `warp_params` set here (see `WARP_12BIT_REFUSAL`).
35784+ if bit_depth(fctx) == 12 && warp_params.is_some() {
35785+ return Err(Error::unsupported(
35786+ "AV1 tile decode",
35787+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
35788+ ));
35789+ }
35767 if crate::envflags::env_flag!("EC_TRACE_MODE") {35790 if crate::envflags::env_flag!("EC_TRACE_MODE") {
35768 eprintln!(35791 eprintln!(
35769 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",35792 "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(
9745 side,9745 side,
9746 fctx.interp_filter.get(),9746 fctx.interp_filter.get(),
9747 fctx.interp_filter.get(),9747 fctx.interp_filter.get(),
9748- dst,9748+ dst, fctx,
9749 );9749 );
9750 }9750 }
9751 let mut blended16 = [0u16; BLOCK * BLOCK];9751 let mut blended16 = [0u16; BLOCK * BLOCK];
@@ -9838,7 +9838,7 @@ fn predict_compound_u8(
9838 side,9838 side,
9839 fctx.interp_filter.get(),9839 fctx.interp_filter.get(),
9840 fctx.interp_filter.get(),9840 fctx.interp_filter.get(),
9841- dst,9841+ dst, fctx,
9842 );9842 );
9843 }9843 }
9844 let mut blended = vec![0u16; side * side];9844 let mut blended = vec![0u16; side * side];
crates/ec-av1/src/mc.rsmodified+674 -171
@@ -23,24 +23,46 @@ fn round2(value: i32, shift: u32) -> i32 {
23 /// through `packs_epi32`, which saturates -- so the scalar arms must too, or23 /// through `packs_epi32`, which saturates -- so the scalar arms must too, or
24 /// the two would disagree on an out-of-range sum. Motion compensation never24 /// the two would disagree on an out-of-range sum. Motion compensation never
25 /// produces one (`horizontal_intermediate_fits_i16` proves the bound from the25 /// 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's26+/// tap sums at every supported bit depth), and restoration's wiener pass
27-/// wiener pass clamps its own output into i16 immediately after.27+/// clamps its own output into i16 immediately after.
28 fn sat16(value: i32) -> i16 {28 fn sat16(value: i32) -> i16 {
29 value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i1629 value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
30 }30 }
31 31
32-/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the32+/// `InterRound0` (spec 7.11.3.2), non-compound: the shift the horizontal
33-/// horizontal pass's sum is brought down by before it is stored as the33+/// pass's sum is brought down by before it is stored as the intermediate.
34-/// 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`).
35 const INTER_ROUND_0: u32 = 3;36 const INTER_ROUND_0: u32 = 3;
36-/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical37+/// `InterRound1` (spec 7.11.3.2), non-compound: the shift the vertical
37-/// pass's sum is brought down by to land back on an 8-bit sample. Composed38+/// pass's sum is brought down by to land back on a sample. Composed
38-/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass39+/// with [`INTER_ROUND_0`] the two shifts are the filter's own gain (each pass
39 /// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)40 /// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)
40 /// -- so an identity or DC input comes back exactly, by construction of the41 /// -- 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`].
42 const INTER_ROUND_1: u32 = 11;43 const INTER_ROUND_1: u32 = 11;
43 44
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+
44 /// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel66 /// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel
45 /// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer67 /// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer
46 /// sample (fraction 0 is the identity tap `[.., 128, ..]`).68 /// sample (fraction 0 is the identity tap `[.., 128, ..]`).
@@ -296,9 +318,9 @@ pub(crate) fn simd_level() -> SimdLevel {
296 /// the same `Round2(sum, InterRound0)`.318 /// the same `Round2(sum, InterRound0)`.
297 #[allow(unsafe_code)]319 #[allow(unsafe_code)]
298 #[inline]320 #[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) {
300 let n = out.len();322 let n = out.len();
301- hpass_rows(src, 0, 1, n, t16, out);323+ hpass_rows(src, 0, 1, n, t16, out, round0);
302 }324 }
303 325
304 /// lane-mc2: `rows` rows of [`hpass_contig`], `src_stride` apart in `src` and326 /// lane-mc2: `rows` rows of [`hpass_contig`], `src_stride` apart in `src` and
@@ -313,6 +335,7 @@ pub(crate) fn hpass_rows(
313 block_w: usize,335 block_w: usize,
314 t16: &[i16; 8],336 t16: &[i16; 8],
315 out: &mut [i16],337 out: &mut [i16],
338+ round0: u32,
316 ) {339 ) {
317 #[cfg(target_arch = "x86_64")]340 #[cfg(target_arch = "x86_64")]
318 {341 {
@@ -320,13 +343,13 @@ pub(crate) fn hpass_rows(
320 SimdLevel::Avx2 => {343 SimdLevel::Avx2 => {
321 // SAFETY: the AVX2 arm is reached only when the CPU reports344 // SAFETY: the AVX2 arm is reached only when the CPU reports
322 // avx2; each row reads at most `block_w + 7` samples.345 // 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) };
324 return;347 return;
325 }348 }
326 SimdLevel::Sse41 => {349 SimdLevel::Sse41 => {
327 // SAFETY: as above; the kernel needs only SSE2, which every350 // SAFETY: as above; the kernel needs only SSE2, which every
328 // x86_64 CPU has.351 // 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) };
330 return;353 return;
331 }354 }
332 SimdLevel::Scalar => {}355 SimdLevel::Scalar => {}
@@ -337,12 +360,13 @@ pub(crate) fn hpass_rows(
337 &src[r * src_stride..],360 &src[r * src_stride..],
338 t16,361 t16,
339 &mut out[r * block_w..(r + 1) * block_w],362 &mut out[r * block_w..(r + 1) * block_w],
363+ round0,
340 );364 );
341 }365 }
342 }366 }
343 367
344 /// The scalar reference for [`hpass_contig`] (lane-perf2's loop).368 /// 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) {
346 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit370 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit
347 // depth), so the products are exactly the i32 ones but the widening371 // depth), so the products are exactly the i32 ones but the widening
348 // multiply is one instruction per pair.372 // multiply is one instruction per pair.
@@ -351,7 +375,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
351 for t in 0..8 {375 for t in 0..8 {
352 sum += i32::from(t16[t]) * i32::from(w[t] as i16);376 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
353 }377 }
354- *o = sat16(round2(sum, INTER_ROUND_0));378+ *o = sat16(round2(sum, round0));
355 }379 }
356 }380 }
357 381
@@ -363,7 +387,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
363 #[cfg(target_arch = "x86_64")]387 #[cfg(target_arch = "x86_64")]
364 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract388 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
365 mod simd {389 mod simd {
366- use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1};390+ use super::{round2, sat16};
367 use std::arch::x86_64::*;391 use std::arch::x86_64::*;
368 392
369 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape393 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
@@ -372,15 +396,26 @@ mod simd {
372 #[inline]396 #[inline]
373 fn taps16(taps: &[i32; 8]) -> [i16; 8] {397 fn taps16(taps: &[i32; 8]) -> [i16; 8] {
374 [398 [
375- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,399+ taps[0] as i16,
376- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] 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,
377 ]407 ]
378 }408 }
379 409
380 #[inline]410 #[inline]
381 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {411 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
382 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);412 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+ ]
384 }419 }
385 420
386 /// Horizontal pass, AVX2: 16 outputs per iteration. Each 256-bit `madd`421 /// Horizontal pass, AVX2: 16 outputs per iteration. Each 256-bit `madd`
@@ -399,6 +434,7 @@ mod simd {
399 block_w: usize,434 block_w: usize,
400 t16: &[i16; 8],435 t16: &[i16; 8],
401 out: &mut [i16],436 out: &mut [i16],
437+ round0: u32,
402 ) {438 ) {
403 debug_assert!(out.len() >= rows * block_w);439 debug_assert!(out.len() >= rows * block_w);
404 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);440 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
@@ -409,7 +445,7 @@ mod simd {
409 _mm256_set1_epi32(tp[2]),445 _mm256_set1_epi32(tp[2]),
410 _mm256_set1_epi32(tp[3]),446 _mm256_set1_epi32(tp[3]),
411 ];447 ];
412- let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_0 - 1));448+ let rnd = _mm256_set1_epi32(1 << (round0 - 1));
413 for r in 0..rows {449 for r in 0..rows {
414 let sp = src.as_ptr().add(r * src_stride);450 let sp = src.as_ptr().add(r * src_stride);
415 let op = out.as_mut_ptr().add(r * block_w);451 let op = out.as_mut_ptr().add(r * block_w);
@@ -423,8 +459,8 @@ mod simd {
423 let so = _mm256_loadu_si256(sp.add(c + 2 * k + 1).cast());459 let so = _mm256_loadu_si256(sp.add(c + 2 * k + 1).cast());
424 o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));460 o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));
425 }461 }
426- e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), INTER_ROUND_0 as i32);462+ e = _mm256_sra_epi32(_mm256_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32));
427- o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);463+ o = _mm256_sra_epi32(_mm256_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32));
428 let lo = _mm256_unpacklo_epi32(e, o);464 let lo = _mm256_unpacklo_epi32(e, o);
429 let hi = _mm256_unpackhi_epi32(e, o);465 let hi = _mm256_unpackhi_epi32(e, o);
430 // `lo`/`hi` already hold the 16 outputs in order, four per466 // `lo`/`hi` already hold the 16 outputs in order, four per
@@ -437,7 +473,15 @@ mod simd {
437 if c < block_w {473 if c < block_w {
438 let s = r * src_stride + c;474 let s = r * src_stride + c;
439 let o = r * block_w + c;475 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+ );
441 }485 }
442 }486 }
443 }487 }
@@ -461,7 +505,9 @@ mod simd {
461 taps: &[i32; 8],505 taps: &[i32; 8],
462 acc: &mut [i32],506 acc: &mut [i32],
463 ) {507 ) {
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+ );
465 let tp = tap_pairs(&taps16(taps));511 let tp = tap_pairs(&taps16(taps));
466 for row in 0..rows {512 for row in 0..rows {
467 let ip = intermediate.as_ptr().add(row * src_stride);513 let ip = intermediate.as_ptr().add(row * src_stride);
@@ -484,7 +530,10 @@ mod simd {
484 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));530 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
485 }531 }
486 _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));532 _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));533+ _mm256_storeu_si256(
534+ ap.add(c + 8).cast(),
535+ _mm256_permute2x128_si256(lo, hi, 0x31),
536+ );
488 c += 16;537 c += 16;
489 }538 }
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);
@@ -570,10 +619,13 @@ mod simd {
570 taps: &[i32; 8],619 taps: &[i32; 8],
571 max: i32,620 max: i32,
572 dst: &mut [u16],621 dst: &mut [u16],
622+ round1: u32,
573 ) {623 ) {
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+ );
575 let tp = tap_pairs(&taps16(taps));627 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));
577 let mx = _mm256_set1_epi16(max as i16);629 let mx = _mm256_set1_epi16(max as i16);
578 for row in 0..rows {630 for row in 0..rows {
579 let ip = intermediate.as_ptr().add(row * src_stride);631 let ip = intermediate.as_ptr().add(row * src_stride);
@@ -592,15 +644,15 @@ mod simd {
592 lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));644 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));645 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
594 }646 }
595- lo = _mm256_srai_epi32(lo, INTER_ROUND_1 as i32);647+ lo = _mm256_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32));
596- hi = _mm256_srai_epi32(hi, INTER_ROUND_1 as i32);648+ hi = _mm256_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32));
597 // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four649 // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
598 // per lane in order, so this is c..c+16 in order.650 // per lane in order, so this is c..c+16 in order.
599 let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);651 let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
600 _mm256_storeu_si256(dp.add(c).cast(), v);652 _mm256_storeu_si256(dp.add(c).cast(), v);
601 c += 16;653 c += 16;
602 }654 }
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);
604 }656 }
605 }657 }
606 658
@@ -619,8 +671,9 @@ mod simd {
619 max: i32,671 max: i32,
620 dp: *mut u16,672 dp: *mut u16,
621 mut c: usize,673 mut c: usize,
674+ round1: u32,
622 ) {675 ) {
623- let rnd = _mm_set1_epi32(1 << (INTER_ROUND_1 - 1));676+ let rnd = _mm_set1_epi32(1 << (round1 - 1));
624 let mx = _mm_set1_epi16(max as i16);677 let mx = _mm_set1_epi16(max as i16);
625 while c + 4 <= block_w {678 while c + 4 <= block_w {
626 let wide = c + 8 <= block_w;679 let wide = c + 8 <= block_w;
@@ -631,7 +684,10 @@ mod simd {
631 continue;684 continue;
632 }685 }
633 let tv = _mm_set1_epi32(tp[k]);686 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+ );
635 let (a, b) = if wide {691 let (a, b) = if wide {
636 (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast()))692 (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast()))
637 } else {693 } else {
@@ -643,7 +699,10 @@ mod simd {
643 }699 }
644 }700 }
645 let v = _mm_min_epu16(701 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+ ),
647 mx,706 mx,
648 );707 );
649 if wide {708 if wide {
@@ -659,7 +718,7 @@ mod simd {
659 for (t, &tap) in taps.iter().enumerate() {718 for (t, &tap) in taps.iter().enumerate() {
660 sum += tap * i32::from(*ip.add(t * src_stride + c));719 sum += tap * i32::from(*ip.add(t * src_stride + c));
661 }720 }
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;
663 c += 1;722 c += 1;
664 }723 }
665 }724 }
@@ -677,13 +736,23 @@ mod simd {
677 taps: &[i32; 8],736 taps: &[i32; 8],
678 max: i32,737 max: i32,
679 dst: &mut [u16],738 dst: &mut [u16],
739+ round1: u32,
680 ) {740 ) {
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+ );
682 let tp = tap_pairs(&taps16(taps));744 let tp = tap_pairs(&taps16(taps));
683 for row in 0..rows {745 for row in 0..rows {
684 vpass_u16_tail_sse(746 vpass_u16_tail_sse(
685- intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps, max,747+ intermediate.as_ptr().add(row * src_stride),
686- dst.as_mut_ptr().add(row * block_w), 0,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,
687 );756 );
688 }757 }
689 }758 }
@@ -700,12 +769,19 @@ mod simd {
700 taps: &[i32; 8],769 taps: &[i32; 8],
701 acc: &mut [i32],770 acc: &mut [i32],
702 ) {771 ) {
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+ );
704 let tp = tap_pairs(&taps16(taps));775 let tp = tap_pairs(&taps16(taps));
705 for row in 0..rows {776 for row in 0..rows {
706 vpass_tail_sse(777 vpass_tail_sse(
707- intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps,778+ intermediate.as_ptr().add(row * src_stride),
708- acc.as_mut_ptr().add(row * block_w), 0,779+ block_w,
780+ src_stride,
781+ &tp,
782+ taps,
783+ acc.as_mut_ptr().add(row * block_w),
784+ 0,
709 );785 );
710 }786 }
711 }787 }
@@ -723,6 +799,7 @@ mod simd {
723 block_w: usize,799 block_w: usize,
724 t16: &[i16; 8],800 t16: &[i16; 8],
725 out: &mut [i16],801 out: &mut [i16],
802+ round0: u32,
726 ) {803 ) {
727 debug_assert!(out.len() >= rows * block_w);804 debug_assert!(out.len() >= rows * block_w);
728 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);805 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
@@ -733,7 +810,7 @@ mod simd {
733 _mm_set1_epi32(tp[2]),810 _mm_set1_epi32(tp[2]),
734 _mm_set1_epi32(tp[3]),811 _mm_set1_epi32(tp[3]),
735 ];812 ];
736- let rnd = _mm_set1_epi32(1 << (INTER_ROUND_0 - 1));813+ let rnd = _mm_set1_epi32(1 << (round0 - 1));
737 for r in 0..rows {814 for r in 0..rows {
738 let sp = src.as_ptr().add(r * src_stride);815 let sp = src.as_ptr().add(r * src_stride);
739 let op = out.as_mut_ptr().add(r * block_w);816 let op = out.as_mut_ptr().add(r * block_w);
@@ -747,8 +824,8 @@ mod simd {
747 let so = _mm_loadu_si128(sp.add(c + 2 * k + 1).cast());824 let so = _mm_loadu_si128(sp.add(c + 2 * k + 1).cast());
748 o = _mm_add_epi32(o, _mm_madd_epi16(so, tv[k]));825 o = _mm_add_epi32(o, _mm_madd_epi16(so, tv[k]));
749 }826 }
750- e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);827+ e = _mm_sra_epi32(_mm_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32));
751- o = _mm_srai_epi32(_mm_add_epi32(o, rnd), INTER_ROUND_0 as i32);828+ o = _mm_sra_epi32(_mm_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32));
752 let lo = _mm_unpacklo_epi32(e, o);829 let lo = _mm_unpacklo_epi32(e, o);
753 let hi = _mm_unpackhi_epi32(e, o);830 let hi = _mm_unpackhi_epi32(e, o);
754 _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));831 _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));
@@ -759,7 +836,7 @@ mod simd {
759 for t in 0..8 {836 for t in 0..8 {
760 sum += i32::from(t16[t]) * i32::from(*sp.add(c + t) as i16);837 sum += i32::from(t16[t]) * i32::from(*sp.add(c + t) as i16);
761 }838 }
762- *op.add(c) = sat16(round2(sum, INTER_ROUND_0));839+ *op.add(c) = sat16(round2(sum, round0));
763 c += 1;840 c += 1;
764 }841 }
765 }842 }
@@ -774,7 +851,15 @@ mod simd {
774 /// loop and it auto-vectorises. The edge case keeps the exact spec form851 /// loop and it auto-vectorises. The edge case keeps the exact spec form
775 /// (`sample`'s clamp per tap); both arms compute the same sums.852 /// (`sample`'s clamp per tap); both arms compute the same sums.
776 #[inline]853 #[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+) {
778 let block_w = out.len();863 let block_w = out.len();
779 let start = x0 - 3;864 let start = x0 - 3;
780 if start >= 0 && start as usize + block_w + 7 <= true_width {865 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
784 // bit depth), so the products are exactly the i32 ones above but869 // bit depth), so the products are exactly the i32 ones above but
785 // the widening multiply is one instruction per pair.870 // the widening multiply is one instruction per pair.
786 let t16 = [871 let t16 = [
787- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,872+ taps[0] as i16,
788- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] 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,
789 ];880 ];
790- hpass_contig(src, &t16, out);881+ hpass_contig(src, &t16, out, round0);
791 return;882 return;
792 }883 }
793 }884 }
@@ -797,7 +888,7 @@ fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, tap
797 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;888 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
798 sum += tap * i32::from(reference[row_base + x]);889 sum += tap * i32::from(reference[row_base + x]);
799 }890 }
800- *o = sat16(round2(sum, INTER_ROUND_0));891+ *o = sat16(round2(sum, round0));
801 }892 }
802 }893 }
803 894
@@ -815,6 +906,7 @@ fn horizontal_pass_unscaled(
815 block_w: usize,906 block_w: usize,
816 rows: usize,907 rows: usize,
817 intermediate: &mut [i16],908 intermediate: &mut [i16],
909+ round0: u32,
818 ) {910 ) {
819 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,911 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
820 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position912 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
@@ -838,8 +930,14 @@ fn horizontal_pass_unscaled(
838 let span = block_w + 7;930 let span = block_w + 7;
839 if base + (rows - 1) * stride + span <= reference.len() {931 if base + (rows - 1) * stride + span <= reference.len() {
840 let t16 = [932 let t16 = [
841- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,933+ taps[0] as i16,
842- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] 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,
843 ];941 ];
844 hpass_rows(942 hpass_rows(
845 &reference[base..],943 &reference[base..],
@@ -848,6 +946,7 @@ fn horizontal_pass_unscaled(
848 block_w,946 block_w,
849 &t16,947 &t16,
850 &mut intermediate[..rows * block_w],948 &mut intermediate[..rows * block_w],
949+ round0,
851 );950 );
852 return;951 return;
853 }952 }
@@ -856,9 +955,11 @@ fn horizontal_pass_unscaled(
856 let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize;955 let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize;
857 let out = &mut intermediate[r * block_w..(r + 1) * block_w];956 let out = &mut intermediate[r * block_w..(r + 1) * block_w];
858 if identity {957 if identity {
859- let gain = 128 >> INTER_ROUND_0;958+ let gain = 128 >> round0;
860 if x0 >= 0 && x0 as usize + block_w <= true_width {959 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+ {
862 for (o, &s) in out.iter_mut().zip(src) {963 for (o, &s) in out.iter_mut().zip(src) {
863 *o = (gain * i32::from(s)) as i16;964 *o = (gain * i32::from(s)) as i16;
864 }965 }
@@ -871,7 +972,7 @@ fn horizontal_pass_unscaled(
871 }972 }
872 continue;973 continue;
873 }974 }
874- hpass_row(reference, y * stride, true_width, x0, taps, out);975+ hpass_row(reference, y * stride, true_width, x0, taps, out, round0);
875 }976 }
876 }977 }
877 978
@@ -882,7 +983,14 @@ fn horizontal_pass_unscaled(
882 /// eight slots. `acc` is left holding the unrounded sums.983 /// eight slots. `acc` is left holding the unrounded sums.
883 #[inline]984 #[inline]
884 #[allow(unsafe_code)]985 #[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+) {
886 #[cfg(target_arch = "x86_64")]994 #[cfg(target_arch = "x86_64")]
887 {995 {
888 match simd_level() {996 match simd_level() {
@@ -903,7 +1011,11 @@ pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, src_stride: usize,
903 }1011 }
904 for row in 0..rows {1012 for row in 0..rows {
905 vpass_row_scalar(1013 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,
907 &mut acc[row * block_w..(row + 1) * block_w],1019 &mut acc[row * block_w..(row + 1) * block_w],
908 );1020 );
909 }1021 }
@@ -923,6 +1035,7 @@ fn vpass_row_u16(
923 taps: &[i32; 8],1035 taps: &[i32; 8],
924 max: i32,1036 max: i32,
925 dst: &mut [u16],1037 dst: &mut [u16],
1038+ round1: u32,
926 ) {1039 ) {
927 #[cfg(target_arch = "x86_64")]1040 #[cfg(target_arch = "x86_64")]
928 {1041 {
@@ -932,11 +1045,33 @@ fn vpass_row_u16(
932 // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which1045 // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which
933 // the debug asserts pin.1046 // the debug asserts pin.
934 SimdLevel::Avx2 => {1047 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+ };
936 return;1060 return;
937 }1061 }
938 SimdLevel::Sse41 => {1062 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+ };
940 return;1075 return;
941 }1076 }
942 SimdLevel::Scalar => {}1077 SimdLevel::Scalar => {}
@@ -944,8 +1079,14 @@ fn vpass_row_u16(
944 }1079 }
945 for row in 0..rows {1080 for row in 0..rows {
946 vpass_row_u16_scalar(1081 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,
948 &mut dst[row * block_w..(row + 1) * block_w],1088 &mut dst[row * block_w..(row + 1) * block_w],
1089+ round1,
949 );1090 );
950 }1091 }
951 }1092 }
@@ -959,25 +1100,36 @@ fn vpass_row_u16_scalar(
959 taps: &[i32; 8],1100 taps: &[i32; 8],
960 max: i32,1101 max: i32,
961 dst: &mut [u16],1102 dst: &mut [u16],
1103+ round1: u32,
962 ) {1104 ) {
963 for (c, d) in dst[..block_w].iter_mut().enumerate() {1105 for (c, d) in dst[..block_w].iter_mut().enumerate() {
964 let mut sum = 0i32;1106 let mut sum = 0i32;
965 for (t, &tap) in taps.iter().enumerate() {1107 for (t, &tap) in taps.iter().enumerate() {
966 sum += tap * i32::from(intermediate[(row + t) * src_stride + c]);1108 sum += tap * i32::from(intermediate[(row + t) * src_stride + c]);
967 }1109 }
968- *d = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;1110+ *d = round2(sum, round1).clamp(0, max) as u16;
969 }1111 }
970 }1112 }
971 1113
972 /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).1114 /// 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+) {
974 acc[..block_w].fill(0);1123 acc[..block_w].fill(0);
975 for (t, &tap) in taps.iter().enumerate() {1124 for (t, &tap) in taps.iter().enumerate() {
976 if tap == 0 {1125 if tap == 0 {
977 continue;1126 continue;
978 }1127 }
979 let base = (row + t) * src_stride;1128 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+ {
981 *a += tap * i32::from(s);1133 *a += tap * i32::from(s);
982 }1134 }
983 }1135 }
@@ -1037,7 +1189,8 @@ pub(crate) fn predict(
1037 y_q4: i32,1189 y_q4: i32,
1038 block_w: usize,1190 block_w: usize,
1039 block_h: usize,1191 block_h: usize,
1040- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1192+ dst: &mut [u16],
1193+ fctx: &crate::decode::FrameCtx,
1041 ) {1194 ) {
1042 predict_with_filter(1195 predict_with_filter(
1043 reference,1196 reference,
@@ -1054,7 +1207,8 @@ pub(crate) fn predict(
1054 // `Regular` (the decoder's own inter path calls1207 // `Regular` (the decoder's own inter path calls
1055 // `predict_with_filters` with the kernels it parsed).1208 // `predict_with_filters` with the kernels it parsed).
1056 fctx.interp_filter.get(),1209 fctx.interp_filter.get(),
1057- dst, fctx,1210+ dst,
1211+ fctx,
1058 );1212 );
1059 }1213 }
1060 1214
@@ -1072,7 +1226,8 @@ pub(crate) fn predict_with_filter(
1072 block_w: usize,1226 block_w: usize,
1073 block_h: usize,1227 block_h: usize,
1074 filter_kind: InterpFilterKind,1228 filter_kind: InterpFilterKind,
1075- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1229+ dst: &mut [u16],
1230+ fctx: &crate::decode::FrameCtx,
1076 ) {1231 ) {
1077 predict_with_filters(1232 predict_with_filters(
1078 reference,1233 reference,
@@ -1085,7 +1240,8 @@ pub(crate) fn predict_with_filter(
1085 block_h,1240 block_h,
1086 filter_kind,1241 filter_kind,
1087 filter_kind,1242 filter_kind,
1088- dst, fctx,1243+ dst,
1244+ fctx,
1089 );1245 );
1090 }1246 }
1091 1247
@@ -1105,11 +1261,24 @@ pub(crate) fn predict_with_filters(
1105 block_h: usize,1261 block_h: usize,
1106 h_kind: InterpFilterKind,1262 h_kind: InterpFilterKind,
1107 v_kind: InterpFilterKind,1263 v_kind: InterpFilterKind,
1108- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1264+ dst: &mut [u16],
1265+ fctx: &crate::decode::FrameCtx,
1109 ) {1266 ) {
1110 predict_with_filters_kern(1267 predict_with_filters_kern(
1111- reference, stride, true_width, true_height, x_q4, y_q4, block_w,1268+ reference,
1112- block_h, block_w, block_h, h_kind, v_kind, dst, fctx,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,
1113 );1282 );
1114 }1283 }
1115 1284
@@ -1135,7 +1304,8 @@ pub(crate) fn predict_with_filters_kern(
1135 kern_h: usize,1304 kern_h: usize,
1136 h_kind: InterpFilterKind,1305 h_kind: InterpFilterKind,
1137 v_kind: InterpFilterKind,1306 v_kind: InterpFilterKind,
1138- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1307+ dst: &mut [u16],
1308+ fctx: &crate::decode::FrameCtx,
1139 ) {1309 ) {
1140 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");1310 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1141 assert!(!reference.is_empty(), "a reference plane has samples");1311 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1173,7 +1343,9 @@ pub(crate) fn predict_with_filters_kern(
1173 let out = &mut dst[row * block_w..(row + 1) * block_w];1343 let out = &mut dst[row * block_w..(row + 1) * block_w];
1174 // lane-perf2: an interior row is one contiguous copy.1344 // lane-perf2: an interior row is one contiguous copy.
1175 if x0 >= 0 && x0 as usize + block_w <= true_width {1345 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+ {
1177 // The common widths get a constant-length copy: at 81349 // The common widths get a constant-length copy: at 8
1178 // samples a `memcpy` call costs more than the move it1350 // samples a `memcpy` call costs more than the move it
1179 // makes, and 8x8 is the most common inter block on real1351 // makes, and 8x8 is the most common inter block on real
@@ -1219,15 +1391,23 @@ pub(crate) fn predict_with_filters_kern(
1219 // block's own first row where the pass would have put the 4th.1391 // block's own first row where the pass would have put the 4th.
1220 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1392 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1221 let max = crate::decode::sample_max(fctx);1393 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)));
1222 // lane-mc2: a whole-pel horizontal position makes the horizontal pass the1397 // lane-mc2: a whole-pel horizontal position makes the horizontal pass the
1223- // identity tap, whose output is `s << 4` (`Round2(128 * s, InterRound0)`1398+ // identity tap, whose output is `(128 >> round0) * s` (`Round2(128 * s,
1224- // with the tap 128). The vertical pass then computes1399+ // round0)` with the tap 128). The vertical pass then computes
1225- // `Round2(sum(tap * (s << 4)), InterRound1)`, which is the same 8-tap sum1400+ // `Round2(sum(tap * ((128 >> round0) * s)), round1)`, which is the same
1226- // taken straight off the reference rows with every tap scaled by 16 --1401+ // 8-tap sum taken straight off the reference rows with every tap scaled
1227- // bit-identical, and it skips materialising `block_h + 7` intermediate1402+ // by `128 >> round0` -- bit-identical (128 is a multiple of `2^round0` at
1228- // rows. Interior blocks only; an edge block still needs the clamped read.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.
1229 if xfrac != 0 || yfrac == 0 {1406 if xfrac != 0 || yfrac == 0 {
1230 // fall through to the two-pass path1407 // fall through to the two-pass path
1408+ if xfrac != 0 || yfrac != 0 {
1409+ hit!(MC_SUBPEL_HITS);
1410+ }
1231 } else {1411 } else {
1232 let top = y0 - 3;1412 let top = y0 - 3;
1233 if top >= 01413 if top >= 0
@@ -1239,15 +1419,25 @@ pub(crate) fn predict_with_filters_kern(
1239 if base + (block_h + 6) * stride + block_w <= reference.len() {1419 if base + (block_h + 6) * stride + block_w <= reference.len() {
1240 let mut v16 = [0i32; 8];1420 let mut v16 = [0i32; 8];
1241 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {1421 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1242- *o = t * 16;1422+ *o = t * (128 >> round0);
1243 }1423 }
1244 // SAFETY: samples are below `2^15` at every supported bit1424 // SAFETY: samples are below `2^15` at every supported bit
1245 // depth, so the same bytes read as `i16` are the same values;1425 // depth, so the same bytes read as `i16` are the same values;
1246 // the length is unchanged.1426 // the length is unchanged.
1247 #[allow(unsafe_code)]1427 #[allow(unsafe_code)]
1248- let src: &[i16] =1428+ let src: &[i16] = unsafe {
1249- unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };1429+ 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);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+ );
1251 #[cfg(test)]1441 #[cfg(test)]
1252 crate::encode::stage_since(1, stage_t);1442 crate::encode::stage_since(1, stage_t);
1253 return;1443 return;
@@ -1256,17 +1446,36 @@ pub(crate) fn predict_with_filters_kern(
1256 }1446 }
1257 with_scratch(rows, block_w, |intermediate, _acc| {1447 with_scratch(rows, block_w, |intermediate, _acc| {
1258 horizontal_pass_unscaled(1448 horizontal_pass_unscaled(
1259- reference, stride, true_width, true_height, x0,1449+ reference,
1260- if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,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,
1261 intermediate,1458 intermediate,
1459+ round0,
1262 );1460 );
1263 if yfrac == 0 {1461 if yfrac == 0 {
1462+ // The vertical filter is the identity tap here:
1463+ // `Round2(128 * a, round1) == Round2(a, round1 - 7)` exactly.
1264 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {1464 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;
1266 }1466 }
1267 return;1467 return;
1268 }1468 }
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+ );
1270 });1479 });
1271 1480
1272 #[cfg(test)]1481 #[cfg(test)]
@@ -1304,6 +1513,13 @@ pub fn predict_scaled_hits() -> usize {
1304 }1513 }
1305 1514
1306 thread_local! {1515 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+
1307 /// lane-hbdinter: how many inter predictions this thread has produced1523 /// lane-hbdinter: how many inter predictions this thread has produced
1308 /// (single-reference, scaled, and the compound intermediate entry). The1524 /// (single-reference, scaled, and the compound intermediate entry). The
1309 /// 10-bit inter gate hard-asserts this moved, so a stream that coded1525 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
@@ -1343,6 +1559,12 @@ pub fn inter_pred_hits() -> usize {
1343 INTER_PRED_HITS.with(|c| c.get())1559 INTER_PRED_HITS.with(|c| c.get())
1344 }1560 }
1345 1561
1562+/// Current value of [`MC_SUBPEL_HITS`].
1563+#[allow(dead_code)] // reader is test-only (the 12-bit inter witness); dead in non-test builds
1564+pub(crate) fn mc_subpel_hits() -> usize {
1565+ MC_SUBPEL_HITS.with(|c| c.get())
1566+}
1567+
1346 fn round_pow2_64(value: i64, shift: u32) -> i64 {1568 fn round_pow2_64(value: i64, shift: u32) -> i64 {
1347 if shift == 0 {1569 if shift == 0 {
1348 value1570 value
@@ -1386,6 +1608,7 @@ fn horizontal_scaled_pass(
1386 rows: usize,1608 rows: usize,
1387 h_kind: InterpFilterKind,1609 h_kind: InterpFilterKind,
1388 intermediate: &mut [i16],1610 intermediate: &mut [i16],
1611+ round0: u32,
1389 ) {1612 ) {
1390 let x_step_qn = round_pow2_64(x_scale_fp, 4);1613 let x_step_qn = round_pow2_64(x_scale_fp, 4);
1391 let off = (x_scale_fp - REF_NO_SCALE) * 8;1614 let off = (x_scale_fp - REF_NO_SCALE) * 8;
@@ -1407,7 +1630,7 @@ fn horizontal_scaled_pass(
1407 let x = int_pel + t as i32 - 3;1630 let x = int_pel + t as i32 - 3;
1408 sum += tap * sample(reference, stride, true_width, true_height, x, y);1631 sum += tap * sample(reference, stride, true_width, true_height, x, y);
1409 }1632 }
1410- intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;1633+ intermediate[r * block_w + c] = round2(sum, round0) as i16;
1411 }1634 }
1412 }1635 }
1413 }1636 }
@@ -1439,11 +1662,16 @@ fn horizontal_pass(
1439 rows: usize,1662 rows: usize,
1440 h_kind: InterpFilterKind,1663 h_kind: InterpFilterKind,
1441 intermediate: &mut [i16],1664 intermediate: &mut [i16],
1665+ round0: u32,
1442 ) {1666 ) {
1443 if x_scale_fp == REF_NO_SCALE {1667 if x_scale_fp == REF_NO_SCALE {
1444 let (h_wide, h_narrow) = h_kind.tables();1668 let (h_wide, h_narrow) = h_kind.tables();
1445 let xfrac = x_q4.rem_euclid(16) as usize;1669 let xfrac = x_q4.rem_euclid(16) as usize;
1446- let taps = if kern_w <= 4 { &h_narrow[xfrac] } else { &h_wide[xfrac] };1670+ let taps = if kern_w <= 4 {
1671+ &h_narrow[xfrac]
1672+ } else {
1673+ &h_wide[xfrac]
1674+ };
1447 horizontal_pass_unscaled(1675 horizontal_pass_unscaled(
1448 reference,1676 reference,
1449 stride,1677 stride,
@@ -1455,12 +1683,24 @@ fn horizontal_pass(
1455 block_w,1683 block_w,
1456 rows,1684 rows,
1457 intermediate,1685 intermediate,
1686+ round0,
1458 );1687 );
1459 return;1688 return;
1460 }1689 }
1461 horizontal_scaled_pass(1690 horizontal_scaled_pass(
1462- reference, stride, true_width, true_height, x_q4, y0, x_scale_fp, block_w, kern_w,1691+ reference,
1463- rows, h_kind, intermediate,1692+ stride,
1693+ true_width,
1694+ true_height,
1695+ x_q4,
1696+ y0,
1697+ x_scale_fp,
1698+ block_w,
1699+ kern_w,
1700+ rows,
1701+ h_kind,
1702+ intermediate,
1703+ round0,
1464 );1704 );
1465 }1705 }
1466 1706
@@ -1491,11 +1731,25 @@ pub(crate) fn predict_scaled(
1491 block_h: usize,1731 block_h: usize,
1492 h_kind: InterpFilterKind,1732 h_kind: InterpFilterKind,
1493 v_kind: InterpFilterKind,1733 v_kind: InterpFilterKind,
1494- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1734+ dst: &mut [u16],
1735+ fctx: &crate::decode::FrameCtx,
1495 ) {1736 ) {
1496 predict_scaled_kern(1737 predict_scaled_kern(
1497- reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,1738+ reference,
1498- block_w, block_h, block_w, block_h, h_kind, v_kind, dst, fctx,1739+ stride,
1740+ true_width,
1741+ true_height,
1742+ x_q4,
1743+ y_q4,
1744+ x_scale_fp,
1745+ block_w,
1746+ block_h,
1747+ block_w,
1748+ block_h,
1749+ h_kind,
1750+ v_kind,
1751+ dst,
1752+ fctx,
1499 );1753 );
1500 }1754 }
1501 1755
@@ -1516,7 +1770,8 @@ pub(crate) fn predict_scaled_kern(
1516 kern_h: usize,1770 kern_h: usize,
1517 h_kind: InterpFilterKind,1771 h_kind: InterpFilterKind,
1518 v_kind: InterpFilterKind,1772 v_kind: InterpFilterKind,
1519- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1773+ dst: &mut [u16],
1774+ fctx: &crate::decode::FrameCtx,
1520 ) {1775 ) {
1521 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");1776 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1522 assert!(!reference.is_empty(), "a reference plane has samples");1777 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1539,19 +1794,41 @@ pub(crate) fn predict_scaled_kern(
1539 1794
1540 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1795 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1541 let max = crate::decode::sample_max(fctx);1796 let max = crate::decode::sample_max(fctx);
1797+ let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
1542 with_scratch(rows, block_w, |intermediate, _acc| {1798 with_scratch(rows, block_w, |intermediate, _acc| {
1543 horizontal_pass(1799 horizontal_pass(
1544- reference, stride, true_width, true_height, x_q4,1800+ reference,
1545- if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,1801+ stride,
1546- kern_w, rows, h_kind, intermediate,1802+ true_width,
1803+ true_height,
1804+ x_q4,
1805+ if yfrac == 0 { y0 + 3 } else { y0 },
1806+ x_scale_fp,
1807+ block_w,
1808+ kern_w,
1809+ rows,
1810+ h_kind,
1811+ intermediate,
1812+ round0,
1547 );1813 );
1548 if yfrac == 0 {1814 if yfrac == 0 {
1815+ // Identity vertical tap: `Round2(128 * a, round1) ==
1816+ // Round2(a, round1 - 7)` exactly.
1549 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {1817 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;1818+ *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16;
1551 }1819 }
1552 return;1820 return;
1553 }1821 }
1554- vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);1822+ vpass_row_u16(
1823+ intermediate,
1824+ block_w,
1825+ block_w,
1826+ block_h,
1827+ v_filter,
1828+ max,
1829+ dst,
1830+ round1,
1831+ );
1555 });1832 });
1556 }1833 }
1557 1834
@@ -1572,17 +1849,39 @@ pub(crate) fn predict_maybe_scaled(
1572 block_h: usize,1849 block_h: usize,
1573 h_kind: InterpFilterKind,1850 h_kind: InterpFilterKind,
1574 v_kind: InterpFilterKind,1851 v_kind: InterpFilterKind,
1575- dst: &mut [u16], fctx: &crate::decode::FrameCtx,1852+ dst: &mut [u16],
1853+ fctx: &crate::decode::FrameCtx,
1576 ) {1854 ) {
1577 if x_scale_fp == REF_NO_SCALE {1855 if x_scale_fp == REF_NO_SCALE {
1578 predict_with_filters(1856 predict_with_filters(
1579- reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind,1857+ reference,
1580- v_kind, dst, fctx,1858+ stride,
1859+ true_width,
1860+ true_height,
1861+ x_q4,
1862+ y_q4,
1863+ block_w,
1864+ block_h,
1865+ h_kind,
1866+ v_kind,
1867+ dst,
1868+ fctx,
1581 );1869 );
1582 } else {1870 } else {
1583 predict_scaled(1871 predict_scaled(
1584- reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w,1872+ reference,
1585- block_h, h_kind, v_kind, dst, fctx,1873+ stride,
1874+ true_width,
1875+ true_height,
1876+ x_q4,
1877+ y_q4,
1878+ x_scale_fp,
1879+ block_w,
1880+ block_h,
1881+ h_kind,
1882+ v_kind,
1883+ dst,
1884+ fctx,
1586 );1885 );
1587 }1886 }
1588 }1887 }
@@ -1620,7 +1919,7 @@ const DIST_PRECISION_BITS: u32 = 4;
1620 /// Panics when `dst` is not `block_w * block_h` long, or the reference is1919 /// Panics when `dst` is not `block_w * block_h` long, or the reference is
1621 /// empty.1920 /// empty.
1622 #[allow(clippy::too_many_arguments)]1921 #[allow(clippy::too_many_arguments)]
1623-pub fn predict_compound_intermediate(1922+pub(crate) fn predict_compound_intermediate(
1624 reference: &[u16],1923 reference: &[u16],
1625 stride: usize,1924 stride: usize,
1626 true_width: usize,1925 true_width: usize,
@@ -1633,17 +1932,31 @@ pub fn predict_compound_intermediate(
1633 h_kind: InterpFilterKind,1932 h_kind: InterpFilterKind,
1634 v_kind: InterpFilterKind,1933 v_kind: InterpFilterKind,
1635 dst: &mut [i32],1934 dst: &mut [i32],
1935+ fctx: &crate::decode::FrameCtx,
1636 ) {1936 ) {
1637 predict_compound_intermediate_kern(1937 predict_compound_intermediate_kern(
1638- reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,1938+ reference,
1639- block_w, block_h, block_w, block_h, h_kind, v_kind, dst,1939+ stride,
1940+ true_width,
1941+ true_height,
1942+ x_q4,
1943+ y_q4,
1944+ x_scale_fp,
1945+ block_w,
1946+ block_h,
1947+ block_w,
1948+ block_h,
1949+ h_kind,
1950+ v_kind,
1951+ dst,
1952+ fctx,
1640 );1953 );
1641 }1954 }
1642 1955
1643 /// [`predict_compound_intermediate`] with the 4-tap decision from the block's1956 /// [`predict_compound_intermediate`] with the 4-tap decision from the block's
1644 /// true dims (see [`predict_with_filters_kern`]).1957 /// true dims (see [`predict_with_filters_kern`]).
1645 #[allow(clippy::too_many_arguments)]1958 #[allow(clippy::too_many_arguments)]
1646-pub fn predict_compound_intermediate_kern(1959+pub(crate) fn predict_compound_intermediate_kern(
1647 reference: &[u16],1960 reference: &[u16],
1648 stride: usize,1961 stride: usize,
1649 true_width: usize,1962 true_width: usize,
@@ -1658,6 +1971,7 @@ pub fn predict_compound_intermediate_kern(
1658 h_kind: InterpFilterKind,1971 h_kind: InterpFilterKind,
1659 v_kind: InterpFilterKind,1972 v_kind: InterpFilterKind,
1660 dst: &mut [i32],1973 dst: &mut [i32],
1974+ fctx: &crate::decode::FrameCtx,
1661 ) {1975 ) {
1662 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");1976 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1663 assert!(!reference.is_empty(), "a reference plane has samples");1977 assert!(!reference.is_empty(), "a reference plane has samples");
@@ -1682,10 +1996,15 @@ pub fn predict_compound_intermediate_kern(
1682 };1996 };
1683 1997
1684 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1998 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1999+ // lane-av112bit: the horizontal pass shares `predict_with_filters_kern`'s
2000+ // `round_0` (the compound VERTICAL round below is `INTER_ROUND_1_COMPOUND`
2001+ // at every bit depth), so the identity-tap gain moves with it the same way.
2002+ let (round0, _round1) = round_pair(u32::from(crate::decode::bit_depth(fctx)));
1685 // lane-mc2: the unscaled whole-pel horizontal position is the identity2003 // lane-mc2: the unscaled whole-pel horizontal position is the identity
1686- // tap, whose intermediate is `s << 4`, so the vertical pass is the same2004+ // tap, whose intermediate is `(128 >> round0) * s`, so the vertical pass
1687- // 8-tap sum taken straight off the reference rows with the taps scaled by2005+ // is the same 8-tap sum taken straight off the reference rows with the
1688- // 16 (see `predict_with_filters_kern`). Interior blocks only.2006+ // taps scaled by that gain (see `predict_with_filters_kern`). Interior
2007+ // blocks only.
1689 let x0 = x_q4.div_euclid(16);2008 let x0 = x_q4.div_euclid(16);
1690 if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 {2009 if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 {
1691 let top = y0 - 3;2010 let top = y0 - 3;
@@ -1698,13 +2017,14 @@ pub fn predict_compound_intermediate_kern(
1698 if base + (block_h + 6) * stride + block_w <= reference.len() {2017 if base + (block_h + 6) * stride + block_w <= reference.len() {
1699 let mut v16 = [0i32; 8];2018 let mut v16 = [0i32; 8];
1700 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {2019 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1701- *o = t * 16;2020+ *o = t * (128 >> round0);
1702 }2021 }
1703 // SAFETY: samples are below `2^15` at every supported bit2022 // SAFETY: samples are below `2^15` at every supported bit
1704 // depth, so the same bytes read as `i16` are the same values.2023 // depth, so the same bytes read as `i16` are the same values.
1705 #[allow(unsafe_code)]2024 #[allow(unsafe_code)]
1706- let src: &[i16] =2025+ let src: &[i16] = unsafe {
1707- unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };2026+ std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len())
2027+ };
1708 vpass_row(&src[base..], block_w, stride, block_h, &v16, dst);2028 vpass_row(&src[base..], block_w, stride, block_h, &v16, dst);
1709 for d in dst.iter_mut() {2029 for d in dst.iter_mut() {
1710 *d = round2(*d, INTER_ROUND_1_COMPOUND);2030 *d = round2(*d, INTER_ROUND_1_COMPOUND);
@@ -1715,9 +2035,19 @@ pub fn predict_compound_intermediate_kern(
1715 }2035 }
1716 with_scratch(rows, block_w, |intermediate, _acc| {2036 with_scratch(rows, block_w, |intermediate, _acc| {
1717 horizontal_pass(2037 horizontal_pass(
1718- reference, stride, true_width, true_height, x_q4,2038+ reference,
1719- if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,2039+ stride,
1720- kern_w, rows, h_kind, intermediate,2040+ true_width,
2041+ true_height,
2042+ x_q4,
2043+ if yfrac == 0 { y0 + 3 } else { y0 },
2044+ x_scale_fp,
2045+ block_w,
2046+ kern_w,
2047+ rows,
2048+ h_kind,
2049+ intermediate,
2050+ round0,
1721 );2051 );
1722 if yfrac == 0 {2052 if yfrac == 0 {
1723 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.2053 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
@@ -1739,16 +2069,24 @@ pub fn predict_compound_intermediate_kern(
1739 /// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s2069 /// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
1740 /// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound2070 /// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
1741 /// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this2071 /// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
1742-/// function does not cover -- decode.rs still refuses those by name.2072+/// function does not cover -- see [`blend_masked_compound`]/[`diffwtd_mask`];
2073+/// every kind absorbs the same CONV_BUF gain drop at 12 bits
2074+/// ([`round_delta`]), witnessed by the 12-bit compound stream gate.
1743 pub(crate) fn combine_compound(2075 pub(crate) fn combine_compound(
1744 pred0: &[i32],2076 pred0: &[i32],
1745 pred1: &[i32],2077 pred1: &[i32],
1746 fwd_weight: i32,2078 fwd_weight: i32,
1747 bck_weight: i32,2079 bck_weight: i32,
1748- dst: &mut [u16], fctx: &crate::decode::FrameCtx,2080+ dst: &mut [u16],
2081+ fctx: &crate::decode::FrameCtx,
1749 ) {2082 ) {
1750 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");2083 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1751 assert_eq!(dst.len(), pred0.len(), "the destination is the block");2084 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
2085+ // lane-av112bit: `round_bits` is `2*FILTER_BITS - round_0 - round_1`
2086+ // with the frame's own `round_0`, i.e. `INTER_POST_ROUND` minus
2087+ // [`round_delta`] -- the CONV_BUF gain drops from 16x to 4x at 12-bit
2088+ // (`round_0` 5, compound `round_1` 7) and this final round absorbs it.
2089+ let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx)));
1752 for i in 0..dst.len() {2090 for i in 0..dst.len() {
1753 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)2091 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
1754 // applies the two shifts SEPARATELY: a truncating `>>2092 // applies the two shifts SEPARATELY: a truncating `>>
@@ -1758,7 +2096,7 @@ pub(crate) fn combine_compound(
1758 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the2096 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
1759 // dropped low 4 bits are non-zero.2097 // dropped low 4 bits are non-zero.
1760 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;2098 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
1761- dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)2099+ dst[i] = round2(sum >> DIST_PRECISION_BITS, post_round)
1762 .clamp(0, crate::decode::sample_max(fctx)) as u16;2100 .clamp(0, crate::decode::sample_max(fctx)) as u16;
1763 }2101 }
1764 }2102 }
@@ -1773,15 +2111,22 @@ pub(crate) fn combine_compound(
1773 /// produces give the identical `diff` libaom computes. `round` is2111 /// produces give the identical `diff` libaom computes. `round` is
1774 /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for2112 /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
1775 /// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).2113 /// 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) {2114+pub(crate) fn diffwtd_mask(
2115+ pred0: &[i32],
2116+ pred1: &[i32],
2117+ inv: bool,
2118+ mask: &mut [u8],
2119+ fctx: &crate::decode::FrameCtx,
2120+) {
1777 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");2121 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1778 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");2122 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
1779 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS2123 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
1780 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the2124 // - 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`2125+ // bit-depth headroom the CONV_BUF domain carries, minus the [`round_delta`]
1782- // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s2126+ // that moves `round_0` itself at 12-bit (`convolve.h:83`'s
1783- // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.2127+ // `intbufrange > 16`; at 12-bit this is 14 - 5 - 7 + 4 == 6).
1784- let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);2128+ let bd = u32::from(crate::decode::bit_depth(fctx));
2129+ let round = INTER_POST_ROUND + bd.saturating_sub(8) - round_delta(bd);
1785 for i in 0..mask.len() {2130 for i in 0..mask.len() {
1786 let diff = round2((pred0[i] - pred1[i]).abs(), round);2131 let diff = round2((pred0[i] - pred1[i]).abs(), round);
1787 let m = (38 + diff / 16).clamp(0, 64);2132 let m = (38 + diff / 16).clamp(0, 64);
@@ -1808,11 +2153,13 @@ pub(crate) fn blend_masked_compound(
1808 w: usize,2153 w: usize,
1809 h: usize,2154 h: usize,
1810 subsampled: bool,2155 subsampled: bool,
1811- dst: &mut [u16], fctx: &crate::decode::FrameCtx,2156+ dst: &mut [u16],
2157+ fctx: &crate::decode::FrameCtx,
1812 ) {2158 ) {
1813 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");2159 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
1814 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");2160 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
1815 assert_eq!(dst.len(), w * h, "the destination is the block");2161 assert_eq!(dst.len(), w * h, "the destination is the block");
2162+ let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx)));
1816 for i in 0..h {2163 for i in 0..h {
1817 for j in 0..w {2164 for j in 0..w {
1818 let m = if subsampled {2165 let m = if subsampled {
@@ -1828,7 +2175,12 @@ pub(crate) fn blend_masked_compound(
1828 i32::from(mask[i * mask_stride + j])2175 i32::from(mask[i * mask_stride + j])
1829 };2176 };
1830 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;2177 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;2178+ // `post_round` above: `INTER_POST_ROUND - round_delta` -- see
2179+ // [`combine_compound`] (the same CONV_BUF gain absorption; the
2180+ // `>> 6` above is bit-depth free because the CONV_BUF relative
2181+ // weights are).
2182+ dst[i * w + j] =
2183+ round2(res, post_round).clamp(0, crate::decode::sample_max(fctx)) as u16;
1832 }2184 }
1833 }2185 }
1834 }2186 }
@@ -1860,6 +2212,7 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1860 InterpFilterKind::Regular,2212 InterpFilterKind::Regular,
1861 InterpFilterKind::Regular,2213 InterpFilterKind::Regular,
1862 &mut pred0,2214 &mut pred0,
2215+ fctx,
1863 );2216 );
1864 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");2217 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
1865 2218
@@ -1872,8 +2225,8 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1872 #[cfg(test)]2225 #[cfg(test)]
1873 mod tests {2226 mod tests {
1874 use super::{2227 use super::{
1875- InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter,2228+ predict, predict_scaled, predict_with_filter, predict_with_filters, InterpFilterKind,
1876- predict_with_filters,2229+ REF_NO_SCALE,
1877 };2230 };
1878 2231
1879 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma2232 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
@@ -1945,7 +2298,8 @@ mod tests {
1945 16,2298 16,
1946 16,2299 16,
1947 InterpFilterKind::Smooth,2300 InterpFilterKind::Smooth,
1948- &mut dst, fctx,2301+ &mut dst,
2302+ fctx,
1949 );2303 );
1950 #[rustfmt::skip]2304 #[rustfmt::skip]
1951 let expected_row0: [u16; 16] =2305 let expected_row0: [u16; 16] =
@@ -2010,7 +2364,8 @@ mod tests {
2010 4 * 16,2364 4 * 16,
2011 6,2365 6,
2012 6,2366 6,
2013- &mut dst, fctx,2367+ &mut dst,
2368+ fctx,
2014 );2369 );
2015 for row in 0..6 {2370 for row in 0..6 {
2016 for col in 0..6 {2371 for col in 0..6 {
@@ -2043,7 +2398,8 @@ mod tests {
2043 5 * 16,2398 5 * 16,
2044 4,2399 4,
2045 4,2400 4,
2046- &mut dst, fctx,2401+ &mut dst,
2402+ fctx,
2047 );2403 );
2048 for row in 0..4 {2404 for row in 0..4 {
2049 for col in 0..4 {2405 for col in 0..4 {
@@ -2075,7 +2431,8 @@ mod tests {
2075 5 * 16 + yfrac,2431 5 * 16 + yfrac,
2076 5,2432 5,
2077 5,2433 5,
2078- &mut dst, fctx,2434+ &mut dst,
2435+ fctx,
2079 );2436 );
2080 assert!(2437 assert!(
2081 dst.iter().all(|&v| v == 142),2438 dst.iter().all(|&v| v == 142),
@@ -2109,7 +2466,8 @@ mod tests {
2109 3 * 16,2466 3 * 16,
2110 4,2467 4,
2111 4,2468 4,
2112- &mut horiz, fctx,2469+ &mut horiz,
2470+ fctx,
2113 );2471 );
2114 let mut vert = vec![0u16; 4 * 4];2472 let mut vert = vec![0u16; 4 * 4];
2115 predict(2473 predict(
@@ -2121,7 +2479,8 @@ mod tests {
2121 3 * 16 + 8,2479 3 * 16 + 8,
2122 4,2480 4,
2123 4,2481 4,
2124- &mut vert, fctx,2482+ &mut vert,
2483+ fctx,
2125 );2484 );
2126 2485
2127 for row in 0..4 {2486 for row in 0..4 {
@@ -2164,7 +2523,8 @@ mod tests {
2164 -50 * 16 + 5,2523 -50 * 16 + 5,
2165 4,2524 4,
2166 4,2525 4,
2167- &mut dst, fctx,2526+ &mut dst,
2527+ fctx,
2168 );2528 );
2169 let expected = reference[0]; // the whole plane clamps to the top-left corner2529 let expected = reference[0]; // the whole plane clamps to the top-left corner
2170 assert!(2530 assert!(
@@ -2182,7 +2542,8 @@ mod tests {
2182 50 * 16 + 5,2542 50 * 16 + 5,
2183 4,2543 4,
2184 4,2544 4,
2185- &mut dst2, fctx,2545+ &mut dst2,
2546+ fctx,
2186 );2547 );
2187 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner2548 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
2188 assert!(2549 assert!(
@@ -2217,7 +2578,8 @@ mod tests {
2217 8,2578 8,
2218 InterpFilterKind::Regular,2579 InterpFilterKind::Regular,
2219 InterpFilterKind::Regular,2580 InterpFilterKind::Regular,
2220- &mut expected, fctx,2581+ &mut expected,
2582+ fctx,
2221 );2583 );
2222 let mut got = vec![0u16; block_w * 8];2584 let mut got = vec![0u16; block_w * 8];
2223 predict_scaled(2585 predict_scaled(
@@ -2232,7 +2594,8 @@ mod tests {
2232 8,2594 8,
2233 InterpFilterKind::Regular,2595 InterpFilterKind::Regular,
2234 InterpFilterKind::Regular,2596 InterpFilterKind::Regular,
2235- &mut got, fctx,2597+ &mut got,
2598+ fctx,
2236 );2599 );
2237 assert_eq!(2600 assert_eq!(
2238 got, expected,2601 got, expected,
@@ -2272,26 +2635,52 @@ mod tests {
2272 for frac in 0..16usize {2635 for frac in 0..16usize {
2273 let taps = &table[frac];2636 let taps = &table[frac];
2274 let t16 = [2637 let t16 = [
2275- taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,2638+ taps[0] as i16,
2276- taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,2639+ taps[1] as i16,
2640+ taps[2] as i16,
2641+ taps[3] as i16,
2642+ taps[4] as i16,
2643+ taps[5] as i16,
2644+ taps[6] as i16,
2645+ taps[7] as i16,
2277 ];2646 ];
2278 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {2647 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
2279 let src: Vec<u16> = (0..w + 7)2648 let src: Vec<u16> = (0..w + 7)
2280 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)2649 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
2281 .collect();2650 .collect();
2282 let mut want = vec![0i16; w];2651 let mut want = vec![0i16; w];
2283- super::hpass_contig_scalar(&src, &t16, &mut want);2652+ super::hpass_contig_scalar(&src, &t16, &mut want, 3);
2284 let mut got = vec![0i16; w];2653 let mut got = vec![0i16; w];
2285- super::hpass_contig(&src, &t16, &mut got);2654+ super::hpass_contig(&src, &t16, &mut got, 3);
2286 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");2655 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
2287 #[cfg(target_arch = "x86_64")]2656 #[cfg(target_arch = "x86_64")]
2288 {2657 {
2289 let mut sse = vec![0i16; w];2658 let mut sse = vec![0i16; w];
2290- unsafe { super::simd::hpass_sse2(&src, 0, 1, sse.len(), &t16, &mut sse) };2659+ unsafe {
2660+ super::simd::hpass_sse2(
2661+ &src,
2662+ 0,
2663+ 1,
2664+ sse.len(),
2665+ &t16,
2666+ &mut sse,
2667+ 3,
2668+ )
2669+ };
2291 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");2670 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
2292 if std::arch::is_x86_feature_detected!("avx2") {2671 if std::arch::is_x86_feature_detected!("avx2") {
2293 let mut avx = vec![0i16; w];2672 let mut avx = vec![0i16; w];
2294- unsafe { super::simd::hpass_avx2(&src, 0, 1, avx.len(), &t16, &mut avx) };2673+ unsafe {
2674+ super::simd::hpass_avx2(
2675+ &src,
2676+ 0,
2677+ 1,
2678+ avx.len(),
2679+ &t16,
2680+ &mut avx,
2681+ 3,
2682+ )
2683+ };
2295 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");2684 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
2296 }2685 }
2297 }2686 }
@@ -2308,10 +2697,11 @@ mod tests {
2308 /// is a claim about the FILTER TABLES, not about a sample: every kernel's2697 /// is a claim about the FILTER TABLES, not about a sample: every kernel's
2309 /// positive taps sum to at most `S+` and its negative ones to `S-`, so a2698 /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
2310 /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored2699 /// 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 four2700+ /// value is that over `1 << round_0`. This enumerates all four
2312 /// filter kinds, both their wide and narrow tables and all 16 phases at2701 /// filter kinds, both their wide and narrow tables and all 16 phases at
2313- /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses2702+ /// the deepest sample this decoder accepts (12-bit now -- lane-av112bit
2314- /// 12-bit by name) and pins the result inside `i16` -- so the SIMD2703+ /// lifted the refusal, with `round_0` at 5 there and 3 at 8/10-bit) and
2704+ /// pins the result inside `i16` -- so the SIMD
2315 /// stores' `packs_epi32` never saturates on a motion-compensation path.2705 /// stores' `packs_epi32` never saturates on a motion-compensation path.
2316 #[test]2706 #[test]
2317 fn horizontal_intermediate_fits_i16() {2707 fn horizontal_intermediate_fits_i16() {
@@ -2321,7 +2711,8 @@ mod tests {
2321 InterpFilterKind::Sharp,2711 InterpFilterKind::Sharp,
2322 InterpFilterKind::Bilinear,2712 InterpFilterKind::Bilinear,
2323 ];2713 ];
2324- let max_sample = 1023i32; // 10-bit2714+ // (max sample, the frame's `round_0`) per supported bit depth.
2715+ for (max_sample, round0) in [(255i32, 3u32), (1023, 3), (4095, 5)] {
2325 let (mut worst_lo, mut worst_hi) = (0i32, 0i32);2716 let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
2326 for &kind in &kinds {2717 for &kind in &kinds {
2327 let (wide, narrow) = kind.tables();2718 let (wide, narrow) = kind.tables();
@@ -2329,16 +2720,18 @@ mod tests {
2329 for taps in table {2720 for taps in table {
2330 let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();2721 let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
2331 let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();2722 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));2723+ worst_hi = worst_hi.max(super::round2(max_sample * pos, round0));
2333- worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0));2724+ worst_lo = worst_lo.min(super::round2(max_sample * neg, round0));
2334 }2725 }
2335 }2726 }
2336 }2727 }
2337 assert!(2728 assert!(
2338 worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),2729 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"2730+ "the {max_sample}-sample (round_0 {round0}) intermediate range \
2731+ [{worst_lo}, {worst_hi}] must fit i16"
2340 );2732 );
2341 }2733 }
2734+ }
2342 2735
2343 /// lane-perf5: the vertical pass's SIMD kernels against the scalar2736 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
2344 /// reference, over the same domain as2737 /// reference, over the same domain as
@@ -2368,29 +2761,58 @@ mod tests {
2368 };2761 };
2369 let reference: Vec<u16> = (0..width * height).map(|_| (rng() % 256) as u16).collect();2762 let reference: Vec<u16> = (0..width * height).map(|_| (rng() % 256) as u16).collect();
2370 let mut checked = 0usize;2763 let mut checked = 0usize;
2371- for &kind in &[InterpFilterKind::Regular, InterpFilterKind::Smooth, InterpFilterKind::Sharp] {2764+ for &kind in &[
2765+ InterpFilterKind::Regular,
2766+ InterpFilterKind::Smooth,
2767+ InterpFilterKind::Sharp,
2768+ ] {
2372 let (v_wide, v_narrow) = kind.tables();2769 let (v_wide, v_narrow) = kind.tables();
2373- for (bw, bh) in [(4usize, 4usize), (5, 4), (8, 8), (16, 16), (12, 8), (32, 16)] {2770+ for (bw, bh) in [
2771+ (4usize, 4usize),
2772+ (5, 4),
2773+ (8, 8),
2774+ (16, 16),
2775+ (12, 8),
2776+ (32, 16),
2777+ ] {
2374 for yfrac in 1..16i32 {2778 for yfrac in 1..16i32 {
2375 let (x0, y0) = (7i32, 9i32);2779 let (x0, y0) = (7i32, 9i32);
2376- let taps = if bh <= 4 { &v_narrow[yfrac as usize] } else { &v_wide[yfrac as usize] };2780+ let taps = if bh <= 4 {
2781+ &v_narrow[yfrac as usize]
2782+ } else {
2783+ &v_wide[yfrac as usize]
2784+ };
2377 let mut want = vec![0u16; bw * bh];2785 let mut want = vec![0u16; bw * bh];
2378 for row in 0..bh {2786 for row in 0..bh {
2379 for col in 0..bw {2787 for col in 0..bw {
2380 let mut sum = 0i32;2788 let mut sum = 0i32;
2381 for (t, &tap) in taps.iter().enumerate() {2789 for (t, &tap) in taps.iter().enumerate() {
2382 let y = y0 - 3 + row as i32 + t as i32;2790 let y = y0 - 3 + row as i32 + t as i32;
2383- let s = i32::from(reference[y as usize * width + x0 as usize + col]);2791+ let s =
2792+ i32::from(reference[y as usize * width + x0 as usize + col]);
2384 // The identity horizontal tap's output.2793 // The identity horizontal tap's output.
2385 sum += tap * (s << 4);2794 sum += tap * (s << 4);
2386 }2795 }
2387- want[row * bw + col] = super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;2796+ want[row * bw + col] =
2797+ super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;
2388 }2798 }
2389 }2799 }
2390 let mut got = vec![0u16; bw * bh];2800 let mut got = vec![0u16; bw * bh];
2391 super::predict_with_filters_kern(2801 super::predict_with_filters_kern(
2392- &reference, width, width, height, x0 * 16, y0 * 16 + yfrac,2802+ &reference,
2393- bw, bh, bw, bh, kind, kind, &mut got, fctx,2803+ width,
2804+ width,
2805+ height,
2806+ x0 * 16,
2807+ y0 * 16 + yfrac,
2808+ bw,
2809+ bh,
2810+ bw,
2811+ bh,
2812+ kind,
2813+ kind,
2814+ &mut got,
2815+ fctx,
2394 );2816 );
2395 assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}");2817 assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}");
2396 checked += 1;2818 checked += 1;
@@ -2436,7 +2858,14 @@ mod tests {
2436 .collect();2858 .collect();
2437 for row in [0usize, 1, 4] {2859 for row in [0usize, 1, 4] {
2438 let mut want = vec![0i32; w];2860 let mut want = vec![0i32; w];
2439- super::vpass_row_scalar(&inter[row * st..], w, st, 0, taps, &mut want);2861+ super::vpass_row_scalar(
2862+ &inter[row * st..],
2863+ w,
2864+ st,
2865+ 0,
2866+ taps,
2867+ &mut want,
2868+ );
2440 let mut got = vec![0i32; w];2869 let mut got = vec![0i32; w];
2441 super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);2870 super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);
2442 assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");2871 assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");
@@ -2444,13 +2873,37 @@ mod tests {
2444 {2873 {
2445 if std::arch::is_x86_feature_detected!("sse4.1") {2874 if std::arch::is_x86_feature_detected!("sse4.1") {
2446 let mut sse = vec![0i32; w];2875 let mut sse = vec![0i32; w];
2447- unsafe { super::simd::vpass_sse41(&inter[row * st..], w, st, 1, taps, &mut sse) };2876+ unsafe {
2448- assert_eq!(sse, want, "sse4.1 w={w} frac={frac} row={row}");2877+ super::simd::vpass_sse41(
2878+ &inter[row * st..],
2879+ w,
2880+ st,
2881+ 1,
2882+ taps,
2883+ &mut sse,
2884+ )
2885+ };
2886+ assert_eq!(
2887+ sse, want,
2888+ "sse4.1 w={w} frac={frac} row={row}"
2889+ );
2449 }2890 }
2450 if std::arch::is_x86_feature_detected!("avx2") {2891 if std::arch::is_x86_feature_detected!("avx2") {
2451 let mut avx = vec![0i32; w];2892 let mut avx = vec![0i32; w];
2452- unsafe { super::simd::vpass_avx2(&inter[row * st..], w, st, 1, taps, &mut avx) };2893+ unsafe {
2453- assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");2894+ super::simd::vpass_avx2(
2895+ &inter[row * st..],
2896+ w,
2897+ st,
2898+ 1,
2899+ taps,
2900+ &mut avx,
2901+ )
2902+ };
2903+ assert_eq!(
2904+ avx, want,
2905+ "avx2 w={w} frac={frac} row={row}"
2906+ );
2454 }2907 }
2455 }2908 }
2456 // lane-mc: the rounding-fused form, over both2909 // lane-mc: the rounding-fused form, over both
@@ -2459,28 +2912,78 @@ mod tests {
2459 // `round2(_, InterRound1).clamp(0, max)`.2912 // `round2(_, InterRound1).clamp(0, max)`.
2460 for max in [255i32, 1023] {2913 for max in [255i32, 1023] {
2461 let mut want_u16 = vec![0u16; w];2914 let mut want_u16 = vec![0u16; w];
2462- super::vpass_row_u16_scalar(&inter, w, st, row, taps, max, &mut want_u16);2915+ super::vpass_row_u16_scalar(
2916+ &inter,
2917+ w,
2918+ st,
2919+ row,
2920+ taps,
2921+ max,
2922+ &mut want_u16,
2923+ 11,
2924+ );
2463 for (d, &a) in want_u16.iter().zip(want.iter()) {2925 for (d, &a) in want_u16.iter().zip(want.iter()) {
2464 assert_eq!(2926 assert_eq!(
2465 i32::from(*d),2927 i32::from(*d),
2466- super::round2(a, super::INTER_ROUND_1).clamp(0, max),2928+ super::round2(a, super::INTER_ROUND_1)
2929+ .clamp(0, max),
2467 "the fused reference is the two-step one"2930 "the fused reference is the two-step one"
2468 );2931 );
2469 }2932 }
2470 let mut got_u16 = vec![0u16; w];2933 let mut got_u16 = vec![0u16; w];
2471- super::vpass_row_u16(&inter[row * st..], w, st, 1, taps, max, &mut got_u16);2934+ super::vpass_row_u16(
2472- assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}");2935+ &inter[row * st..],
2936+ w,
2937+ st,
2938+ 1,
2939+ taps,
2940+ max,
2941+ &mut got_u16,
2942+ 11,
2943+ );
2944+ assert_eq!(
2945+ got_u16, want_u16,
2946+ "fused w={w} frac={frac} row={row} max={max}"
2947+ );
2473 #[cfg(target_arch = "x86_64")]2948 #[cfg(target_arch = "x86_64")]
2474 {2949 {
2475 if std::arch::is_x86_feature_detected!("sse4.1") {2950 if std::arch::is_x86_feature_detected!("sse4.1") {
2476 let mut sse = vec![0u16; w];2951 let mut sse = vec![0u16; w];
2477- unsafe { super::simd::vpass_row_u16_sse41(&inter[row * st..], w, st, 1, taps, max, &mut sse) };2952+ unsafe {
2478- assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}");2953+ super::simd::vpass_row_u16_sse41(
2954+ &inter[row * st..],
2955+ w,
2956+ st,
2957+ 1,
2958+ taps,
2959+ max,
2960+ &mut sse,
2961+ 11,
2962+ )
2963+ };
2964+ assert_eq!(
2965+ sse, want_u16,
2966+ "fused sse4.1 w={w} max={max}"
2967+ );
2479 }2968 }
2480 if std::arch::is_x86_feature_detected!("avx2") {2969 if std::arch::is_x86_feature_detected!("avx2") {
2481 let mut avx = vec![0u16; w];2970 let mut avx = vec![0u16; w];
2482- unsafe { super::simd::vpass_row_u16_avx2(&inter[row * st..], w, st, 1, taps, max, &mut avx) };2971+ unsafe {
2483- assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}");2972+ super::simd::vpass_row_u16_avx2(
2973+ &inter[row * st..],
2974+ w,
2975+ st,
2976+ 1,
2977+ taps,
2978+ max,
2979+ &mut avx,
2980+ 11,
2981+ )
2982+ };
2983+ assert_eq!(
2984+ avx, want_u16,
2985+ "fused avx2 w={w} max={max}"
2986+ );
2484 }2987 }
2485 }2988 }
2486 }2989 }
crates/ec-av1/src/refusal_inventory.rsmodified+27 -3
@@ -72,7 +72,17 @@ const REFUSALS: &[&str] = &[
72 // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`)72 // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`)
73 // still runs: it now reports `reached = 0` with the same non-vacuous73 // still runs: it now reports `reached = 0` with the same non-vacuous
74 // premise (allow_intrabc frames + decoded sub-8 leaves).74 // 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 named
76+ // 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+ // lane-av112bitc: compound joined the witnessed set (six-frame 12-bit
81+ // compound stream byte-exact vs ffmpeg; the combines already absorbed
82+ // the CONV_BUF gain drop through `INTER_POST_ROUND - delta`).
83+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
84+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)",
85+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
76 // lane-av1txr: the silent-garbage guard. A 4:4:4/4:2:2 stream used to86 // lane-av1txr: the silent-garbage guard. A 4:4:4/4:2:2 stream used to
77 // decode with no refusal and wrong pixels (every chroma extent is87 // decode with no refusal and wrong pixels (every chroma extent is
78 // hardcoded 4:2:0, the probe emits 4:2:0 planes only); it is now refused88 // hardcoded 4:2:0, the probe emits 4:2:0 planes only); it is now refused
@@ -347,9 +357,23 @@ const PROVEN: &[(&str, &str)] = &[
347 "a motion_mode symbol for a block shape with no CDF row here",357 "a motion_mode symbol for a block shape with no CDF row here",
348 "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row",358 "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row",
349 ),359 ),
360+ // lane-av112bit: real-aomenc 12-bit streams, each refused by name
361+ // (the gates encode with aomenc --bit-depth=12 and assert the exact
362+ // string; the pixel witnesses are the same battery's Ok arms).
363+ // lane-av112bitc: the compound pair left with its refusal -- the
364+ // six-frame compound stream now DECODES byte-exact
365+ // (`a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact`).
350 (366 (
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)",367+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)",
352- "a_twelve_bit_sequence_header_is_refused_by_name",368+ "a_12bit_warped_motion_stream_is_refused_by_name",
369+ ),
370+ (
371+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)",
372+ "a_12bit_film_grain_stream_is_refused_by_name",
373+ ),
374+ (
375+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
376+ "a_12bit_screen_content_stream_is_refused_by_name",
353 ),377 ),
354 // lane-av1txr: the guard's own gate builds a profile-1 and a profile-2378 // lane-av1txr: the guard's own gate builds a profile-1 and a profile-2
355 // sequence header by hand and asserts each refuses by name while the379 // sequence header by hand and asserts each refuses by name while the
crates/ec-av1/src/restoration.rsmodified+242 -72
@@ -63,7 +63,12 @@ fn inverse_recenter(r: u32, v: u32) -> u32 {
63 /// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed63 /// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed
64 /// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around64 /// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around
65 /// `reference`.65 /// `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 {
67 let v = decode_subexp_msac(dec, n, k);72 let v = decode_subexp_msac(dec, n, k);
68 if (reference << 1) <= n {73 if (reference << 1) <= n {
69 inverse_recenter(reference, v)74 inverse_recenter(reference, v)
@@ -74,7 +79,13 @@ fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32,
74 79
75 /// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter`80 /// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter`
76 /// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`.81 /// 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 {
78 let n = (high - low) as u32;89 let n = (high - low) as u32;
79 let r = (reference - low).clamp(0, n as i32) as u32;90 let r = (reference - low).clamp(0, n as i32) as u32;
80 decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low91 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
274 285
275 /// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating286 /// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating
276 /// `reference` in place (the running per-plane, per-tile reference state).287 /// `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 {
278 let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter);293 let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter);
279 let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter);294 let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter);
280 let info = WienerInfo { vfilter, hfilter };295 let info = WienerInfo { vfilter, hfilter };
@@ -462,7 +477,8 @@ pub(crate) fn read_lr(
462 reference: &mut [(WienerInfo, SgrprojInfo); 3],477 reference: &mut [(WienerInfo, SgrprojInfo); 3],
463 mi_row: u32,478 mi_row: u32,
464 mi_col: u32,479 mi_col: u32,
465- sb_mi: u32, fctx: &crate::decode::FrameCtx,480+ sb_mi: u32,
481+ fctx: &crate::decode::FrameCtx,
466 ) {482 ) {
467 if !lr.uses_lr {483 if !lr.uses_lr {
468 return;484 return;
@@ -636,8 +652,16 @@ fn lr_sample(
636 ) -> i32 {652 ) -> i32 {
637 let col_c = col.clamp(0, plane_w as i64 - 1) as usize;653 let col_c = col.clamp(0, plane_w as i64 - 1) as usize;
638 i32::from(654 i32::from(
639- lr_src_row(cdef, deblocked, stride, plane_w, plane_h, stripe_v_start, stripe_v_end, row)655+ lr_src_row(
640- [col_c],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],
641 )665 )
642 }666 }
643 667
@@ -671,7 +695,11 @@ fn lr_src_row<'a>(
671 let dist = stripe_v_start as i64 - 1 - row;695 let dist = stripe_v_start as i64 - 1 - row;
672 (696 (
673 deblocked,697 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+ },
675 )703 )
676 }704 }
677 } else if stripe_v_end == plane_h {705 } else if stripe_v_end == plane_h {
@@ -712,7 +740,8 @@ fn apply_wiener_stripe(
712 h_end: usize,740 h_end: usize,
713 v_start: usize,741 v_start: usize,
714 v_end: usize,742 v_end: usize,
715- info: &WienerInfo, fctx: &crate::decode::FrameCtx,743+ info: &WienerInfo,
744+ fctx: &crate::decode::FrameCtx,
716 ) {745 ) {
717 let w = h_end - h_start;746 let w = h_end - h_start;
718 let h = v_end - v_start;747 let h = v_end - v_start;
@@ -720,8 +749,26 @@ fn apply_wiener_stripe(
720 return;749 return;
721 }750 }
722 let bd = i64::from(crate::decode::bit_depth(fctx));751 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.
723 let wiener_bias = 1i64 << (bd + 3);769 let wiener_bias = 1i64 << (bd + 3);
724 let wiener_limit = 1i64 << (bd + 5);770 let wiener_limit = 1i64 << (bd + 5);
771+ let (round0, round1) = crate::mc::round_pair(bd as u32);
725 let rows = h + 6;772 let rows = h + 6;
726 // lane-perf7: reused across stripes, as the sgrproj `ab` grids are --773 // lane-perf7: reused across stripes, as the sgrproj `ab` grids are --
727 // this was a fresh allocation per stripe. Every entry is written below.774 // this was a fresh allocation per stripe. Every entry is written below.
@@ -738,28 +785,50 @@ fn apply_wiener_stripe(
738 // stripe substitution is resolved once per row by `lr_src_row`, and only785 // stripe substitution is resolved once per row by `lr_src_row`, and only
739 // a unit touching the plane's left or right edge needs the clamped copy.786 // a unit touching the plane's left or right edge needs the clamped copy.
740 let hf = &info.hfilter;787 let hf = &info.hfilter;
741- let t16: [i16; 8] =788+ 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];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+ ];
743 // lane-mc: the intermediate is `i16` now. Both bounds are inside that798 // 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 the799+ // range at every supported bit depth (the centred sum's own range,
745- // kernel's saturating store composes with this clamp instead of changing800+ // `|kernel| <= 348` against `2^bd - 1` samples, never reaches them), so
746- // it: `[-2048, 8191]` at 8-bit, `[-8192, 32767]` at 10.801+ // the kernel's saturating store composes with this clamp instead of
747- let (lo_bound, hi_bound) = (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16);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+ };
748 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));813 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
749 for r in 0..rows {814 for r in 0..rows {
750 let row = v_start as i64 - 3 + r as i64;815 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+ );
752 let lo = h_start as i64 - 3;819 let lo = h_start as i64 - 3;
753 let out = &mut inter[r * w..r * w + w];820 let out = &mut inter[r * w..r * w + w];
754- if lo >= 0 && lo as usize + w + 7 <= plane_w {821+ // The row the pass convolves, contiguous when the block sits inside
755- crate::mc::hpass_contig(&src[lo as usize..], &t16, out);822+ // the plane and the clamped copy (`hbuf`) at an edge.
756- } else {823+ let interior = lo >= 0 && lo as usize + w + 7 <= plane_w;
824+ if !interior {
757 hbuf.clear();825 hbuf.clear();
758 hbuf.extend(826 hbuf.extend(
759 (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]),827 (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]),
760 );828 );
761- crate::mc::hpass_contig(&hbuf, &t16, out);
762 }829 }
830+ let row_slice: &[u16] = if interior { &src[lo as usize..] } else { &hbuf };
831+ crate::mc::hpass_contig(row_slice, &t16, out, round0);
763 for v in out.iter_mut() {832 for v in out.iter_mut() {
764 *v = (*v).clamp(lo_bound, hi_bound);833 *v = (*v).clamp(lo_bound, hi_bound);
765 }834 }
@@ -769,7 +838,9 @@ fn apply_wiener_stripe(
769 // instead of taking a thread-local read per output sample.838 // instead of taking a thread-local read per output sample.
770 let smax = i64::from(crate::decode::sample_max(fctx));839 let smax = i64::from(crate::decode::sample_max(fctx));
771 // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves840 // 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`).
773 let vf = &info.vfilter;844 let vf = &info.vfilter;
774 let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0];845 let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0];
775 let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));846 let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
@@ -779,7 +850,7 @@ fn apply_wiener_stripe(
779 crate::mc::vpass_row(&inter[r * w..], w, w, 1, &taps, &mut acc);850 crate::mc::vpass_row(&inter[r * w..], w, w, 1, &taps, &mut acc);
780 let dst = &mut out[(v_start + r) * stride + h_start..][..w];851 let dst = &mut out[(v_start + r) * stride + h_start..][..w];
781 for (o, &a) in dst.iter_mut().zip(acc.iter()) {852 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;
783 }854 }
784 }855 }
785 WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc);856 WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc);
@@ -815,31 +886,27 @@ thread_local! {
815 // `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other886 // `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other
816 // transcription slip.887 // transcription slip.
817 const SGR_X_BY_XPLUS1: [i32; 256] = [888 const SGR_X_BY_XPLUS1: [i32; 256] = [
818- 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239,889+ 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243,
819- 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247,890+ 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249,
820- 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250,891+ 249, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252,
821- 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252,892+ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253,
822- 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253,893+ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
823- 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,
824- 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254,895+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
825- 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,
826- 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,
827- 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,898+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
828- 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,899+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
829- 254, 254, 254, 254, 254, 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,
830- 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,
831- 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,
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,
836 ];903 ];
837 904
838 /// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25`905 /// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25`
839 /// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`.906 /// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`.
840 const SGR_ONE_BY_X: [i32; 25] = [907 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,908+ 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228,
842- 178, 171, 164,909+ 216, 205, 195, 186, 178, 171, 164,
843 ];910 ];
844 911
845 const SGRPROJ_MTABLE_BITS: u32 = 20;912 const SGRPROJ_MTABLE_BITS: u32 = 20;
@@ -877,7 +944,8 @@ fn compute_ab(
877 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every944 // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every
878 // page then faulted in on first touch. Every entry is written below, so945 // page then faulted in on first touch. Every entry is written below, so
879 // the resize's fill value is never read.946 // 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,
881 ) {949 ) {
882 let gw = w + 2;950 let gw = w + 2;
883 let gh = h + 2;951 let gh = h + 2;
@@ -927,8 +995,9 @@ fn compute_ab(
927 let i = gi as i64 - 1;995 let i = gi as i64 - 1;
928 {996 {
929 let mut accumulate = |row: i64, add: bool| {997 let mut accumulate = |row: i64, add: bool| {
930- let src =998+ let src = lr_src_row(
931- lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row);999+ cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row,
1000+ );
932 fill_clamped_row(src, plane_w, base_col, &mut samp);1001 fill_clamped_row(src, plane_w, base_col, &mut samp);
933 if add {1002 if add {
934 for ((c_a, c_b), &px) in col_a.iter_mut().zip(col_b.iter_mut()).zip(samp.iter())1003 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(
967 a_row[gj] = a;1036 a_row[gj] = a;
968 b_row[gj] = b;1037 b_row[gj] = b;
969 }1038 }
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+ );
971 let dump_gj = 6i64 - h_start as i64 + 1;1048 let dump_gj = 6i64 - h_start as i64 + 1;
972 if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) {1049 if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) {
973 let gj = dump_gj as usize;1050 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
1006 let b_s = round2_u31(b, bd_shift);1083 let b_s = round2_u31(b, bd_shift);
1007 let p = (a_s * n - b_s * b_s).max(0);1084 let p = (a_s * n - b_s * b_s).max(0);
1008 let a_val = SGR_X_BY_XPLUS1[z_index(p, s)];1085 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+ );
1010 (a_val, b_val)1090 (a_val, b_val)
1011 }1091 }
1012 1092
1013 /// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time1093 /// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time
1014 /// under AVX2 (the kernel is that arithmetic lane-wise, same widths).1094 /// under AVX2 (the kernel is that arithmetic lane-wise, same widths).
1015 fn ab_row(1095 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,
1017 out: &mut [(i32, i64)],1102 out: &mut [(i32, i64)],
1018 ) {1103 ) {
1019 let mut done = 0usize;1104 let mut done = 0usize;
@@ -1054,7 +1139,12 @@ mod sgr_simd {
1054 #[target_feature(enable = "avx2")]1139 #[target_feature(enable = "avx2")]
1055 #[allow(clippy::too_many_arguments)]1140 #[allow(clippy::too_many_arguments)]
1056 pub unsafe fn ab_row_avx2(1141 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,
1058 out: &mut [(i32, i64)],1148 out: &mut [(i32, i64)],
1059 ) -> usize {1149 ) -> usize {
1060 let len = out.len().min(a_row.len()).min(b_row.len());1150 let len = out.len().min(a_row.len()).min(b_row.len());
@@ -1070,8 +1160,16 @@ mod sgr_simd {
1070 let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32);1160 let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32);
1071 let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32);1161 let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32);
1072 let sh_bd = _mm_cvtsi32_si128(bd_shift as i32);1162 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) });1163+ let rnd_a = _mm256_set1_epi32(if bd_shift == 0 {
1074- let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (bd_shift - 1) });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+ });
1075 let mut av = [0i32; 8];1173 let mut av = [0i32; 8];
1076 let mut bv = [0i32; 8];1174 let mut bv = [0i32; 8];
1077 let mut gj = 0usize;1175 let mut gj = 0usize;
@@ -1115,7 +1213,11 @@ mod sgr_simd {
1115 /// width narrower).1213 /// width narrower).
1116 #[inline]1214 #[inline]
1117 fn round2_u31(value: i32, shift: u32) -> i32 {1215 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+ }
1119 }1221 }
1120 1222
1121 /// Copies one source row's `out.len()` samples starting at `base_col` into a1223 /// Copies one source row's `out.len()` samples starting at `base_col` into a
@@ -1150,7 +1252,8 @@ fn apply_sgrproj_stripe(
1150 h_end: usize,1252 h_end: usize,
1151 v_start: usize,1253 v_start: usize,
1152 v_end: usize,1254 v_end: usize,
1153- info: &SgrprojInfo, fctx: &crate::decode::FrameCtx,1255+ info: &SgrprojInfo,
1256+ fctx: &crate::decode::FrameCtx,
1154 ) {1257 ) {
1155 let w = h_end - h_start;1258 let w = h_end - h_start;
1156 let h = v_end - v_start;1259 let h = v_end - v_start;
@@ -1166,10 +1269,16 @@ fn apply_sgrproj_stripe(
1166 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))1269 (std::mem::take(&mut m.0), std::mem::take(&mut m.1))
1167 });1270 });
1168 if r0 > 0 {1271 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+ );
1170 }1276 }
1171 if r1 > 0 {1277 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+ );
1173 }1282 }
1174 let ab0 = (r0 > 0).then_some(&buf0);1283 let ab0 = (r0 > 0).then_some(&buf0);
1175 let ab1 = (r1 > 0).then_some(&buf1);1284 let ab1 = (r1 > 0).then_some(&buf1);
@@ -1185,7 +1294,9 @@ fn apply_sgrproj_stripe(
1185 let bytes: Vec<i32> = (59..=61)1294 let bytes: Vec<i32> = (59..=61)
1186 .flat_map(|row| {1295 .flat_map(|row| {
1187 (5..=7).map(move |col| {1296 (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+ )
1189 })1300 })
1190 })1301 })
1191 .collect();1302 .collect();
@@ -1265,7 +1376,8 @@ fn apply_sgrproj_stripe(
1265 let (a_ur, b_ur) = ab[idx(i - 1, j + 1)];1376 let (a_ur, b_ur) = ab[idx(i - 1, j + 1)];
1266 let (a_dl, b_dl) = ab[idx(i + 1, j - 1)];1377 let (a_dl, b_dl) = ab[idx(i + 1, j - 1)];
1267 let (a_dr, b_dr) = ab[idx(i + 1, j + 1)];1378 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;
1269 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;1381 let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
1270 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);1382 let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
1271 v += xq[1] as i64 * (flt1 - u);1383 v += xq[1] as i64 * (flt1 - u);
@@ -1278,9 +1390,15 @@ fn apply_sgrproj_stripe(
1278 "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \1390 "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \
1279 ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \1391 ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \
1280 u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}",1392 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)],1393+ ab[idx(i, j)],
1282- ab[idx(i, j + 1)], ab[idx(i - 1, j - 1)], ab[idx(i - 1, j + 1)],1394+ ab[idx(i - 1, j)],
1283- ab[idx(i + 1, j - 1)], ab[idx(i + 1, j + 1)]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)]
1284 );1402 );
1285 }1403 }
1286 }1404 }
@@ -1311,7 +1429,8 @@ fn filter_restoration_unit(
1311 v_start: usize,1429 v_start: usize,
1312 v_end: usize,1430 v_end: usize,
1313 ss_y: u32,1431 ss_y: u32,
1314- filter: UnitFilter, fctx: &crate::decode::FrameCtx,1432+ filter: UnitFilter,
1433+ fctx: &crate::decode::FrameCtx,
1315 ) {1434 ) {
1316 let full_stripe_height = 64usize >> ss_y;1435 let full_stripe_height = 64usize >> ss_y;
1317 let runit_offset = 8usize >> ss_y;1436 let runit_offset = 8usize >> ss_y;
@@ -1333,10 +1452,32 @@ fn filter_restoration_unit(
1333 }1452 }
1334 match filter {1453 match filter {
1335 UnitFilter::Wiener(info) => apply_wiener_stripe(1454 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,
1337 ),1467 ),
1338 UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(1468 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,
1340 ),1481 ),
1341 UnitFilter::None => {}1482 UnitFilter::None => {}
1342 }1483 }
@@ -1395,12 +1536,16 @@ pub(crate) fn apply_loop_restoration_plane(
1395 let out = unsafe { so.get() };1536 let out = unsafe { so.get() };
1396 for rrow in r_lo..r_hi {1537 for rrow in r_lo..r_hi {
1397 lr_unit_row(1538 lr_unit_row(
1398- out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,1539+ out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane,
1399- plane, rrow, &rows, fctx,1540+ rrow, &rows, fctx,
1400 );1541 );
1401 }1542 }
1402 });1543 });
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+ );
1404 return;1549 return;
1405 };1550 };
1406 for rrow in r_lo..r_hi.min(rows.len()) {1551 for rrow in r_lo..r_hi.min(rows.len()) {
@@ -1435,7 +1580,11 @@ pub(crate) fn lr_unit_rows(
1435 let mut y0 = 0u32;1580 let mut y0 = 0u32;
1436 while y0 < plane_h as u32 {1581 while y0 < plane_h as u32 {
1437 let remaining_h = plane_h as u32 - y0;1582 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+ };
1439 let v_start = (y0 as i64 - voffset as i64).max(0) as u32;1588 let v_start = (y0 as i64 - voffset as i64).max(0) as u32;
1440 let mut v_end = y0 + uh;1589 let mut v_end = y0 + uh;
1441 if v_end < plane_h as u32 {1590 if v_end < plane_h as u32 {
@@ -1471,7 +1620,11 @@ fn lr_unit_row(
1471 let mut rcol = 0usize;1620 let mut rcol = 0usize;
1472 while x0 < plane_w as u32 {1621 while x0 < plane_w as u32 {
1473 let remaining_w = plane_w as u32 - x0;1622 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+ };
1475 let filter = grid.get(plane, rrow, rcol);1628 let filter = grid.get(plane, rrow, rcol);
1476 if filter != UnitFilter::None {1629 if filter != UnitFilter::None {
1477 filter_restoration_unit(1630 filter_restoration_unit(
@@ -1486,7 +1639,8 @@ fn lr_unit_row(
1486 v_start as usize,1639 v_start as usize,
1487 v_end as usize,1640 v_end as usize,
1488 ss_y,1641 ss_y,
1489- filter, fctx,1642+ filter,
1643+ fctx,
1490 );1644 );
1491 }1645 }
1492 x0 += uw;1646 x0 += uw;
@@ -1510,7 +1664,15 @@ mod tests {
1510 /// `SGRPROJ_PRJ_MAX-MIN+1`.1664 /// `SGRPROJ_PRJ_MAX-MIN+1`.
1511 #[test]1665 #[test]
1512 fn subexp_roundtrips_every_value() {1666 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+ ] {
1514 for v in 0..num_syms {1676 for v in 0..num_syms {
1515 let mut enc = SymbolEncoder::new();1677 let mut enc = SymbolEncoder::new();
1516 write_subexp(&mut enc, num_syms, k, v);1678 write_subexp(&mut enc, num_syms, k, v);
@@ -1563,8 +1725,12 @@ mod tests {
1563 write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v);1725 write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v);
1564 let payload = enc.finish();1726 let payload = enc.finish();
1565 let mut dec = SymbolDecoder::new(&payload);1727 let mut dec = SymbolDecoder::new(&payload);
1566- let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v);1728+ let got =
1567- assert_eq!(got, v, "low={low} high={high} k={k} reference={reference_v} v={v}");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+ );
1568 }1734 }
1569 }1735 }
1570 }1736 }
@@ -1595,7 +1761,11 @@ mod tests {
1595 let mut dec = SymbolDecoder::new(&payload);1761 let mut dec = SymbolDecoder::new(&payload);
1596 let mut rref = WienerInfo::default();1762 let mut rref = WienerInfo::default();
1597 for u in &units {1763 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+ );
1599 }1769 }
1600 }1770 }
1601 }1771 }
crates/ec-av1/src/stream.rsmodified+464 -46
@@ -43,6 +43,21 @@ fn no_grain() -> bool {
43 std::env::var_os("EC_AV1_NO_GRAIN").is_some()43 std::env::var_os("EC_AV1_NO_GRAIN").is_some()
44 }44 }
45 45
46+/// lane-av112bit: film grain synthesis has no 12-bit byte-exact witness (the
47+/// lane's witnesses encode with grain off), so a 12-bit frame that would
48+/// synthesise grain is refused by name at output rather than trusted --
49+/// `film_grain.rs` is bit-depth generic since lane-hbd10, but generic is not
50+/// proven until a real 12-bit grain stream compares exact.
51+fn grain_refusal(bit_depth: u32) -> Result<()> {
52+ if bit_depth == 12 {
53+ return Err(Error::unsupported(
54+ "AV1 decode_stream",
55+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)",
56+ ));
57+ }
58+ Ok(())
59+}
60+
46 // lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the61 // lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
47 // current thread, overriding the environment variable. Every ffmpeg/aomdec62 // current thread, overriding the environment variable. Every ffmpeg/aomdec
48 // pixel gate in this repo compares SHOWN frames only (class63 // pixel gate in this repo compares SHOWN frames only (class
@@ -689,6 +704,7 @@ pub fn decode_stream_with_threads(
689 pictures_shown += 1;704 pictures_shown += 1;
690 let grain = header.film_grain;705 let grain = header.film_grain;
691 let seq = SeqFlags::read(&parser);706 let seq = SeqFlags::read(&parser);
707+ grain_refusal(u32::from(seq.bit_depth))?;
692 let tx = tx.clone();708 let tx = tx.clone();
693 jobs.submit(move || {709 jobs.submit(move || {
694 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {710 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
@@ -740,6 +756,13 @@ pub fn decode_stream_with_threads(
740 }756 }
741 picture757 picture
742 };758 };
759+ if header.film_grain.apply_grain {
760+ grain_refusal(
761+ parser
762+ .sequence_header()
763+ .map_or(8, |seq| u32::from(seq.color_config.bit_depth)),
764+ )?;
765+ }
743 let output = if header.film_grain.apply_grain && !no_grain() {766 let output = if header.film_grain.apply_grain && !no_grain() {
744 // lane-hbd10 r1: grain synthesis is bit-depth generic767 // lane-hbd10 r1: grain synthesis is bit-depth generic
745 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).768 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
@@ -1081,6 +1104,9 @@ pub fn decode_stream_with_threads(
1081 // Grain is synthesised for OUTPUT only: a hidden frame is1104 // Grain is synthesised for OUTPUT only: a hidden frame is
1082 // reported to the sink clean, exactly as the inline path1105 // reported to the sink clean, exactly as the inline path
1083 // below reports it (spec 7.18.3.1).1106 // below reports it (spec 7.18.3.1).
1107+ if header.film_grain.apply_grain {
1108+ grain_refusal(u32::from(seq.bit_depth))?;
1109+ }
1084 let output = if shown && header.film_grain.apply_grain && !no_grain() {1110 let output = if shown && header.film_grain.apply_grain && !no_grain() {
1085 std::sync::Arc::new(crate::film_grain::apply_grain(1111 std::sync::Arc::new(crate::film_grain::apply_grain(
1086 &picture,1112 &picture,
@@ -1215,6 +1241,9 @@ pub fn decode_stream_with_threads(
1215 decode::note_fwd_kf();1241 decode::note_fwd_kf();
1216 }1242 }
1217 if header.show_frame {1243 if header.show_frame {
1244+ if header.film_grain.apply_grain {
1245+ grain_refusal(u32::from(seq.bit_depth))?;
1246+ }
1218 let output = if header.film_grain.apply_grain && !no_grain() {1247 let output = if header.film_grain.apply_grain && !no_grain() {
1219 let mc_identity = seq.mc_identity;1248 let mc_identity = seq.mc_identity;
1220 std::sync::Arc::new(crate::film_grain::apply_grain(1249 std::sync::Arc::new(crate::film_grain::apply_grain(
@@ -1647,19 +1676,23 @@ fn decode_frame(
1647 // reason as `set_enable_edge_filter` above. Defaults to 8 when no1676 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
1648 // sequence header has been seen yet, matching every existing fixture.1677 // sequence header has been seen yet, matching every existing fixture.
1649 let bit_depth = seq.bit_depth;1678 let bit_depth = seq.bit_depth;
1650- // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every1679+ // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the
1651- // rounding shift below is written for 8/10-bit only -- `warp.rs`'s1680+ // lane's witnesses prove byte-exact against ffmpeg on real `aomenc
1652- // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses1681+ // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop
1653- // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the1682+ // restoration ON, grain off -- gates
1654- // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the1683+ // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and
1655- // Wiener rounding bits change, and neither CDEF nor film grain has a1684+ // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The
1656- // 12-bit path. Refuse by name rather than decode silently wrong pixels.1685+ // rounding sites that move at 12 bits are parameterised from libaom's
1657- if bit_depth == 12 {1686+ // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange`
1658- return Err(Error::unsupported(1687+ // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener
1659- "AV1 decode_stream",1688+ // pair via `get_conv_params_wiener`; the compound post-rounds absorb
1660- "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)",1689+ // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/
1661- ));1690+ // superres upscale were already bit-depth generic (10-bit-proven).
1662- }1691+ // Everything no 12-bit witness reached stays refused BY NAME at its own
1692+ // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0),
1693+ // film grain (`grain_refusal`, the witnesses run with grain off), and
1694+ // any per-feature gap the witnesses' counters prove unreached -- see the
1695+ // 12-bit refusals in decode.rs and `refusal_inventory.rs`.
1663 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by1696 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by
1664 // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces1697 // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces
1665 // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but1698 // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but
@@ -1699,6 +1732,20 @@ fn decode_frame(
1699 "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",1732 "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",
1700 ));1733 ));
1701 }1734 }
1735+ // lane-av112bit: the frame-level half of the 12-bit gate -- screen
1736+ // content tools. Neither palette nor intrabc has a 12-bit witness (the
1737+ // 12-bit gates are natural content), and both hang off this header bit:
1738+ // `allow_screen_content_tools` is what lets a block code a palette or
1739+ // read a `use_intrabc` symbol. Refusing the FRAME by name keeps every
1740+ // palette/intrabc code path 12-bit-unreachable rather than unwitnessed
1741+ // and trusted. Gate:
1742+ // `a_12bit_screen_content_stream_is_refused_by_name`.
1743+ if bit_depth == 12 && header.allow_screen_content_tools {
1744+ return Err(Error::unsupported(
1745+ "AV1 decode_stream",
1746+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
1747+ ));
1748+ }
1702 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)1749 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
1703 // is a different tile syntax, and this decoder has none of it: libaom1750 // is a different tile syntax, and this decoder has none of it: libaom
1704 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no1751 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
@@ -2117,39 +2164,6 @@ pub(crate) mod tests {
2117 picture2164 picture
2118 }2165 }
2119 2166
2120- /// A stream whose sequence header says `twelve_bit` is refused by name
2121- /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s
2122- /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and
2123- /// film grain). Reachability, not a pixel claim: the header is written at
2124- /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's
2125- /// tile payload is never reached.
2126- #[test]
2127- fn a_twelve_bit_sequence_header_is_refused_by_name() {
2128- let fctx = &crate::decode::FrameCtx::new();
2129- let picture = test_card(64, 64);
2130- let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2131- let mut color = ec_av1_syntax::ColorConfig {
2132- bit_depth: 12,
2133- ..Default::default()
2134- };
2135- color.num_planes = 3;
2136- // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2).
2137- let (mut seq, header) =
2138- crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2139- seq.seq_profile = 2;
2140- let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2141- stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2142-
2143- let err = decode_stream(&stream).unwrap_err().to_string();
2144- assert!(
2145- err.contains(
2146- "a bit depth of 12 (this decoder is gated at 8 and 10 only: \
2147- warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)"
2148- ),
2149- "expected the 12-bit refusal, got: {err}"
2150- );
2151- }
2152-
2153 /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is2167 /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is
2154 /// refused by name, because the decoder reconstructs every chroma extent2168 /// refused by name, because the decoder reconstructs every chroma extent
2155 /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe2169 /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe
@@ -8176,6 +8190,410 @@ pub(crate) mod tests {
8176 /// actually parses to says `bit_depth == 10` before trusting any pixel8190 /// actually parses to says `bit_depth == 10` before trusting any pixel
8177 /// match -- a stream that silently fell back to 8-bit would still8191 /// match -- a stream that silently fell back to 8-bit would still
8178 /// "match" trivially.8192 /// "match" trivially.
8193+ // -------------------------------------------------------------------
8194+ // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted
8195+ // for what these gates witness byte-exact against ffmpeg on real
8196+ // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack,
8197+ // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop
8198+ // restoration (Wiener AND SGR), and translational subpel motion
8199+ // compensation through the bit-depth-parameterised `round_0`/`round_1`
8200+ // (libaom `convolve.h:81..86`). Everything else stays refused by name:
8201+ // warp, film grain, screen content tools (palette/intrabc) at the frame
8202+ // level, compound inter blocks at the mode read, each with its own
8203+ // real-stream refusal gate below.
8204+ // -------------------------------------------------------------------
8205+
8206+ /// The 12-bit witness source, byte-identical to the lane's committed
8207+ /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a
8208+ /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame
8209+ /// vertically with linear edge coverage -- sub-pixel true motion, so an
8210+ /// inter frame over it cannot be coded whole-pel-only.
8211+ fn y4m_12bit_subpel_source(frames: usize) -> Vec<u8> {
8212+ const W: usize = 160;
8213+ const H: usize = 128;
8214+ let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0);
8215+ let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes();
8216+ for t in 0..frames {
8217+ let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64);
8218+ let (bx, by) = (ax + 24.0, ay + 20.0);
8219+ y4m.extend_from_slice(b"FRAME\n");
8220+ for j in 0..H as i64 {
8221+ for i in 0..W as i64 {
8222+ let g = (i * 190) / W as i64 + (j * 150) / H as i64;
8223+ let mut v = (g * 12
8224+ + if (i * 5 + j * 3 + t as i64) % 7 < 3 { 90 } else { 220 }
8225+ + if (60..110).contains(&i) && (70..110).contains(&j) { 640 } else { 0 })
8226+ as f64;
8227+ let c = cov(ax, bx, i) * cov(ay, by, j);
8228+ if c > 0.0 {
8229+ v = v * (1.0 - c) + 3500.0 * c;
8230+ }
8231+ y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes());
8232+ }
8233+ }
8234+ for (base, fx) in [(1900usize, 0usize), (2100, 1)] {
8235+ for j in 0..H / 2 {
8236+ for i in 0..W / 2 {
8237+ let v = if fx == 0 {
8238+ base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H)
8239+ } else {
8240+ base + (((j / 4 + t) % 5) * 140 + (i * 40) / W)
8241+ };
8242+ y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes());
8243+ }
8244+ }
8245+ }
8246+ }
8247+ y4m
8248+ }
8249+
8250+ /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so
8251+ /// every search runs; explicit CDEF/restoration ON). Warp/global-motion
8252+ /// are deliberately NOT spelled here: this aomenc honours the LAST
8253+ /// occurrence of these flags (measured), so a base pin plus an override
8254+ /// would silently take the base value -- each gate spells what it needs
8255+ /// exactly once.
8256+ fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec<u8> {
8257+ let limit = format!("--limit={frames}");
8258+ let mut args: Vec<&str> = vec![
8259+ "--codec=av1",
8260+ "--profile=2",
8261+ "--passes=1",
8262+ "--end-usage=q",
8263+ "--cq-level=20",
8264+ "--cpu-used=0",
8265+ "--threads=1",
8266+ "--row-mt=0",
8267+ "--sb-size=64",
8268+ "--lag-in-frames=0",
8269+ "--auto-alt-ref=0",
8270+ "--kf-max-dist=1000",
8271+ "--input-bit-depth=12",
8272+ "--bit-depth=12",
8273+ "--enable-cdef=1",
8274+ "--enable-restoration=1",
8275+ "--obu",
8276+ "-o",
8277+ "-",
8278+ "-",
8279+ &limit,
8280+ ];
8281+ // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
8282+ // of a flag, so the per-arm override goes BEFORE the base list.
8283+ args.splice(1..1, extra.iter().copied());
8284+ let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
8285+ assert!(
8286+ out.status.success(),
8287+ "aomenc refused the 12-bit fixture: {}",
8288+ String::from_utf8_lossy(&out.stderr)
8289+ );
8290+ out.stdout
8291+ }
8292+
8293+ /// Asserts the stream's sequence header really says 12-bit before any
8294+ /// pixel comparison is trusted.
8295+ fn assert_12bit_sequence_header(stream: &[u8], name: &str) {
8296+ let mut probe = Av1Parser::new();
8297+ let mut pos = 0usize;
8298+ while pos < stream.len() && probe.sequence_header().is_none() {
8299+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
8300+ pos += obu.total_size;
8301+ }
8302+ let seq = probe.sequence_header().expect("stream has a sequence header OBU");
8303+ assert_eq!(
8304+ seq.color_config.bit_depth, 12,
8305+ "{name}: aomenc did not actually write a 12-bit sequence header"
8306+ );
8307+ }
8308+
8309+ fn ffmpeg_decode_sequence_12bit(stream: &[u8], width: usize, height: usize, frames: usize) -> Vec<Pic> {
8310+ let out = run_with_stdin(
8311+ Command::new("ffmpeg").args([
8312+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
8313+ "yuv420p12le", "-",
8314+ ]),
8315+ stream,
8316+ );
8317+ assert!(
8318+ out.status.success(),
8319+ "ffmpeg refused the 12-bit stream: {}",
8320+ String::from_utf8_lossy(&out.stderr)
8321+ );
8322+ let (luma, chroma) = (width * height, width * height / 4);
8323+ let frame_bytes = (luma + 2 * chroma) * 2;
8324+ assert_eq!(
8325+ out.stdout.len(),
8326+ frame_bytes * frames,
8327+ "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}",
8328+ String::from_utf8_lossy(&out.stderr)
8329+ );
8330+ fn le16(bytes: &[u8]) -> Vec<u16> {
8331+ bytes
8332+ .chunks_exact(2)
8333+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
8334+ .collect()
8335+ }
8336+ (0..frames)
8337+ .map(|i| {
8338+ let base = i * frame_bytes;
8339+ Pic {
8340+ width,
8341+ height,
8342+ y: le16(&out.stdout[base..base + luma * 2]),
8343+ u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
8344+ v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
8345+ }
8346+ })
8347+ .collect()
8348+ }
8349+
8350+ /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off.
8351+ /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard-
8352+ /// assert fired: a CDEF index literal read (bits > 0) and at least one
8353+ /// Wiener or SGR restoration unit. Gauntlet for the parameterised
8354+ /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF,
8355+ /// the 12-bit dequant tables, bd-scaled SGR box sums.
8356+ #[test]
8357+ fn a_real_aomenc_12bit_stream_decodes_pixel_exact() {
8358+ const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact";
8359+ let _gate_lock = lock_gate_counters();
8360+ if !have_ffmpeg() {
8361+ eprintln!("SKIP {NAME}: no ffmpeg");
8362+ return;
8363+ }
8364+ if !have_aomenc() {
8365+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8366+ return;
8367+ }
8368+ let y4m = y4m_12bit_subpel_source(1);
8369+ let stream = encode_12bit(
8370+ &y4m,
8371+ 1,
8372+ &["--enable-warped-motion=0", "--enable-global-motion=0"],
8373+ );
8374+ assert_12bit_sequence_header(&stream, NAME);
8375+ let before_cdef = decode::cdef_idx_hits();
8376+ let before_lr =
8377+ crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
8378+ let frames = decode_stream(&stream)
8379+ .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}"));
8380+ assert_eq!(frames.len(), 1);
8381+ assert!(
8382+ decode::cdef_idx_hits() > before_cdef,
8383+ "{NAME}: no CDEF index literal was read -- CDEF is not exercised"
8384+ );
8385+ assert!(
8386+ crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
8387+ "{NAME}: no loop restoration unit was decoded -- LR is not exercised"
8388+ );
8389+ let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1);
8390+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (12-bit key)");
8391+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)");
8392+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)");
8393+ }
8394+
8395+ /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel
8396+ /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass
8397+ /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own
8398+ /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs
8399+ /// parameterisation -- really executed, and asserts
8400+ /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent
8401+ /// second reference, so no compound mode symbol is read -- the lane's
8402+ /// compound witness is the six-frame gate below).
8403+ #[test]
8404+ fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() {
8405+ const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact";
8406+ let _gate_lock = lock_gate_counters();
8407+ if !have_ffmpeg() {
8408+ eprintln!("SKIP {NAME}: no ffmpeg");
8409+ return;
8410+ }
8411+ if !have_aomenc() {
8412+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8413+ return;
8414+ }
8415+ let y4m = y4m_12bit_subpel_source(2);
8416+ let stream = encode_12bit(
8417+ &y4m,
8418+ 2,
8419+ &["--enable-warped-motion=0", "--enable-global-motion=0"],
8420+ );
8421+ assert_12bit_sequence_header(&stream, NAME);
8422+ let before_subpel = crate::mc::mc_subpel_hits();
8423+ let before_compound = decode::compound_mode_hits();
8424+ let frames = decode_stream(&stream)
8425+ .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}"));
8426+ assert_eq!(frames.len(), 2);
8427+ assert!(
8428+ crate::mc::mc_subpel_hits() > before_subpel,
8429+ "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised"
8430+ );
8431+ assert_eq!(
8432+ decode::compound_mode_hits(),
8433+ before_compound,
8434+ "{NAME}: a compound mode symbol was read -- the single-reference premise is gone"
8435+ );
8436+ let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
8437+ for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8438+ assert_eq!(ours.y, reference.y, "frame {i} luma vs ffmpeg (12-bit inter)");
8439+ assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)");
8440+ assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)");
8441+ }
8442+ }
8443+
8444+ /// The 12-bit warp refusal, exercised on a REAL stream: the same source
8445+ /// and recipe with the warp tools ON -- aomenc picks a global warp model
8446+ /// on this content (measured: the decode refuses at the first warped
8447+ /// block) -- is refused by name.
8448+ #[test]
8449+ fn a_12bit_warped_motion_stream_is_refused_by_name() {
8450+ const NAME: &str = "a_12bit_warped_motion_stream_is_refused_by_name";
8451+ let _gate_lock = lock_gate_counters();
8452+ if !have_aomenc() {
8453+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8454+ return;
8455+ }
8456+ let y4m = y4m_12bit_subpel_source(6);
8457+ // Exactly the recipe measured to refuse at warp: warp ON, global
8458+ // motion NOT spelled (spelling it ON makes a GLOBAL_GLOBALMV
8459+ // compound block reach the compound refusal first), six frames --
8460+ // the warp model fires at the third frame.
8461+ let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
8462+ let err = decode_stream(&stream).unwrap_err().to_string();
8463+ assert!(
8464+ err.contains(
8465+ "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)"
8466+ ),
8467+ "{NAME}: expected the 12-bit warp refusal, got: {err}"
8468+ );
8469+ }
8470+
8471+ /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source
8472+ /// and recipe with warp pinned OFF -- with six frames LAST diverges
8473+ /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks
8474+ /// (pre-lift measurement: the decode refused at the compound mode
8475+ /// read). Two arms: the default recipe (dist-weighted average
8476+ /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND
8477+ /// the masked choice harder: 6 diffwtd blends). Both byte-exact
8478+ /// against ffmpeg; each hard-asserts compound mode symbols and
8479+ /// masked-diffwtd blends really ran, so the parameterised combine
8480+ /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at
8481+ /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed.
8482+ #[test]
8483+ fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() {
8484+ const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact";
8485+ let _gate_lock = lock_gate_counters();
8486+ if !have_ffmpeg() {
8487+ eprintln!("SKIP {NAME}: no ffmpeg");
8488+ return;
8489+ }
8490+ if !have_aomenc() {
8491+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8492+ return;
8493+ }
8494+ let y4m = y4m_12bit_subpel_source(6);
8495+ for (arm, extra) in [
8496+ ("dist-wtd", &["--enable-warped-motion=0"][..]),
8497+ ("plain-masked", &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..]),
8498+ ] {
8499+ let stream = encode_12bit(&y4m, 6, &extra);
8500+ assert_12bit_sequence_header(&stream, NAME);
8501+ let before_compound = decode::compound_mode_hits();
8502+ let before_masked = decode::masked_compound_hits();
8503+ let before_diffwtd = decode::diffwtd_hits();
8504+ let before_wedge = decode::wedge_hits();
8505+ let frames = decode_stream(&stream).unwrap_or_else(|e| {
8506+ panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}")
8507+ });
8508+ assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count");
8509+ let (comp, masked, diffwtd, wedge) = (
8510+ decode::compound_mode_hits() - before_compound,
8511+ decode::masked_compound_hits() - before_masked,
8512+ decode::diffwtd_hits() - before_diffwtd,
8513+ decode::wedge_hits() - before_wedge,
8514+ );
8515+ eprintln!(
8516+ "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}"
8517+ );
8518+ assert!(comp > 0, "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised");
8519+ assert!(masked > 0, "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised");
8520+ assert!(diffwtd > 0, "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised");
8521+ let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
8522+ for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8523+ assert_eq!(ours.y, reference.y, "{NAME} [{arm}] frame {i} luma vs ffmpeg");
8524+ assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg");
8525+ assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg");
8526+ }
8527+ }
8528+ }
8529+
8530+ /// The 12-bit film grain refusal: a real `--film-grain-test=1` stream
8531+ /// (grain params present AND applied) is refused by name at output.
8532+ #[test]
8533+ fn a_12bit_film_grain_stream_is_refused_by_name() {
8534+ const NAME: &str = "a_12bit_film_grain_stream_is_refused_by_name";
8535+ let _gate_lock = lock_gate_counters();
8536+ if !have_aomenc() {
8537+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8538+ return;
8539+ }
8540+ let y4m = y4m_12bit_subpel_source(1);
8541+ let stream = encode_12bit(&y4m, 1, &["--film-grain-test=1"]);
8542+ let err = decode_stream(&stream).unwrap_err().to_string();
8543+ assert!(
8544+ err.contains(
8545+ "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)"
8546+ ),
8547+ "{NAME}: expected the 12-bit grain refusal, got: {err}"
8548+ );
8549+ }
8550+
8551+ /// The 12-bit screen-content refusal: a real `--tune-content=screen
8552+ /// --enable-palette=1 --enable-intrabc=1` frame carries
8553+ /// `allow_screen_content_tools = 1` and is refused by name at the frame
8554+ /// gate -- palette and intrabc have no 12-bit witness.
8555+ #[test]
8556+ fn a_12bit_screen_content_stream_is_refused_by_name() {
8557+ const NAME: &str = "a_12bit_screen_content_stream_is_refused_by_name";
8558+ let _gate_lock = lock_gate_counters();
8559+ if !have_ffmpeg() {
8560+ eprintln!("SKIP {NAME}: no ffmpeg");
8561+ return;
8562+ }
8563+ if !have_aomenc() {
8564+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8565+ return;
8566+ }
8567+ let y4m = Command::new("ffmpeg")
8568+ .args([
8569+ "-v", "error", "-f", "lavfi", "-i", "smptebars=s=128x128:r=25",
8570+ "-pix_fmt", "yuv420p12le", "-strict", "-1", "-frames:v", "2",
8571+ "-f", "yuv4mpegpipe", "-",
8572+ ])
8573+ .stdin(Stdio::null())
8574+ .stdout(Stdio::piped())
8575+ .stderr(Stdio::piped())
8576+ .output()
8577+ .expect("ffmpeg failed to run");
8578+ assert!(
8579+ y4m.status.success(),
8580+ "ffmpeg failed to render the 12-bit screen fixture: {}",
8581+ String::from_utf8_lossy(&y4m.stderr)
8582+ );
8583+ let stream = encode_12bit(
8584+ &y4m.stdout,
8585+ 1,
8586+ &["--tune-content=screen", "--enable-palette=1", "--enable-intrabc=1"],
8587+ );
8588+ let err = decode_stream(&stream).unwrap_err().to_string();
8589+ assert!(
8590+ err.contains(
8591+ "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)"
8592+ ),
8593+ "{NAME}: expected the 12-bit screen content refusal, got: {err}"
8594+ );
8595+ }
8596+
8179 #[test]8597 #[test]
8180 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {8598 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
8181 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";8599 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).
lanes/av112bitc.report.mdadded+124 -0
@@ -0,0 +1,124 @@
1+# lane-av112bitc — the 12-bit compound lift
2+
3+Base 0899977a (lane-av112bit's merged tree), worktree `edith_codecs-av112bc`,
4+branch `lane-av1-12bit-comp`. The charter: lift the named 12-bit compound
5+refusal the parent left ("a compound inter block at 12 bits ...") exactly as
6+far as a real `aomenc --bit-depth=12` compound witness proves byte-exactness
7+against ffmpeg, and keep warp, grain and screen content refused by name.
8+
9+## Reaching the path (encode 1 of the 8 allowed)
10+
11+The parent had already measured a compound-reaching recipe: the lane's own
12+sub-pel source, six frames, warp pinned OFF — with six frames LAST diverges
13+from GOLDEN from frame 2 on and aomenc codes compound inter blocks. Pre-fix
14+proof: the unmodified tree's gate
15+`a_12bit_compound_inter_stream_is_refused_by_name` encoded that stream live
16+and refused it at the compound mode read (decode.rs, both
17+`read_inter_compound_mode` callers). Reaching + non-vacuity in one
18+measurement, and the same recipe then became the witness.
19+
20+## What changed
21+
22+- **decode.rs** — both 12-bit compound refusal sites deleted (the block-level
23+ arm and the 8x8-leaf arm). The `bit_depth(fctx) == 12` guard sat AFTER the
24+ compound mode symbol read and BEFORE any prediction, so the lift changes
25+ nothing for 8/10-bit: the parse simply proceeds into `assign_compound_mv`
26+ and the prediction path the parent already parameterised.
27+- **mc.rs** — NO arithmetic change. The parent's parameterisation already
28+ covered every combine: `combine_compound` rounds by
29+ `INTER_POST_ROUND - round_delta` (CONV_BUF gain 16x -> 4x at 12-bit,
30+ `round_0` 5, compound `round_1` 7), `diffwtd_mask` by
31+ `INTER_POST_ROUND + (bd-8) - round_delta` (reconinter.c:307),
32+ `blend_masked_compound` by `INTER_POST_ROUND - round_delta`. Only the
33+ stale doc sentence on `combine_compound` ("decode.rs still refuses those
34+ by name") was corrected.
35+- **decode.rs** header comment over the 12-bit family updated: the family is
36+ now warp-only; compound joined the witnessed set.
37+- **`mc_subpel_hits`** gained the repo-standard
38+ `#[allow(dead_code)] // reader is test-only` (its only reader is the
39+ parent's 12-bit inter gate; non-test builds warned — this tree now checks
40+ `cargo check -p ec-av1 --all-targets` warning-free, which the charter
41+ demands).
42+- **refusal_inventory.rs** — the compound string left both the inventory and
43+ the gate-coverage mapping; inventory 38 -> 37, all still proven, every
44+ proven refusal still names an existing test.
45+- **stream.rs** — the compound refusal gate was REPLACED by the witness
46+ `a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact` (below).
47+
48+## The witnesses
49+
50+Source: the parent's `y4m_12bit_subpel_source(6)` (160x128 C420p12,
51+gradient + texture, a 24x20 box moving 1.25 px/frame horizontally and
52+0.75 px/frame vertically), encoded live in-gate by
53+`~/.cache/aom-oracle/build/aomenc` (libaom src `92d4c37fbdd08944a0e721bbaeb13318f10aebb0`),
54+recipe = the parent's `encode_12bit` base (`--profile=2 --bit-depth=12
55+--passes=1 --end-usage=q --cq-level=20 --cpu-used=0 --threads=1 --row-mt=0
56+--sb-size=64 --lag-in-frames=0 --auto-alt-ref=0 --kf-max-dist=1000
57+--enable-cdef=1 --enable-restoration=1 --obu --limit=6`) plus, spelled exactly
58+once, the arm flags. Two arms:
59+
60+1. **`dist-wtd`** — `--enable-warped-motion=0` (dist-weighted average
61+ combines live): census compound blocks=15, masked=1, diffwtd=1, wedge=0.
62+2. **`plain-masked`** — `--enable-warped-motion=0 --enable-dist-wtd-comp=0`
63+ (pushes compound and the masked choice harder): census compound blocks=18,
64+ masked=6, diffwtd=6, wedge=0.
65+
66+Both arms byte-exact against ffmpeg 8.1.2 (`yuv420p12le` rawvideo) on every
67+plane of every frame, with hard asserts `compound_mode_hits > 0`,
68+`masked_compound_hits > 0`, `diffwtd_hits > 0` (all deterministic: aomenc
69+`--threads=1 --passes=1` on pinned bytes).
70+
71+Committed fixtures (same live recipes, determinism proven by `cmp` of a
72+re-encode against the committed bytes):
73+
74+- `crates/ec-av1/fixtures/av112bit-compound.obu` — 7486 bytes, sha256
75+ `a839cff534b89d5cd52681dd43a7dedc10131d8dd7725bdfa5502d6bc4421740`
76+- `crates/ec-av1/fixtures/av112bit-compound-masked.obu` — 7470 bytes, sha256
77+ `83625de2ed347d457eb67f9781eed3fea598ef035f29bbc311d7025fe178c691`
78+
79+Both fixtures additionally verified standalone: `dump_yuv` (the crate's own
80+decoder) vs `ffmpeg -pix_fmt yuv420p12le -f rawvideo`, whole-stream `cmp`
81+clean for all 6 frames.
82+
83+## Regression
84+
85+- Parent 12-bit key witness `a_real_aomenc_12bit_stream_decodes_pixel_exact`
86+ — byte-exact, CDEF + restoration asserts green.
87+- Parent 12-bit single-ref inter witness
88+ `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact` — byte-exact;
89+ its `compound_mode_hits` UNCHANGED premise still holds on the 2-frame
90+ recipe (doc wording updated: compound no longer "stays refused", the
91+ 2-frame recipe simply never reads a compound symbol).
92+- `a_12bit_warped_motion_stream_is_refused_by_name` — still refuses by name
93+ (warp stays unwitnessed; the compound lift does not reach it first).
94+- 10-bit film gates: `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact`
95+ (pixel-exact, grain_hits=1) and
96+ `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact`
97+ (15 shown frames pixel-exact on every plane) — green.
98+- `refusal_inventory` module green (37 refusals + 1 capability claim, all
99+ proven); `gate_coverage::print_never_on_per_bit_depth` green.
100+- `cargo check -p ec-av1 --all-targets`: **0 warnings**.
101+
102+## Open halves (recorded, not silently dropped)
103+
104+1. **Wedge-masked compound at 12 bits** — unwitnessed. Two recipes on the
105+ sub-pel corpus never made aomenc pick COMPOUND_WEDGE (`wedge_hits == 0`
106+ in both arms); the 8-bit wedge gate only reaches wedge on hard-edge
107+ content with attempt loops, which this lane's charter forbids
108+ (deterministic single-recipe encodes). The lift is still honest per the
109+ parent's own composition rule: the wedge arm and the diffwtd arm run the
110+ SAME `blend_masked_compound` (witnessed byte-exact at 12 bits via six
111+ diffwtd blends), differing only in the u8 mask bytes, and the wedge
112+ codebook is bit-depth independent and 8-bit-witnessed (lane-wedge r3).
113+ Disposition: `accepted` — a future wedge witness needs only an
114+ aomenc recipe that picks wedge at 12 bits.
115+2. Warp, film grain synthesis, screen content (palette/intrabc) at 12 bits
116+ — unchanged, refused by name exactly as the parent left them.
117+
118+## Process note
119+
120+One fixture encode initially landed in the MAIN checkout's
121+`crates/ec-av1/fixtures/` (a shell call whose cwd did not apply); both files
122+were moved into this worktree unmodified (sha256s above taken after the
123+move) and `git status --short` on the main checkout shows nothing from this
124+lane. The parent worktree was never touched.