diff --git a/crates/ec-av1/fixtures/av112bit-inter.obu b/crates/ec-av1/fixtures/av112bit-inter.obu new file mode 100644 index 0000000000000000000000000000000000000000..2bae0ac1fda0db3a9a88e94d388b92056b2542cd GIT binary patch literal 4533 zcmV;m5lZe701690000BD|MTDHj36?s91sA5AOHv<2n-iJ0RHf8a@pS>9t(gL>R|hm z%4eKythDpG=p>TWaz!Z;m(TK+4E7EB`tW!DSJq2x^UCySBhupLL=^a!r2-}r?~ z4r=`kxch2XenW-B5iMkBy)rQbTW#RWyS9!-~L4SlcUFThpFAlzgXYW~8lWYvF zr6RV}xf?Nf!)YK;<6pNF5+QIFqr2h&&B$WCLvu@WX<*jLjTUz#+u{HoOv4W zx}^}p4!gUHn?h``&EXh98I^vQN!#UStLlv_1kq)B5Db zl)H;1BF{}ew`~2a(S!XN#bQ50q2D7%1@|wYAkF{dXsx9y24s1$&zF3S*|NF4%t9io z!g7W~a&T%OdppmMi!m3RY6QdXkPC5r(T$e@!q9@`x~wF`ia$B59x90c-$B`I4?VOB zv^#E{+~9iC$Q|uEcglqBW6$F;54N#Pe`{pq5vbh7U6uvZUsB5k>s2qnB;~Yj2{Q;W zeM>_1wopFO6F@1_71OdWe9!qXn99nJUjIeJUcN_+BBnGY<>+ANFyK7%9t|WxDio2% zyDHDkA1>lR^s!t1-~a`=4A13RMll^!>^)dw@)B?{Ut@6OPGn9e?Qi~M;!MChoF5{h zU8g78>6Ii9hi~U*K4zUTob^*3d|5dMnR>Qm6jTsv_i>n`{o|uSl=!Z}XtKhca2g&N zm~-JBk3}pjfj}KYwD26||G*f)FSJ`^59Kya84ahRqpZnAAf^@cg;@q798wPEphN~K z`@<12%-)^Ij@vpl?M2^^s~x9CftHcGUg{Jh#>~|R95o*C!W&qtBwgvSJzun7TnZfO zuAG2Q$9qwmn}lX;SZ267IdB{4bhI+IhIM}TQZ|GXy@&(f0xz5(wH237@)~T%nfp;I ztUV`jz4qLJ)0J9iE*A6G96S0(hYJNo_)@snwtf0KefPf)c7UgawG(?-={*X$V<#MB z1|JMri}QY`t?Q1|OP3!t#{KTyeK>cDxa0HtDeCUdMdbT|Fd?;Y6p;U~eIn~>3>t2F zz}bd6EH-O0tVR`H=SO!E#Kxx&0~3Qes1o>=C`O!Hk)-g#w$%DevCsNg%$6SU7}9x5 zhaVH>EijJA_Pr{2TAW@qXCxE~Ew85UtA}7hto$cAp4UDm>4QL5gsG>$*omi44CrpxJ!3}&VVGyjeL{f) z?)Wwh?^|lq7)a(RFfynI-$kwTEYd-sM3e)@2Eao6`JeFMo6^z*cQR>^Bgy&%DXE3jce+-6V?S1*p@7 zxiV*80FafJxZZ|6>F-In{h-fDeD|xpwDH zPKE~w@zB;zC82E_O13ww+@2@wc8{%}8*nT|R*=tF;I-Si+jQ=zx61>AT9yef;petH zL?ev+W)dyn9HLp~Un#pUB4O+7aNB_iQoAmJDHp9q<~}I6`o7}{am3EA+-vra2u>!e zYe)BBMJ!FG+Vw}U^3ixWdy#IB9(dfHj$a(@()9*(u2 z@VHw(6+zNjNbYHSK+nfwVdLUs4W|8v6N7$K*RzSO=1S%^KsYoGIs zm$P-f-j(*PEj8;u?yG9BwvnNM!r36sdU18L({~>jbj&Y|pymHq&Ot!if!}RZso1EU z>WzQh!4By|;`yhLz*yhoX&}n2TUXA8FSz;S-<^$3*VRV_Z3kQdwt`(Xn<7(}#I1;o zo>6^`n2MP7<>D1Ys)V6z_D?AHoa(J@5|oIijI7`#sO9$?vypn(y{i1y>ko8 zoF@UDRtff-q3)q;v0$3;d4c*!F_RvI>qhC5)vWY1Dok?vgln>ElZLpEjRVL0!3GJN zh}drsL!^5bgCQhlf9N8s*7Y>sesN^M3RC4sScSao)i^se?fff=Q0LNB`Mm5anON= z?5n`*{zK+$CJCS^v!~}+F!$G~)>2cI?g<4tv^ZPbZ1?~=)M4YEtdLecQjA6T9jtAi zZqLbc`2K%)b3&kfz?q;0!X)<4xy%#i)h7cA7$Uje1*%h#H#p}U*Xf34ibTqEre|S} zH9}y$NwBKI5w*9u!s@*Oo1AXa9y`xB*)|H<$ni=ahqBND6U|dVdcQVhoUt-~_1MPr zV&cD?Q@65Uq`vGr`*jRY3!_I!+KHyE=9*A}4SV93Nfwj8FJo3=(b7gu@pgbTW)k1q znd$i0*_7>C3bF@8#o$AxsbzDF;Lef8E=wyZB-lH@YzDDOp_WlyR{L+tqF!^t1gF#b zj3%wY=0J17v)7GZ#jcIU(&RDa%j1qz-w0|C97q9v$4AP3b|^b|xdB3S^a14!ja?z; z)pZF**iT-_79#xw$6P3&ba3=*8X@AH=!c@2+=5hT!zxFP49qs+X{rI?e)acj2YGOF zXVow!r-U#{?yiT|RI@g|r_bdA3=RRedMtYnboz+vaYL#2Ow6Bd(8;*<4_oQCTVnF_ z?|4MDDTTopRtIhs*zj-v9b%cnADmZqsUH#%&RUzH=*rC+wzcF`Hu?Qa$SV7}9)SWJ zDC-UhU`DUv8#@x3<9O!@xrsfCysggb*)g)#(|l54n|qi~Ss`a}=%Q@BY+mpS5ZOqO zwS+V?@5Y9CG@K(#Nm59&sr*DIwo>}0)pRx_lboOA&<}jm@9ROW^MuE6)xwd6qz&z{ z8!i(TFSWZrd$Dt7eTZr4$=ezZkjpoL-B0rkUXO?}XkhS;5Dq-!u@Gu7B@VYX-xsjx zFp4l^yWm0|^T}J%=%4e<4AiukDL$B0k2Om6VVmCKXXmX6q?acDV$6t@92{_sy2+3j zy%<&&*Wn(^9^S@t_Cc>ZlZxShPoX&`0U-IB>^nw6IARtK_t@+pzw16O@PD;j7_eBL z1P33FSOu2st6qK?M}R3d$W6{bYSO0y$MyppDYG9QYK1&aym&<*jGX~CGMS=Wap_N0 z!K?)9_63sN&?(K;Z*U-_@;$?EI4(LAf_SGiq#`rsu*_yb7+$ONi7!Ao?Byi9D7o+C%zw>&j;CBO zjn)sTTZfOR-1ds1DECfT5t9n`71cR$Z+c4SI#&G8Z>|xWIOJhIcveXF*8BiN{yea~ zjXm+f)k2R@wahBs_A{n3If$^XID#SVLmcRTFiDX*`Li{%LqrW$zhg6gUa3*;|H$#) z%@o4&Z}1-}yQ1LQfsu6-bpIX?pmblfpsV|f2V>R>6|u%T;c*lSobXjqqo!Wmrx^afIxX5$dc?#MUZ(sIGU zH)}0Pw?*VRh@}bQ;Jsvm6}LcHDfE=Y59(wRyOQ@tZd7r5WAy0yCYnN<`OW2E^K4`^ zov%Y;>arnWafO=|l5G`SHJ&k(T`Hyhvn-M#-0Z0i5v4o2E7!klS7T*{`E=YHn$jWP zw2G})pH2}6wOK_~k@u&l7HaMgp$h+DzLYrcvXrGhq2w5Mne$^s??xVvdLrVnXR4?C z@oE(}x?%FEIakibLQ)7|RQe9o3xyqnE?c=ARWGgkR$if|G=&%O_d!9lwK{WCg^Z!~ZC0~uoNBX61#=7M znOfl!1qbGLsnfD6w#=pTA;}S~8|I`U&h7Y_P@;f{31XD?t17)*=wu0&16da%?J3c2 zNd(RMPNrrN=va}WD0cAIg8nldp1^c%u`Yvk9aTqN^Mtc`QLXv#A4JYaa|?xXlZbMZ zV9DEIsL*6kUA1MA*ck?qg)``>+MyQ%W>h&6^}qzn=JDBzx65=|gT|Q5W4E?{$tlO@ zA3@{OKL_t^TWz#*2o^RLpoLNKhmU5z2?MyTQed05=Z10fa7&c#a>O3M>GLgfBy&L= z0Cjk&(u<)8iCev`=DO~qvt*uVK;Qd-M+qx3~T@a=ld*cObDHv7<`0?rHviT`)M)IB#wRWT=7q4@1^J z0mR~ziF(uRby%#jLC(z~_CHjQBtk`l3C(g9{5|y$+nc^z`S=*C-^UL!H_ImI=$)nZ zlL5m;aOT5FzxQBL>%cJ#KB=c3%A@KyvwFY1G!Z}^*||;;;|(T1hadfec~(Xm@Woix zjnG$essnyF0-82`V@9N`xX+{*JBcQTSd%R#Bkn9=CBnikt)k96TJES`aacnNp2x@i zqfSS&gaP~kc21ISN82kIS)vx4HA{33DA^Gv9pj>0iAOTcoNd}Tdh@Y%js=oiYh$9% zd_+LI(XA#1lmu9T*x=G#`oU6Tx|39Q2wA;+N@X)@74(HFIt8;r7Gs61eJV-;EVc34 z&7)p!InH_#4YSg9TuhCzfWhmuKKbn$^_^}&&JGb|RW+3X@RuD1* zXlcArFh;7@xn~MNV8aG#Eu#hok6XY@SXErK1zR%r9iN)_~#G}Xep;AnlWsXB2U z*4*nbTx>7LxAX~RK9u|*&j=Cnc7kNsKl`u0BekEy;Q)ICBIE}qW<0wRPm+x?N71Jg z7$AM^Q)$x898y>%i{}uY*ju3g#=DuR%j}2xEJ9$NU2362?+*C{{w{)H_!siNRWQJRsn}^4!2-KjjFOZtyK52yo*8a z&E951k6VIfG`caVv0L<#6sb|p{x@26akXkVOz!T0wvV{~Je&UC*3^)Qku>?*d~M=z ztBHV5>QD3*j6sIqI{NRYGtK0Iu^%t;8$ZgZrgzS}W>MGFv_{43oNy+&3k(cIj(M$T zYx-v2$}`VOQmIqw`9s}hOZFOti;jNn=QJL#PcFK^-egRs#7ibRYsKmm zM80^bX@eQGzl~r%D$N}G=-{gdWi>Dc-&zZ${ow=Xh>3z#%JWV-H}z&*FJ-}Z z=2x>BJ05w*DdXp#2_j{ab)~dV6^UB?K!w*vdv7xJHEX9P&+6IqF4Q+CM0jc`$aROl0@BJ8F literal 0 HcmV?d00001 diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index ea4a8fc4..b57da84f 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -28,6 +28,14 @@ use ec_av1_syntax::{ }; use ec_core::{Error, Result}; +// lane-av112bit: the 12-bit warp/compound refusals below are inline literals +// (refusal_inventory.rs extracts them from the decode source); each names the +// witness gap that keeps the path refused -- warp's reduce bits inherit the +// 12-bit `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86), and +// the inter witness is a single-reference stream, so compound of every kind +// is unwitnessed. All sites are PARSE-time: a refused stream never builds a +// warp predictor or blends a compound pair. + /// Per-frame decode state, one instance per decoded stream (lane-thread1). /// /// Every field here used to be a `thread_local!` static, which made a decode a @@ -28993,6 +29001,13 @@ fn decode_inter_block( } else { read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx) }; + // lane-av112bit: refused by name -- see `COMPOUND_12BIT_REFUSAL`. + if bit_depth(fctx) == 12 { + return Err(Error::unsupported( + "AV1 tile decode", + "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)", + )); + } let (mv0, mv1) = assign_compound_mv( dec, cdfs, @@ -29083,6 +29098,13 @@ fn decode_inter_block( let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1)); if warp0.is_some() || warp1.is_some() { hit!(COMPOUND_WARP_HITS); + // lane-av112bit: refused by name -- see `WARP_12BIT_REFUSAL`. + if bit_depth(fctx) == 12 { + return Err(Error::unsupported( + "AV1 tile decode", + "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)", + )); + } } // spec `get_ref_filter_type`: matches when EITHER of the // neighbour's two references equals this block's own ref0 -- @@ -29545,8 +29567,7 @@ fn decode_inter_block( write_h, h_filter, v_filter, - &mut inter0_y, - ); + &mut inter0_y, fctx,); // lane-cwarp r1: this reference's own GLOBAL warp replaces the // translational tap (libaom `av1_warp_plane` with // `conv_params->is_compound`); the blend below is unchanged. @@ -29572,8 +29593,7 @@ fn decode_inter_block( write_h, h_filter, v_filter, - &mut inter1_y, - ); + &mut inter1_y, fctx,); // lane-cwarp r1: this reference's own GLOBAL warp replaces the // translational tap (libaom `av1_warp_plane` with // `conv_params->is_compound`); the blend below is unchanged. @@ -29621,8 +29641,7 @@ fn decode_inter_block( write_chroma_h, h_filter, v_filter, - &mut inter0_u, - ); + &mut inter0_u, fctx,); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. @@ -29650,8 +29669,7 @@ fn decode_inter_block( write_chroma_h, h_filter, v_filter, - &mut inter1_u, - ); + &mut inter1_u, fctx,); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. @@ -29695,8 +29713,7 @@ fn decode_inter_block( write_chroma_h, h_filter, v_filter, - &mut inter0_v, - ); + &mut inter0_v, fctx,); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. @@ -29724,8 +29741,7 @@ fn decode_inter_block( write_chroma_h, h_filter, v_filter, - &mut inter1_v, - ); + &mut inter1_v, fctx,); // `av1_init_warp_params` bails when the PLANE's block is // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma // block of an 8x8 luma block stays translational. @@ -30665,6 +30681,15 @@ fn decode_inter_block( hit!(AFFINE_GM_HITS); } } + // lane-av112bit: a local `WARPED_CAUSAL` projection (set above) or + // a global warp model both land here with `warp_params` set -- + // refused by name at 12 bits (see `WARP_12BIT_REFUSAL`). + if bit_depth(fctx) == 12 && warp_params.is_some() { + return Err(Error::unsupported( + "AV1 tile decode", + "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)", + )); + } if crate::envflags::env_flag!("EC_AV1_TELL") { eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}", @@ -34541,6 +34566,13 @@ fn decode_inter_block8( comp_stack.ref_mv_ctx, ) }; + // lane-av112bit: refused by name -- see `COMPOUND_12BIT_REFUSAL`. + if bit_depth(fctx) == 12 { + return Err(Error::unsupported( + "AV1 tile decode", + "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)", + )); + } if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}", @@ -34835,8 +34867,7 @@ fn decode_inter_block8( SIDE, h_filter, v_filter, - &mut inter0_y, - ); + &mut inter0_y, fctx,); if let Some(wp) = &warp0_c { crate::warp::warp_affine_compound( wp, &py0.data, py0.true_width as i32, py0.true_height as i32, @@ -34857,8 +34888,7 @@ fn decode_inter_block8( SIDE, h_filter, v_filter, - &mut inter1_y, - ); + &mut inter1_y, fctx,); if let Some(wp) = &warp1_c { crate::warp::warp_affine_compound( wp, &py1.data, py1.true_width as i32, py1.true_height as i32, @@ -34897,8 +34927,7 @@ fn decode_inter_block8( CHROMA_SIDE, h_filter, v_filter, - &mut inter0_u, - ); + &mut inter0_u, fctx,); let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pu1.data, @@ -34912,8 +34941,7 @@ fn decode_inter_block8( CHROMA_SIDE, h_filter, v_filter, - &mut inter1_u, - ); + &mut inter1_u, fctx,); let mut pred_u = refill(std::mem::take(&mut out[1]), CHROMA_SIDE * CHROMA_SIDE); if let Some(mask_y) = mask_y { mc::blend_masked_compound( @@ -34943,8 +34971,7 @@ fn decode_inter_block8( CHROMA_SIDE, h_filter, v_filter, - &mut inter0_v, - ); + &mut inter0_v, fctx,); let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pv1.data, @@ -34958,8 +34985,7 @@ fn decode_inter_block8( CHROMA_SIDE, h_filter, v_filter, - &mut inter1_v, - ); + &mut inter1_v, fctx,); let mut pred_v = refill(std::mem::take(&mut out[2]), CHROMA_SIDE * CHROMA_SIDE); if let Some(mask_y) = mask_y { mc::blend_masked_compound( @@ -35513,6 +35539,15 @@ fn decode_inter_block8( hit!(AFFINE_GM_HITS); } } + // lane-av112bit: same 12-bit refusal as the 16x16+ leaf -- a local + // `WARPED_CAUSAL` projection or a global model both leave + // `warp_params` set here (see `WARP_12BIT_REFUSAL`). + if bit_depth(fctx) == 12 && warp_params.is_some() { + return Err(Error::unsupported( + "AV1 tile decode", + "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)", + )); + } if crate::envflags::env_flag!("EC_TRACE_MODE") { eprintln!( "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}", diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0f859a22..87c9dbec 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -9745,7 +9745,7 @@ fn mc_trial_compound_typed( side, fctx.interp_filter.get(), fctx.interp_filter.get(), - dst, + dst, fctx, ); } let mut blended16 = [0u16; BLOCK * BLOCK]; @@ -9838,7 +9838,7 @@ fn predict_compound_u8( side, fctx.interp_filter.get(), fctx.interp_filter.get(), - dst, + dst, fctx, ); } let mut blended = vec![0u16; side * side]; diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index 52b55a76..2188395f 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -23,24 +23,46 @@ fn round2(value: i32, shift: u32) -> i32 { /// through `packs_epi32`, which saturates -- so the scalar arms must too, or /// the two would disagree on an out-of-range sum. Motion compensation never /// produces one (`horizontal_intermediate_fits_i16` proves the bound from the -/// tap sums at 8/10-bit; 12-bit is refused in stream.rs), and restoration's -/// wiener pass clamps its own output into i16 immediately after. +/// tap sums at every supported bit depth), and restoration's wiener pass +/// clamps its own output into i16 immediately after. fn sat16(value: i32) -> i16 { value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16 } -/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the -/// horizontal pass's sum is brought down by before it is stored as the -/// intermediate. +/// `InterRound0` (spec 7.11.3.2), non-compound: the shift the horizontal +/// pass's sum is brought down by before it is stored as the intermediate. +/// This is the 8/10-bit base; at 12-bit [`round_delta`] raises it (libaom +/// `convolve.h`'s `get_conv_params_no_round`). const INTER_ROUND_0: u32 = 3; -/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical -/// pass's sum is brought down by to land back on an 8-bit sample. Composed -/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass +/// `InterRound1` (spec 7.11.3.2), non-compound: the shift the vertical +/// pass's sum is brought down by to land back on a sample. Composed +/// with [`INTER_ROUND_0`] the two shifts are the filter's own gain (each pass /// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`) /// -- so an identity or DC input comes back exactly, by construction of the -/// table rather than by a fitted constant. +/// table rather than by a fitted constant. 8/10-bit base; see [`round_delta`]. const INTER_ROUND_1: u32 = 11; +/// The bit-depth headroom libaom adds when the `CONV_BUF` intermediate would +/// no longer fit 16 bits (`convolve.h:81..86`'s +/// `intbufrange = bd + FILTER_BITS - round_0 + 2 > 16`): zero at 8/10-bit; +/// `bd - 10` at 12-bit. There the horizontal `round_0` rises by the delta +/// and the non-compound vertical `round_1` falls by it again, so the +/// filter's own gain `2*FILTER_BITS - round_0 - round_1` is untouched -- +/// only the intermediate quantisation moves. Warp's +/// `reduce_bits_horiz == conv_params->round_0` (`warped_motion.c:295`) and +/// the Wiener pair (`get_conv_params_wiener`) inherit the same delta. +pub(crate) fn round_delta(bd: u32) -> u32 { + bd.saturating_sub(10) +} + +/// A frame's MC rounding pair: horizontal `round_0` and non-compound +/// vertical `round_1` (the compound vertical round is `INTER_ROUND_1_COMPOUND` +/// at every bit depth). +pub(crate) fn round_pair(bd: u32) -> (u32, u32) { + let delta = round_delta(bd); + (INTER_ROUND_0 + delta, INTER_ROUND_1 - delta) +} + /// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel /// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer /// sample (fraction 0 is the identity tap `[.., 128, ..]`). @@ -296,9 +318,9 @@ pub(crate) fn simd_level() -> SimdLevel { /// the same `Round2(sum, InterRound0)`. #[allow(unsafe_code)] #[inline] -pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16]) { +pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16], round0: u32) { let n = out.len(); - hpass_rows(src, 0, 1, n, t16, out); + hpass_rows(src, 0, 1, n, t16, out, round0); } /// lane-mc2: `rows` rows of [`hpass_contig`], `src_stride` apart in `src` and @@ -313,6 +335,7 @@ pub(crate) fn hpass_rows( block_w: usize, t16: &[i16; 8], out: &mut [i16], + round0: u32, ) { #[cfg(target_arch = "x86_64")] { @@ -320,13 +343,13 @@ pub(crate) fn hpass_rows( SimdLevel::Avx2 => { // SAFETY: the AVX2 arm is reached only when the CPU reports // avx2; each row reads at most `block_w + 7` samples. - unsafe { simd::hpass_avx2(src, src_stride, rows, block_w, t16, out) }; + unsafe { simd::hpass_avx2(src, src_stride, rows, block_w, t16, out, round0) }; return; } SimdLevel::Sse41 => { // SAFETY: as above; the kernel needs only SSE2, which every // x86_64 CPU has. - unsafe { simd::hpass_sse2(src, src_stride, rows, block_w, t16, out) }; + unsafe { simd::hpass_sse2(src, src_stride, rows, block_w, t16, out, round0) }; return; } SimdLevel::Scalar => {} @@ -337,12 +360,13 @@ pub(crate) fn hpass_rows( &src[r * src_stride..], t16, &mut out[r * block_w..(r + 1) * block_w], + round0, ); } } /// The scalar reference for [`hpass_contig`] (lane-perf2's loop). -fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) { +fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16], round0: u32) { // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit // depth), so the products are exactly the i32 ones but the widening // multiply is one instruction per pair. @@ -351,7 +375,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) { for t in 0..8 { sum += i32::from(t16[t]) * i32::from(w[t] as i16); } - *o = sat16(round2(sum, INTER_ROUND_0)); + *o = sat16(round2(sum, round0)); } } @@ -363,7 +387,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) { #[cfg(target_arch = "x86_64")] #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract mod simd { - use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1}; + use super::{round2, sat16}; use std::arch::x86_64::*; /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape @@ -372,15 +396,26 @@ mod simd { #[inline] fn taps16(taps: &[i32; 8]) -> [i16; 8] { [ - taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16, - taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16, + taps[0] as i16, + taps[1] as i16, + taps[2] as i16, + taps[3] as i16, + taps[4] as i16, + taps[5] as i16, + taps[6] as i16, + taps[7] as i16, ] } #[inline] fn tap_pairs(t: &[i16; 8]) -> [i32; 4] { let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16); - [pack(t[0], t[1]), pack(t[2], t[3]), pack(t[4], t[5]), pack(t[6], t[7])] + [ + pack(t[0], t[1]), + pack(t[2], t[3]), + pack(t[4], t[5]), + pack(t[6], t[7]), + ] } /// Horizontal pass, AVX2: 16 outputs per iteration. Each 256-bit `madd` @@ -399,6 +434,7 @@ mod simd { block_w: usize, t16: &[i16; 8], out: &mut [i16], + round0: u32, ) { debug_assert!(out.len() >= rows * block_w); debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7); @@ -409,7 +445,7 @@ mod simd { _mm256_set1_epi32(tp[2]), _mm256_set1_epi32(tp[3]), ]; - let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_0 - 1)); + let rnd = _mm256_set1_epi32(1 << (round0 - 1)); for r in 0..rows { let sp = src.as_ptr().add(r * src_stride); let op = out.as_mut_ptr().add(r * block_w); @@ -423,8 +459,8 @@ mod simd { let so = _mm256_loadu_si256(sp.add(c + 2 * k + 1).cast()); o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k])); } - e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), INTER_ROUND_0 as i32); - o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32); + e = _mm256_sra_epi32(_mm256_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32)); + o = _mm256_sra_epi32(_mm256_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32)); let lo = _mm256_unpacklo_epi32(e, o); let hi = _mm256_unpackhi_epi32(e, o); // `lo`/`hi` already hold the 16 outputs in order, four per @@ -437,7 +473,15 @@ mod simd { if c < block_w { let s = r * src_stride + c; let o = r * block_w + c; - hpass_sse2(&src[s..], 0, 1, block_w - c, t16, &mut out[o..o + block_w - c]); + hpass_sse2( + &src[s..], + 0, + 1, + block_w - c, + t16, + &mut out[o..o + block_w - c], + round0, + ); } } } @@ -461,33 +505,38 @@ mod simd { taps: &[i32; 8], acc: &mut [i32], ) { - debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w); + debug_assert!( + intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w + ); let tp = tap_pairs(&taps16(taps)); for row in 0..rows { - let ip = intermediate.as_ptr().add(row * src_stride); - let ap = acc.as_mut_ptr().add(row * block_w); - let mut c = 0usize; - while c + 16 <= block_w { - // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit - // lane), `hi` the other two runs; the two `permute2x128`s put the - // 16 sums back in column order. - let mut lo = _mm256_setzero_si256(); - let mut hi = _mm256_setzero_si256(); - for k in 0..4 { - if tp[k] == 0 { - continue; + let ip = intermediate.as_ptr().add(row * src_stride); + let ap = acc.as_mut_ptr().add(row * block_w); + let mut c = 0usize; + while c + 16 <= block_w { + // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit + // lane), `hi` the other two runs; the two `permute2x128`s put the + // 16 sums back in column order. + let mut lo = _mm256_setzero_si256(); + let mut hi = _mm256_setzero_si256(); + for k in 0..4 { + if tp[k] == 0 { + continue; + } + let tv = _mm256_set1_epi32(tp[k]); + let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast()); + let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast()); + lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv)); + hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv)); } - let tv = _mm256_set1_epi32(tp[k]); - let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast()); - let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast()); - lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv)); - hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv)); + _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20)); + _mm256_storeu_si256( + ap.add(c + 8).cast(), + _mm256_permute2x128_si256(lo, hi, 0x31), + ); + c += 16; } - _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20)); - _mm256_storeu_si256(ap.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31)); - c += 16; - } - vpass_tail_sse(ip, block_w, src_stride, &tp, taps, ap, c); + vpass_tail_sse(ip, block_w, src_stride, &tp, taps, ap, c); } } @@ -570,37 +619,40 @@ mod simd { taps: &[i32; 8], max: i32, dst: &mut [u16], + round1: u32, ) { - debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w); + debug_assert!( + intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w + ); let tp = tap_pairs(&taps16(taps)); - let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_1 - 1)); + let rnd = _mm256_set1_epi32(1 << (round1 - 1)); let mx = _mm256_set1_epi16(max as i16); for row in 0..rows { - let ip = intermediate.as_ptr().add(row * src_stride); - let dp = dst.as_mut_ptr().add(row * block_w); - let mut c = 0usize; - while c + 16 <= block_w { - let mut lo = rnd; - let mut hi = rnd; - for k in 0..4 { - if tp[k] == 0 { - continue; + let ip = intermediate.as_ptr().add(row * src_stride); + let dp = dst.as_mut_ptr().add(row * block_w); + let mut c = 0usize; + while c + 16 <= block_w { + let mut lo = rnd; + let mut hi = rnd; + for k in 0..4 { + if tp[k] == 0 { + continue; + } + let tv = _mm256_set1_epi32(tp[k]); + let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast()); + let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast()); + lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv)); + hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv)); } - let tv = _mm256_set1_epi32(tp[k]); - let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast()); - let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast()); - lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv)); - hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv)); + lo = _mm256_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32)); + hi = _mm256_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32)); + // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four + // per lane in order, so this is c..c+16 in order. + let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx); + _mm256_storeu_si256(dp.add(c).cast(), v); + c += 16; } - lo = _mm256_srai_epi32(lo, INTER_ROUND_1 as i32); - hi = _mm256_srai_epi32(hi, INTER_ROUND_1 as i32); - // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four - // per lane in order, so this is c..c+16 in order. - let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx); - _mm256_storeu_si256(dp.add(c).cast(), v); - c += 16; - } - vpass_u16_tail_sse(ip, block_w, src_stride, &tp, taps, max, dp, c); + vpass_u16_tail_sse(ip, block_w, src_stride, &tp, taps, max, dp, c, round1); } } @@ -619,8 +671,9 @@ mod simd { max: i32, dp: *mut u16, mut c: usize, + round1: u32, ) { - let rnd = _mm_set1_epi32(1 << (INTER_ROUND_1 - 1)); + let rnd = _mm_set1_epi32(1 << (round1 - 1)); let mx = _mm_set1_epi16(max as i16); while c + 4 <= block_w { let wide = c + 8 <= block_w; @@ -631,7 +684,10 @@ mod simd { continue; } let tv = _mm_set1_epi32(tp[k]); - let (pa, pb) = (ip.add(2 * k * src_stride + c), ip.add((2 * k + 1) * src_stride + c)); + let (pa, pb) = ( + ip.add(2 * k * src_stride + c), + ip.add((2 * k + 1) * src_stride + c), + ); let (a, b) = if wide { (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast())) } else { @@ -643,7 +699,10 @@ mod simd { } } let v = _mm_min_epu16( - _mm_packus_epi32(_mm_srai_epi32(lo, INTER_ROUND_1 as i32), _mm_srai_epi32(hi, INTER_ROUND_1 as i32)), + _mm_packus_epi32( + _mm_sra_epi32(lo, _mm_cvtsi32_si128(round1 as i32)), + _mm_sra_epi32(hi, _mm_cvtsi32_si128(round1 as i32)), + ), mx, ); if wide { @@ -659,7 +718,7 @@ mod simd { for (t, &tap) in taps.iter().enumerate() { sum += tap * i32::from(*ip.add(t * src_stride + c)); } - *dp.add(c) = round2(sum, INTER_ROUND_1).clamp(0, max) as u16; + *dp.add(c) = round2(sum, round1).clamp(0, max) as u16; c += 1; } } @@ -677,13 +736,23 @@ mod simd { taps: &[i32; 8], max: i32, dst: &mut [u16], + round1: u32, ) { - debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w); + debug_assert!( + intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w + ); let tp = tap_pairs(&taps16(taps)); for row in 0..rows { vpass_u16_tail_sse( - intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps, max, - dst.as_mut_ptr().add(row * block_w), 0, + intermediate.as_ptr().add(row * src_stride), + block_w, + src_stride, + &tp, + taps, + max, + dst.as_mut_ptr().add(row * block_w), + 0, + round1, ); } } @@ -700,12 +769,19 @@ mod simd { taps: &[i32; 8], acc: &mut [i32], ) { - debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w); + debug_assert!( + intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w + ); let tp = tap_pairs(&taps16(taps)); for row in 0..rows { vpass_tail_sse( - intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps, - acc.as_mut_ptr().add(row * block_w), 0, + intermediate.as_ptr().add(row * src_stride), + block_w, + src_stride, + &tp, + taps, + acc.as_mut_ptr().add(row * block_w), + 0, ); } } @@ -723,6 +799,7 @@ mod simd { block_w: usize, t16: &[i16; 8], out: &mut [i16], + round0: u32, ) { debug_assert!(out.len() >= rows * block_w); debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7); @@ -733,7 +810,7 @@ mod simd { _mm_set1_epi32(tp[2]), _mm_set1_epi32(tp[3]), ]; - let rnd = _mm_set1_epi32(1 << (INTER_ROUND_0 - 1)); + let rnd = _mm_set1_epi32(1 << (round0 - 1)); for r in 0..rows { let sp = src.as_ptr().add(r * src_stride); let op = out.as_mut_ptr().add(r * block_w); @@ -747,8 +824,8 @@ mod simd { let so = _mm_loadu_si128(sp.add(c + 2 * k + 1).cast()); o = _mm_add_epi32(o, _mm_madd_epi16(so, tv[k])); } - e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32); - o = _mm_srai_epi32(_mm_add_epi32(o, rnd), INTER_ROUND_0 as i32); + e = _mm_sra_epi32(_mm_add_epi32(e, rnd), _mm_cvtsi32_si128(round0 as i32)); + o = _mm_sra_epi32(_mm_add_epi32(o, rnd), _mm_cvtsi32_si128(round0 as i32)); let lo = _mm_unpacklo_epi32(e, o); let hi = _mm_unpackhi_epi32(e, o); _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi)); @@ -759,7 +836,7 @@ mod simd { for t in 0..8 { sum += i32::from(t16[t]) * i32::from(*sp.add(c + t) as i16); } - *op.add(c) = sat16(round2(sum, INTER_ROUND_0)); + *op.add(c) = sat16(round2(sum, round0)); c += 1; } } @@ -774,7 +851,15 @@ mod simd { /// loop and it auto-vectorises. The edge case keeps the exact spec form /// (`sample`'s clamp per tap); both arms compute the same sums. #[inline] -fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i16]) { +fn hpass_row( + reference: &[u16], + row_base: usize, + true_width: usize, + x0: i32, + taps: &[i32; 8], + out: &mut [i16], + round0: u32, +) { let block_w = out.len(); let start = x0 - 3; 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 // bit depth), so the products are exactly the i32 ones above but // the widening multiply is one instruction per pair. let t16 = [ - taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16, - taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16, + taps[0] as i16, + taps[1] as i16, + taps[2] as i16, + taps[3] as i16, + taps[4] as i16, + taps[5] as i16, + taps[6] as i16, + taps[7] as i16, ]; - hpass_contig(src, &t16, out); + hpass_contig(src, &t16, out, round0); return; } } @@ -797,7 +888,7 @@ fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, tap let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize; sum += tap * i32::from(reference[row_base + x]); } - *o = sat16(round2(sum, INTER_ROUND_0)); + *o = sat16(round2(sum, round0)); } } @@ -815,6 +906,7 @@ fn horizontal_pass_unscaled( block_w: usize, rows: usize, intermediate: &mut [i16], + round0: u32, ) { // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s, // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position @@ -838,8 +930,14 @@ fn horizontal_pass_unscaled( let span = block_w + 7; if base + (rows - 1) * stride + span <= reference.len() { let t16 = [ - taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16, - taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16, + taps[0] as i16, + taps[1] as i16, + taps[2] as i16, + taps[3] as i16, + taps[4] as i16, + taps[5] as i16, + taps[6] as i16, + taps[7] as i16, ]; hpass_rows( &reference[base..], @@ -848,6 +946,7 @@ fn horizontal_pass_unscaled( block_w, &t16, &mut intermediate[..rows * block_w], + round0, ); return; } @@ -856,9 +955,11 @@ fn horizontal_pass_unscaled( let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize; let out = &mut intermediate[r * block_w..(r + 1) * block_w]; if identity { - let gain = 128 >> INTER_ROUND_0; + let gain = 128 >> round0; if x0 >= 0 && x0 as usize + block_w <= true_width { - if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) { + if let Some(src) = + reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) + { for (o, &s) in out.iter_mut().zip(src) { *o = (gain * i32::from(s)) as i16; } @@ -871,7 +972,7 @@ fn horizontal_pass_unscaled( } continue; } - hpass_row(reference, y * stride, true_width, x0, taps, out); + hpass_row(reference, y * stride, true_width, x0, taps, out, round0); } } @@ -882,7 +983,14 @@ fn horizontal_pass_unscaled( /// eight slots. `acc` is left holding the unrounded sums. #[inline] #[allow(unsafe_code)] -pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, src_stride: usize, rows: usize, taps: &[i32; 8], acc: &mut [i32]) { +pub(crate) fn vpass_row( + intermediate: &[i16], + block_w: usize, + src_stride: usize, + rows: usize, + taps: &[i32; 8], + acc: &mut [i32], +) { #[cfg(target_arch = "x86_64")] { match simd_level() { @@ -903,7 +1011,11 @@ pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, src_stride: usize, } for row in 0..rows { vpass_row_scalar( - &intermediate[row * src_stride..], block_w, src_stride, 0, taps, + &intermediate[row * src_stride..], + block_w, + src_stride, + 0, + taps, &mut acc[row * block_w..(row + 1) * block_w], ); } @@ -923,6 +1035,7 @@ fn vpass_row_u16( taps: &[i32; 8], max: i32, dst: &mut [u16], + round1: u32, ) { #[cfg(target_arch = "x86_64")] { @@ -932,11 +1045,33 @@ fn vpass_row_u16( // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which // the debug asserts pin. SimdLevel::Avx2 => { - unsafe { simd::vpass_row_u16_avx2(intermediate, block_w, src_stride, rows, taps, max, dst) }; + unsafe { + simd::vpass_row_u16_avx2( + intermediate, + block_w, + src_stride, + rows, + taps, + max, + dst, + round1, + ) + }; return; } SimdLevel::Sse41 => { - unsafe { simd::vpass_row_u16_sse41(intermediate, block_w, src_stride, rows, taps, max, dst) }; + unsafe { + simd::vpass_row_u16_sse41( + intermediate, + block_w, + src_stride, + rows, + taps, + max, + dst, + round1, + ) + }; return; } SimdLevel::Scalar => {} @@ -944,8 +1079,14 @@ fn vpass_row_u16( } for row in 0..rows { vpass_row_u16_scalar( - &intermediate[row * src_stride..], block_w, src_stride, 0, taps, max, + &intermediate[row * src_stride..], + block_w, + src_stride, + 0, + taps, + max, &mut dst[row * block_w..(row + 1) * block_w], + round1, ); } } @@ -959,25 +1100,36 @@ fn vpass_row_u16_scalar( taps: &[i32; 8], max: i32, dst: &mut [u16], + round1: u32, ) { for (c, d) in dst[..block_w].iter_mut().enumerate() { let mut sum = 0i32; for (t, &tap) in taps.iter().enumerate() { sum += tap * i32::from(intermediate[(row + t) * src_stride + c]); } - *d = round2(sum, INTER_ROUND_1).clamp(0, max) as u16; + *d = round2(sum, round1).clamp(0, max) as u16; } } /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop). -fn vpass_row_scalar(intermediate: &[i16], block_w: usize, src_stride: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) { +fn vpass_row_scalar( + intermediate: &[i16], + block_w: usize, + src_stride: usize, + row: usize, + taps: &[i32; 8], + acc: &mut [i32], +) { acc[..block_w].fill(0); for (t, &tap) in taps.iter().enumerate() { if tap == 0 { continue; } let base = (row + t) * src_stride; - for (a, &s) in acc[..block_w].iter_mut().zip(&intermediate[base..base + block_w]) { + for (a, &s) in acc[..block_w] + .iter_mut() + .zip(&intermediate[base..base + block_w]) + { *a += tap * i32::from(s); } } @@ -1037,7 +1189,8 @@ pub(crate) fn predict( y_q4: i32, block_w: usize, block_h: usize, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { predict_with_filter( reference, @@ -1054,7 +1207,8 @@ pub(crate) fn predict( // `Regular` (the decoder's own inter path calls // `predict_with_filters` with the kernels it parsed). fctx.interp_filter.get(), - dst, fctx, + dst, + fctx, ); } @@ -1072,7 +1226,8 @@ pub(crate) fn predict_with_filter( block_w: usize, block_h: usize, filter_kind: InterpFilterKind, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { predict_with_filters( reference, @@ -1085,7 +1240,8 @@ pub(crate) fn predict_with_filter( block_h, filter_kind, filter_kind, - dst, fctx, + dst, + fctx, ); } @@ -1105,11 +1261,24 @@ pub(crate) fn predict_with_filters( block_h: usize, h_kind: InterpFilterKind, v_kind: InterpFilterKind, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { predict_with_filters_kern( - reference, stride, true_width, true_height, x_q4, y_q4, block_w, - block_h, block_w, block_h, h_kind, v_kind, dst, fctx, + reference, + stride, + true_width, + true_height, + x_q4, + y_q4, + block_w, + block_h, + block_w, + block_h, + h_kind, + v_kind, + dst, + fctx, ); } @@ -1135,7 +1304,8 @@ pub(crate) fn predict_with_filters_kern( kern_h: usize, h_kind: InterpFilterKind, v_kind: InterpFilterKind, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); @@ -1173,7 +1343,9 @@ pub(crate) fn predict_with_filters_kern( let out = &mut dst[row * block_w..(row + 1) * block_w]; // lane-perf2: an interior row is one contiguous copy. if x0 >= 0 && x0 as usize + block_w <= true_width { - if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) { + if let Some(src) = + reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) + { // The common widths get a constant-length copy: at 8 // samples a `memcpy` call costs more than the move it // makes, and 8x8 is the most common inter block on real @@ -1219,15 +1391,23 @@ pub(crate) fn predict_with_filters_kern( // block's own first row where the pass would have put the 4th. let rows = if yfrac == 0 { block_h } else { block_h + 7 }; let max = crate::decode::sample_max(fctx); + // lane-av112bit: the frame's rounding pair (libaom `get_conv_params_no_round` + // via [`round_pair`]) -- 3/11 at 8 and 10 bits, 5/9 at 12. + let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx))); // lane-mc2: a whole-pel horizontal position makes the horizontal pass the - // identity tap, whose output is `s << 4` (`Round2(128 * s, InterRound0)` - // with the tap 128). The vertical pass then computes - // `Round2(sum(tap * (s << 4)), InterRound1)`, which is the same 8-tap sum - // taken straight off the reference rows with every tap scaled by 16 -- - // bit-identical, and it skips materialising `block_h + 7` intermediate - // rows. Interior blocks only; an edge block still needs the clamped read. + // identity tap, whose output is `(128 >> round0) * s` (`Round2(128 * s, + // round0)` with the tap 128). The vertical pass then computes + // `Round2(sum(tap * ((128 >> round0) * s)), round1)`, which is the same + // 8-tap sum taken straight off the reference rows with every tap scaled + // by `128 >> round0` -- bit-identical (128 is a multiple of `2^round0` at + // every supported depth), and it skips materialising `block_h + 7` + // intermediate rows. Interior blocks only; an edge block still needs the + // clamped read. if xfrac != 0 || yfrac == 0 { // fall through to the two-pass path + if xfrac != 0 || yfrac != 0 { + hit!(MC_SUBPEL_HITS); + } } else { let top = y0 - 3; if top >= 0 @@ -1239,15 +1419,25 @@ pub(crate) fn predict_with_filters_kern( if base + (block_h + 6) * stride + block_w <= reference.len() { let mut v16 = [0i32; 8]; for (o, &t) in v16.iter_mut().zip(v_filter.iter()) { - *o = t * 16; + *o = t * (128 >> round0); } // SAFETY: samples are below `2^15` at every supported bit // depth, so the same bytes read as `i16` are the same values; // the length is unchanged. #[allow(unsafe_code)] - let src: &[i16] = - unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::(), reference.len()) }; - vpass_row_u16(&src[base..], block_w, stride, block_h, &v16, max, dst); + let src: &[i16] = unsafe { + std::slice::from_raw_parts(reference.as_ptr().cast::(), reference.len()) + }; + vpass_row_u16( + &src[base..], + block_w, + stride, + block_h, + &v16, + max, + dst, + round1, + ); #[cfg(test)] crate::encode::stage_since(1, stage_t); return; @@ -1256,17 +1446,36 @@ pub(crate) fn predict_with_filters_kern( } with_scratch(rows, block_w, |intermediate, _acc| { horizontal_pass_unscaled( - reference, stride, true_width, true_height, x0, - if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows, + reference, + stride, + true_width, + true_height, + x0, + if yfrac == 0 { y0 + 3 } else { y0 }, + h_filter, + block_w, + rows, intermediate, + round0, ); if yfrac == 0 { + // The vertical filter is the identity tap here: + // `Round2(128 * a, round1) == Round2(a, round1 - 7)` exactly. for (d, &a) in dst.iter_mut().zip(intermediate.iter()) { - *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16; + *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16; } return; } - vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst); + vpass_row_u16( + intermediate, + block_w, + block_w, + block_h, + v_filter, + max, + dst, + round1, + ); }); #[cfg(test)] @@ -1304,6 +1513,13 @@ pub fn predict_scaled_hits() -> usize { } thread_local! { + /// lane-av112bit: how many inter predictions took the two-pass SUBPEL + /// path (a non-zero horizontal or vertical fraction) -- the 12-bit + /// inter gate's proof that the frame's own `round_0`/`round_1` actually + /// ran, not just the whole-pel identity copy (class + /// `gate-blind-to-feature`). + pub(crate) static MC_SUBPEL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-hbdinter: how many inter predictions this thread has produced /// (single-reference, scaled, and the compound intermediate entry). The /// 10-bit inter gate hard-asserts this moved, so a stream that coded @@ -1343,6 +1559,11 @@ pub fn inter_pred_hits() -> usize { INTER_PRED_HITS.with(|c| c.get()) } +/// Current value of [`MC_SUBPEL_HITS`]. +pub(crate) fn mc_subpel_hits() -> usize { + MC_SUBPEL_HITS.with(|c| c.get()) +} + fn round_pow2_64(value: i64, shift: u32) -> i64 { if shift == 0 { value @@ -1386,6 +1607,7 @@ fn horizontal_scaled_pass( rows: usize, h_kind: InterpFilterKind, intermediate: &mut [i16], + round0: u32, ) { let x_step_qn = round_pow2_64(x_scale_fp, 4); let off = (x_scale_fp - REF_NO_SCALE) * 8; @@ -1407,7 +1629,7 @@ fn horizontal_scaled_pass( let x = int_pel + t as i32 - 3; sum += tap * sample(reference, stride, true_width, true_height, x, y); } - intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16; + intermediate[r * block_w + c] = round2(sum, round0) as i16; } } } @@ -1439,11 +1661,16 @@ fn horizontal_pass( rows: usize, h_kind: InterpFilterKind, intermediate: &mut [i16], + round0: u32, ) { if x_scale_fp == REF_NO_SCALE { let (h_wide, h_narrow) = h_kind.tables(); let xfrac = x_q4.rem_euclid(16) as usize; - let taps = if kern_w <= 4 { &h_narrow[xfrac] } else { &h_wide[xfrac] }; + let taps = if kern_w <= 4 { + &h_narrow[xfrac] + } else { + &h_wide[xfrac] + }; horizontal_pass_unscaled( reference, stride, @@ -1455,12 +1682,24 @@ fn horizontal_pass( block_w, rows, intermediate, + round0, ); return; } horizontal_scaled_pass( - reference, stride, true_width, true_height, x_q4, y0, x_scale_fp, block_w, kern_w, - rows, h_kind, intermediate, + reference, + stride, + true_width, + true_height, + x_q4, + y0, + x_scale_fp, + block_w, + kern_w, + rows, + h_kind, + intermediate, + round0, ); } @@ -1491,11 +1730,25 @@ pub(crate) fn predict_scaled( block_h: usize, h_kind: InterpFilterKind, v_kind: InterpFilterKind, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { predict_scaled_kern( - reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, - block_w, block_h, block_w, block_h, h_kind, v_kind, dst, fctx, + reference, + stride, + true_width, + true_height, + x_q4, + y_q4, + x_scale_fp, + block_w, + block_h, + block_w, + block_h, + h_kind, + v_kind, + dst, + fctx, ); } @@ -1516,7 +1769,8 @@ pub(crate) fn predict_scaled_kern( kern_h: usize, h_kind: InterpFilterKind, v_kind: InterpFilterKind, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); @@ -1539,19 +1793,41 @@ pub(crate) fn predict_scaled_kern( let rows = if yfrac == 0 { block_h } else { block_h + 7 }; let max = crate::decode::sample_max(fctx); + let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx))); with_scratch(rows, block_w, |intermediate, _acc| { horizontal_pass( - reference, stride, true_width, true_height, x_q4, - if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w, - kern_w, rows, h_kind, intermediate, + reference, + stride, + true_width, + true_height, + x_q4, + if yfrac == 0 { y0 + 3 } else { y0 }, + x_scale_fp, + block_w, + kern_w, + rows, + h_kind, + intermediate, + round0, ); if yfrac == 0 { + // Identity vertical tap: `Round2(128 * a, round1) == + // Round2(a, round1 - 7)` exactly. for (d, &a) in dst.iter_mut().zip(intermediate.iter()) { - *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16; + *d = round2(i32::from(a), round1 - 7).clamp(0, max) as u16; } return; } - vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst); + vpass_row_u16( + intermediate, + block_w, + block_w, + block_h, + v_filter, + max, + dst, + round1, + ); }); } @@ -1572,17 +1848,39 @@ pub(crate) fn predict_maybe_scaled( block_h: usize, h_kind: InterpFilterKind, v_kind: InterpFilterKind, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { if x_scale_fp == REF_NO_SCALE { predict_with_filters( - reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind, - v_kind, dst, fctx, + reference, + stride, + true_width, + true_height, + x_q4, + y_q4, + block_w, + block_h, + h_kind, + v_kind, + dst, + fctx, ); } else { predict_scaled( - reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w, - block_h, h_kind, v_kind, dst, fctx, + reference, + stride, + true_width, + true_height, + x_q4, + y_q4, + x_scale_fp, + block_w, + block_h, + h_kind, + v_kind, + dst, + fctx, ); } } @@ -1620,7 +1918,7 @@ const DIST_PRECISION_BITS: u32 = 4; /// Panics when `dst` is not `block_w * block_h` long, or the reference is /// empty. #[allow(clippy::too_many_arguments)] -pub fn predict_compound_intermediate( +pub(crate) fn predict_compound_intermediate( reference: &[u16], stride: usize, true_width: usize, @@ -1633,17 +1931,31 @@ pub fn predict_compound_intermediate( h_kind: InterpFilterKind, v_kind: InterpFilterKind, dst: &mut [i32], + fctx: &crate::decode::FrameCtx, ) { predict_compound_intermediate_kern( - reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, - block_w, block_h, block_w, block_h, h_kind, v_kind, dst, + reference, + stride, + true_width, + true_height, + x_q4, + y_q4, + x_scale_fp, + block_w, + block_h, + block_w, + block_h, + h_kind, + v_kind, + dst, + fctx, ); } /// [`predict_compound_intermediate`] with the 4-tap decision from the block's /// true dims (see [`predict_with_filters_kern`]). #[allow(clippy::too_many_arguments)] -pub fn predict_compound_intermediate_kern( +pub(crate) fn predict_compound_intermediate_kern( reference: &[u16], stride: usize, true_width: usize, @@ -1658,6 +1970,7 @@ pub fn predict_compound_intermediate_kern( h_kind: InterpFilterKind, v_kind: InterpFilterKind, dst: &mut [i32], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); @@ -1682,10 +1995,15 @@ pub fn predict_compound_intermediate_kern( }; let rows = if yfrac == 0 { block_h } else { block_h + 7 }; + // lane-av112bit: the horizontal pass shares `predict_with_filters_kern`'s + // `round_0` (the compound VERTICAL round below is `INTER_ROUND_1_COMPOUND` + // at every bit depth), so the identity-tap gain moves with it the same way. + let (round0, _round1) = round_pair(u32::from(crate::decode::bit_depth(fctx))); // lane-mc2: the unscaled whole-pel horizontal position is the identity - // tap, whose intermediate is `s << 4`, so the vertical pass is the same - // 8-tap sum taken straight off the reference rows with the taps scaled by - // 16 (see `predict_with_filters_kern`). Interior blocks only. + // tap, whose intermediate is `(128 >> round0) * s`, so the vertical pass + // is the same 8-tap sum taken straight off the reference rows with the + // taps scaled by that gain (see `predict_with_filters_kern`). Interior + // blocks only. let x0 = x_q4.div_euclid(16); if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 { let top = y0 - 3; @@ -1698,13 +2016,14 @@ pub fn predict_compound_intermediate_kern( if base + (block_h + 6) * stride + block_w <= reference.len() { let mut v16 = [0i32; 8]; for (o, &t) in v16.iter_mut().zip(v_filter.iter()) { - *o = t * 16; + *o = t * (128 >> round0); } // SAFETY: samples are below `2^15` at every supported bit // depth, so the same bytes read as `i16` are the same values. #[allow(unsafe_code)] - let src: &[i16] = - unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::(), reference.len()) }; + let src: &[i16] = unsafe { + std::slice::from_raw_parts(reference.as_ptr().cast::(), reference.len()) + }; vpass_row(&src[base..], block_w, stride, block_h, &v16, dst); for d in dst.iter_mut() { *d = round2(*d, INTER_ROUND_1_COMPOUND); @@ -1715,9 +2034,19 @@ pub fn predict_compound_intermediate_kern( } with_scratch(rows, block_w, |intermediate, _acc| { horizontal_pass( - reference, stride, true_width, true_height, x_q4, - if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w, - kern_w, rows, h_kind, intermediate, + reference, + stride, + true_width, + true_height, + x_q4, + if yfrac == 0 { y0 + 3 } else { y0 }, + x_scale_fp, + block_w, + kern_w, + rows, + h_kind, + intermediate, + round0, ); if yfrac == 0 { // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`. @@ -1745,10 +2074,16 @@ pub(crate) fn combine_compound( pred1: &[i32], fwd_weight: i32, bck_weight: i32, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block"); assert_eq!(dst.len(), pred0.len(), "the destination is the block"); + // lane-av112bit: `round_bits` is `2*FILTER_BITS - round_0 - round_1` + // with the frame's own `round_0`, i.e. `INTER_POST_ROUND` minus + // [`round_delta`] -- the CONV_BUF gain drops from 16x to 4x at 12-bit + // (`round_0` 5, compound `round_1` 7) and this final round absorbs it. + let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx))); for i in 0..dst.len() { // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin) // applies the two shifts SEPARATELY: a truncating `>> @@ -1758,7 +2093,7 @@ pub(crate) fn combine_compound( // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the // dropped low 4 bits are non-zero. let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight; - dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND) + dst[i] = round2(sum >> DIST_PRECISION_BITS, post_round) .clamp(0, crate::decode::sample_max(fctx)) as u16; } } @@ -1773,15 +2108,22 @@ pub(crate) fn combine_compound( /// produces give the identical `diff` libaom computes. `round` is /// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for /// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`). -pub(crate) fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8], fctx: &crate::decode::FrameCtx) { +pub(crate) fn diffwtd_mask( + pred0: &[i32], + pred1: &[i32], + inv: bool, + mask: &mut [u8], + fctx: &crate::decode::FrameCtx, +) { assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block"); assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel"); // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the - // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0` - // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s - // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`. - let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8); + // bit-depth headroom the CONV_BUF domain carries, minus the [`round_delta`] + // that moves `round_0` itself at 12-bit (`convolve.h:83`'s + // `intbufrange > 16`; at 12-bit this is 14 - 5 - 7 + 4 == 6). + let bd = u32::from(crate::decode::bit_depth(fctx)); + let round = INTER_POST_ROUND + bd.saturating_sub(8) - round_delta(bd); for i in 0..mask.len() { let diff = round2((pred0[i] - pred1[i]).abs(), round); let m = (38 + diff / 16).clamp(0, 64); @@ -1808,11 +2150,13 @@ pub(crate) fn blend_masked_compound( w: usize, h: usize, subsampled: bool, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block"); assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block"); assert_eq!(dst.len(), w * h, "the destination is the block"); + let post_round = INTER_POST_ROUND - round_delta(u32::from(crate::decode::bit_depth(fctx))); for i in 0..h { for j in 0..w { let m = if subsampled { @@ -1828,7 +2172,12 @@ pub(crate) fn blend_masked_compound( i32::from(mask[i * mask_stride + j]) }; let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6; - dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max(fctx)) as u16; + // `post_round` above: `INTER_POST_ROUND - round_delta` -- see + // [`combine_compound`] (the same CONV_BUF gain absorption; the + // `>> 6` above is bit-depth free because the CONV_BUF relative + // weights are). + dst[i * w + j] = + round2(res, post_round).clamp(0, crate::decode::sample_max(fctx)) as u16; } } } @@ -1860,6 +2209,7 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() { InterpFilterKind::Regular, InterpFilterKind::Regular, &mut pred0, + fctx, ); assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}"); @@ -1872,8 +2222,8 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() { #[cfg(test)] mod tests { use super::{ - InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter, - predict_with_filters, + predict, predict_scaled, predict_with_filter, predict_with_filters, InterpFilterKind, + REF_NO_SCALE, }; /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma @@ -1886,7 +2236,7 @@ mod tests { /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream. #[test] fn smooth_filter_matches_aomdec_chroma_inter_block() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); #[rustfmt::skip] let window: [[u8; 24]; 24] = [ [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114], @@ -1945,7 +2295,8 @@ mod tests { 16, 16, InterpFilterKind::Smooth, - &mut dst, fctx, + &mut dst, + fctx, ); #[rustfmt::skip] let expected_row0: [u16; 16] = @@ -1996,7 +2347,7 @@ mod tests { #[test] fn integer_mv_is_identity() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); let width = 12; let height = 12; let reference: Vec = (0..width * height).map(|i| (i * 7 % 251) as u16).collect(); @@ -2010,7 +2361,8 @@ mod tests { 4 * 16, 6, 6, - &mut dst, fctx, + &mut dst, + fctx, ); for row in 0..6 { for col in 0..6 { @@ -2025,7 +2377,7 @@ mod tests { #[test] fn half_pel_reproduces_the_ramp_midpoint() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); // Step 2 so every half-pel position lands on an exact integer. let width = 16; let height = 16; @@ -2043,7 +2395,8 @@ mod tests { 5 * 16, 4, 4, - &mut dst, fctx, + &mut dst, + fctx, ); for row in 0..4 { for col in 0..4 { @@ -2059,7 +2412,7 @@ mod tests { #[test] fn constant_plane_has_unit_dc_gain_at_every_subpel_position() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); let width = 20; let height = 20; let reference = vec![142u16; width * height]; @@ -2075,7 +2428,8 @@ mod tests { 5 * 16 + yfrac, 5, 5, - &mut dst, fctx, + &mut dst, + fctx, ); assert!( dst.iter().all(|&v| v == 142), @@ -2087,7 +2441,7 @@ mod tests { #[test] fn horizontal_and_vertical_only_filtering_differ() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); // A plane linear in both x and y with different, even coefficients so // each axis's half-pel interpolation lands on an exact integer: this // pins the actual value each pass produces, not just that the two @@ -2109,7 +2463,8 @@ mod tests { 3 * 16, 4, 4, - &mut horiz, fctx, + &mut horiz, + fctx, ); let mut vert = vec![0u16; 4 * 4]; predict( @@ -2121,7 +2476,8 @@ mod tests { 3 * 16 + 8, 4, 4, - &mut vert, fctx, + &mut vert, + fctx, ); for row in 0..4 { @@ -2148,7 +2504,7 @@ mod tests { #[test] fn mv_past_the_edge_clamps_instead_of_panicking() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); let width = 8; let height = 8; let reference: Vec = (0..width * height).map(|i| (i * 3 % 200) as u16).collect(); @@ -2164,7 +2520,8 @@ mod tests { -50 * 16 + 5, 4, 4, - &mut dst, fctx, + &mut dst, + fctx, ); let expected = reference[0]; // the whole plane clamps to the top-left corner assert!( @@ -2182,7 +2539,8 @@ mod tests { 50 * 16 + 5, 4, 4, - &mut dst2, fctx, + &mut dst2, + fctx, ); let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner assert!( @@ -2193,7 +2551,7 @@ mod tests { #[test] fn predict_scaled_at_no_scale_matches_predict_with_filters() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE // must reduce predict_scaled's per-column scaled walk to the exact // same int_pel/filter_idx sequence predict_with_filters computes from @@ -2217,7 +2575,8 @@ mod tests { 8, InterpFilterKind::Regular, InterpFilterKind::Regular, - &mut expected, fctx, + &mut expected, + fctx, ); let mut got = vec![0u16; block_w * 8]; predict_scaled( @@ -2232,7 +2591,8 @@ mod tests { 8, InterpFilterKind::Regular, InterpFilterKind::Regular, - &mut got, fctx, + &mut got, + fctx, ); assert_eq!( got, expected, @@ -2272,26 +2632,52 @@ mod tests { for frac in 0..16usize { let taps = &table[frac]; let t16 = [ - taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16, - taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16, + taps[0] as i16, + taps[1] as i16, + taps[2] as i16, + taps[3] as i16, + taps[4] as i16, + taps[5] as i16, + taps[6] as i16, + taps[7] as i16, ]; for w in [4usize, 8, 12, 16, 20, 32, 64, 128] { let src: Vec = (0..w + 7) .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16) .collect(); let mut want = vec![0i16; w]; - super::hpass_contig_scalar(&src, &t16, &mut want); + super::hpass_contig_scalar(&src, &t16, &mut want, 3); let mut got = vec![0i16; w]; - super::hpass_contig(&src, &t16, &mut got); + super::hpass_contig(&src, &t16, &mut got, 3); assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}"); #[cfg(target_arch = "x86_64")] { let mut sse = vec![0i16; w]; - unsafe { super::simd::hpass_sse2(&src, 0, 1, sse.len(), &t16, &mut sse) }; + unsafe { + super::simd::hpass_sse2( + &src, + 0, + 1, + sse.len(), + &t16, + &mut sse, + 3, + ) + }; assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}"); if std::arch::is_x86_feature_detected!("avx2") { let mut avx = vec![0i16; w]; - unsafe { super::simd::hpass_avx2(&src, 0, 1, avx.len(), &t16, &mut avx) }; + unsafe { + super::simd::hpass_avx2( + &src, + 0, + 1, + avx.len(), + &t16, + &mut avx, + 3, + ) + }; assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}"); } } @@ -2308,10 +2694,11 @@ mod tests { /// is a claim about the FILTER TABLES, not about a sample: every kernel's /// positive taps sum to at most `S+` and its negative ones to `S-`, so a /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored - /// value is that over `1 << INTER_ROUND_0`. This enumerates all four + /// value is that over `1 << round_0`. This enumerates all four /// filter kinds, both their wide and narrow tables and all 16 phases at - /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses - /// 12-bit by name) and pins the result inside `i16` -- so the SIMD + /// the deepest sample this decoder accepts (12-bit now -- lane-av112bit + /// lifted the refusal, with `round_0` at 5 there and 3 at 8/10-bit) and + /// pins the result inside `i16` -- so the SIMD /// stores' `packs_epi32` never saturates on a motion-compensation path. #[test] fn horizontal_intermediate_fits_i16() { @@ -2321,23 +2708,26 @@ mod tests { InterpFilterKind::Sharp, InterpFilterKind::Bilinear, ]; - let max_sample = 1023i32; // 10-bit - let (mut worst_lo, mut worst_hi) = (0i32, 0i32); - for &kind in &kinds { - let (wide, narrow) = kind.tables(); - for table in [wide, narrow] { - for taps in table { - let pos: i32 = taps.iter().filter(|&&t| t > 0).sum(); - let neg: i32 = taps.iter().filter(|&&t| t < 0).sum(); - worst_hi = worst_hi.max(super::round2(max_sample * pos, super::INTER_ROUND_0)); - worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0)); + // (max sample, the frame's `round_0`) per supported bit depth. + for (max_sample, round0) in [(255i32, 3u32), (1023, 3), (4095, 5)] { + let (mut worst_lo, mut worst_hi) = (0i32, 0i32); + for &kind in &kinds { + let (wide, narrow) = kind.tables(); + for table in [wide, narrow] { + for taps in table { + let pos: i32 = taps.iter().filter(|&&t| t > 0).sum(); + let neg: i32 = taps.iter().filter(|&&t| t < 0).sum(); + worst_hi = worst_hi.max(super::round2(max_sample * pos, round0)); + worst_lo = worst_lo.min(super::round2(max_sample * neg, round0)); + } } } + assert!( + worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN), + "the {max_sample}-sample (round_0 {round0}) intermediate range \ + [{worst_lo}, {worst_hi}] must fit i16" + ); } - assert!( - worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN), - "the 10-bit intermediate range [{worst_lo}, {worst_hi}] must fit i16" - ); } /// lane-perf5: the vertical pass's SIMD kernels against the scalar @@ -2368,29 +2758,58 @@ mod tests { }; let reference: Vec = (0..width * height).map(|_| (rng() % 256) as u16).collect(); let mut checked = 0usize; - for &kind in &[InterpFilterKind::Regular, InterpFilterKind::Smooth, InterpFilterKind::Sharp] { + for &kind in &[ + InterpFilterKind::Regular, + InterpFilterKind::Smooth, + InterpFilterKind::Sharp, + ] { let (v_wide, v_narrow) = kind.tables(); - for (bw, bh) in [(4usize, 4usize), (5, 4), (8, 8), (16, 16), (12, 8), (32, 16)] { + for (bw, bh) in [ + (4usize, 4usize), + (5, 4), + (8, 8), + (16, 16), + (12, 8), + (32, 16), + ] { for yfrac in 1..16i32 { let (x0, y0) = (7i32, 9i32); - let taps = if bh <= 4 { &v_narrow[yfrac as usize] } else { &v_wide[yfrac as usize] }; + let taps = if bh <= 4 { + &v_narrow[yfrac as usize] + } else { + &v_wide[yfrac as usize] + }; let mut want = vec![0u16; bw * bh]; for row in 0..bh { for col in 0..bw { let mut sum = 0i32; for (t, &tap) in taps.iter().enumerate() { let y = y0 - 3 + row as i32 + t as i32; - let s = i32::from(reference[y as usize * width + x0 as usize + col]); + let s = + i32::from(reference[y as usize * width + x0 as usize + col]); // The identity horizontal tap's output. sum += tap * (s << 4); } - want[row * bw + col] = super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16; + want[row * bw + col] = + super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16; } } let mut got = vec![0u16; bw * bh]; super::predict_with_filters_kern( - &reference, width, width, height, x0 * 16, y0 * 16 + yfrac, - bw, bh, bw, bh, kind, kind, &mut got, fctx, + &reference, + width, + width, + height, + x0 * 16, + y0 * 16 + yfrac, + bw, + bh, + bw, + bh, + kind, + kind, + &mut got, + fctx, ); assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}"); checked += 1; @@ -2431,61 +2850,142 @@ mod tests { // horizontal path, which runs these kernels // straight over a reference plane's stride. for st in [w, w + 3] { - let inter: Vec = (0..rows * st) - .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16) - .collect(); - for row in [0usize, 1, 4] { - let mut want = vec![0i32; w]; - super::vpass_row_scalar(&inter[row * st..], w, st, 0, taps, &mut want); - let mut got = vec![0i32; w]; - super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got); - assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}"); - #[cfg(target_arch = "x86_64")] - { - if std::arch::is_x86_feature_detected!("sse4.1") { - let mut sse = vec![0i32; w]; - unsafe { super::simd::vpass_sse41(&inter[row * st..], w, st, 1, taps, &mut sse) }; - assert_eq!(sse, want, "sse4.1 w={w} frac={frac} row={row}"); - } - if std::arch::is_x86_feature_detected!("avx2") { - let mut avx = vec![0i32; w]; - unsafe { super::simd::vpass_avx2(&inter[row * st..], w, st, 1, taps, &mut avx) }; - assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}"); - } - } - // lane-mc: the rounding-fused form, over both - // sample maxima this decoder accepts -- its - // `packus`/`min_epu16` pair must reproduce - // `round2(_, InterRound1).clamp(0, max)`. - for max in [255i32, 1023] { - let mut want_u16 = vec![0u16; w]; - super::vpass_row_u16_scalar(&inter, w, st, row, taps, max, &mut want_u16); - for (d, &a) in want_u16.iter().zip(want.iter()) { - assert_eq!( - i32::from(*d), - super::round2(a, super::INTER_ROUND_1).clamp(0, max), - "the fused reference is the two-step one" - ); - } - let mut got_u16 = vec![0u16; w]; - super::vpass_row_u16(&inter[row * st..], w, st, 1, taps, max, &mut got_u16); - assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}"); + let inter: Vec = (0..rows * st) + .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16) + .collect(); + for row in [0usize, 1, 4] { + let mut want = vec![0i32; w]; + super::vpass_row_scalar( + &inter[row * st..], + w, + st, + 0, + taps, + &mut want, + ); + let mut got = vec![0i32; w]; + super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got); + assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}"); #[cfg(target_arch = "x86_64")] { if std::arch::is_x86_feature_detected!("sse4.1") { - let mut sse = vec![0u16; w]; - unsafe { super::simd::vpass_row_u16_sse41(&inter[row * st..], w, st, 1, taps, max, &mut sse) }; - assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}"); + let mut sse = vec![0i32; w]; + unsafe { + super::simd::vpass_sse41( + &inter[row * st..], + w, + st, + 1, + taps, + &mut sse, + ) + }; + assert_eq!( + sse, want, + "sse4.1 w={w} frac={frac} row={row}" + ); } if std::arch::is_x86_feature_detected!("avx2") { - let mut avx = vec![0u16; w]; - unsafe { super::simd::vpass_row_u16_avx2(&inter[row * st..], w, st, 1, taps, max, &mut avx) }; - assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}"); + let mut avx = vec![0i32; w]; + unsafe { + super::simd::vpass_avx2( + &inter[row * st..], + w, + st, + 1, + taps, + &mut avx, + ) + }; + assert_eq!( + avx, want, + "avx2 w={w} frac={frac} row={row}" + ); + } + } + // lane-mc: the rounding-fused form, over both + // sample maxima this decoder accepts -- its + // `packus`/`min_epu16` pair must reproduce + // `round2(_, InterRound1).clamp(0, max)`. + for max in [255i32, 1023] { + let mut want_u16 = vec![0u16; w]; + super::vpass_row_u16_scalar( + &inter, + w, + st, + row, + taps, + max, + &mut want_u16, + 11, + ); + for (d, &a) in want_u16.iter().zip(want.iter()) { + assert_eq!( + i32::from(*d), + super::round2(a, super::INTER_ROUND_1) + .clamp(0, max), + "the fused reference is the two-step one" + ); + } + let mut got_u16 = vec![0u16; w]; + super::vpass_row_u16( + &inter[row * st..], + w, + st, + 1, + taps, + max, + &mut got_u16, + 11, + ); + assert_eq!( + got_u16, want_u16, + "fused w={w} frac={frac} row={row} max={max}" + ); + #[cfg(target_arch = "x86_64")] + { + if std::arch::is_x86_feature_detected!("sse4.1") { + let mut sse = vec![0u16; w]; + unsafe { + super::simd::vpass_row_u16_sse41( + &inter[row * st..], + w, + st, + 1, + taps, + max, + &mut sse, + 11, + ) + }; + assert_eq!( + sse, want_u16, + "fused sse4.1 w={w} max={max}" + ); + } + if std::arch::is_x86_feature_detected!("avx2") { + let mut avx = vec![0u16; w]; + unsafe { + super::simd::vpass_row_u16_avx2( + &inter[row * st..], + w, + st, + 1, + taps, + max, + &mut avx, + 11, + ) + }; + assert_eq!( + avx, want_u16, + "fused avx2 w={w} max={max}" + ); + } } } + checked += 1; } - checked += 1; - } } } } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 82d1dd3b..cabed245 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -72,7 +72,15 @@ const REFUSALS: &[&str] = &[ // (`a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal`) // still runs: it now reports `reached = 0` with the same non-vacuous // premise (allow_intrabc frames + decoded sub-8 leaves). - "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)", + // lane-av112bit: the blanket 12-bit refusal is REPLACED by the four + // named refusals below -- the witnessed paths (intra stack, dequant/ + // transforms at the 12-bit tables, deblock, CDEF, Wiener+SGR + // restoration, translational subpel MC through the parameterised + // round_0/round_1) are lifted by the lane's byte-exact ffmpeg gates. + "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)", + "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)", + "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)", + "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)", // lane-av1txr: the silent-garbage guard. A 4:4:4/4:2:2 stream used to // decode with no refusal and wrong pixels (every chroma extent is // hardcoded 4:2:0, the probe emits 4:2:0 planes only); it is now refused @@ -347,9 +355,24 @@ const PROVEN: &[(&str, &str)] = &[ "a motion_mode symbol for a block shape with no CDF row here", "every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row", ), + // lane-av112bit: four real-aomenc 12-bit streams, each refused by name + // (the gates encode with aomenc --bit-depth=12 and assert the exact + // string; the two pixel witnesses are the same battery's Ok arms). ( - "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)", - "a_twelve_bit_sequence_header_is_refused_by_name", + "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)", + "a_12bit_warped_motion_stream_is_refused_by_name", + ), + ( + "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)", + "a_12bit_compound_inter_stream_is_refused_by_name", + ), + ( + "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)", + "a_12bit_film_grain_stream_is_refused_by_name", + ), + ( + "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)", + "a_12bit_screen_content_stream_is_refused_by_name", ), // lane-av1txr: the guard's own gate builds a profile-1 and a profile-2 // sequence header by hand and asserts each refuses by name while the @@ -589,7 +612,11 @@ mod tests { .chain(REFUSALS) .map(|&s| s.to_owned()) .collect(); - assert!(found.len() >= 30, "the refusal scan found only {} reasons -- it is broken, not the decoder", found.len()); + assert!( + found.len() >= 30, + "the refusal scan found only {} reasons -- it is broken, not the decoder", + found.len() + ); let added: Vec<&String> = found.difference(&listed).collect(); assert!( @@ -635,9 +662,14 @@ mod tests { let mut found: BTreeSet = BTreeSet::new(); for (i, _) in src.match_indices("\"SKIP ") { let rest = &src[i + "\"SKIP ".len()..]; - let Some(colon) = rest.find(':') else { continue }; + let Some(colon) = rest.find(':') else { + continue; + }; let name = &rest[..colon]; - if !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') { + if !name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') + { continue; } // The tail of the message says what was skipped. Only "{e}" -- the @@ -650,7 +682,10 @@ mod tests { } } let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect(); - let added: Vec<&String> = found.iter().filter(|n| !listed.contains(n.as_str())).collect(); + let added: Vec<&String> = found + .iter() + .filter(|n| !listed.contains(n.as_str())) + .collect(); assert!( added.is_empty(), "these gates turn a decode error into a printed SKIP and are not declared: \ @@ -723,9 +758,18 @@ mod tests { fn every_partition_value_of_an_enumerated_alphabet_has_an_arm() { // (the refusal in the fallback arm, the alphabet its CDF codes) let blocks: [(&str, usize); 4] = [ - ("a 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1), - ("an INTER 32x32 partition type this decoder does not code", crate::cdf::PARTITION_W32[0].len() - 1), - ("a 128x128 superblock partition value outside the 8-symbol alphabet", crate::cdf::PARTITION_W128[0].len() - 1), + ( + "a 32x32 partition type this decoder does not code", + crate::cdf::PARTITION_W32[0].len() - 1, + ), + ( + "an INTER 32x32 partition type this decoder does not code", + crate::cdf::PARTITION_W32[0].len() - 1, + ), + ( + "a 128x128 superblock partition value outside the 8-symbol alphabet", + crate::cdf::PARTITION_W128[0].len() - 1, + ), // lane-t900 r24: the key-frame superblock root. Its `part` is // either a `partition_w64` symbol or, at a frame edge, one of the // three gathered outcomes (PARTITION_HORZ, PARTITION_VERT, @@ -779,7 +823,10 @@ mod tests { "the `match` at decode.rs:{} refuses {reason:?} but has no arm for {:?} -- that \ is a real gap in its {alphabet}-value alphabet, not a dead refusal", i + 1, - missing.iter().map(|v| PARTITION_NAMES[*v]).collect::>() + missing + .iter() + .map(|v| PARTITION_NAMES[*v]) + .collect::>() ); } assert_eq!( @@ -833,7 +880,11 @@ mod tests { .next() .unwrap_or("") .to_owned(); - assert!(!var.is_empty(), "the chain at decode.rs:{} tests nothing", head + 1); + assert!( + !var.is_empty(), + "the chain at decode.rs:{} tests nothing", + head + 1 + ); // Walk up collecting every branch head of this chain, each read to // the line that opens its body. @@ -843,7 +894,8 @@ mod tests { loop { i -= 1; let t = lines[i].trim_start(); - if indent(lines[i]) != outer || !(t.starts_with("} else if ") || t.starts_with("if ")) + if indent(lines[i]) != outer + || !(t.starts_with("} else if ") || t.starts_with("if ")) { if i == 0 { break; @@ -893,7 +945,10 @@ mod tests { "the chain at decode.rs:{} refuses {reason:?} but no branch names {:?} -- that \ is a real gap in its {alphabet}-value alphabet, not a dead refusal", head + 1, - missing.iter().map(|v| PARTITION_NAMES[*v]).collect::>() + missing + .iter() + .map(|v| PARTITION_NAMES[*v]) + .collect::>() ); } assert_eq!(found, chains.len()); @@ -996,11 +1051,18 @@ mod tests { values.insert(((1u64 << length) - 2) as u32); } let max = *values.iter().max().unwrap(); - assert_eq!(max, (1u32 << 20) - 2, "the enumeration misses the spec's own ceiling"); + assert_eq!( + max, + (1u32 << 20) - 2, + "the enumeration misses the spec's own ceiling" + ); // A coefficient is masked to 20 bits (spec 5.11.39), and the base and // base-range syntax contribute at most 15 of that before the tail, so // this is the largest tail a legal coefficient can need. - assert!(max >= 0xF_FFFF - 15, "the ceiling is below the largest legal tail"); + assert!( + max >= 0xF_FFFF - 15, + "the ceiling is below the largest legal tail" + ); for value in values { match roundtrip(value) { Ok(read) => assert_eq!(read, value, "the Golomb tail {value} read back as {read}"), @@ -1056,7 +1118,11 @@ mod tests { ]; assert_eq!(alphabets[0].1, 13, "the y_mode alphabet changed size"); for group in &crate::cdf::Y_MODE { - assert_eq!(group.len() - 1, alphabets[0].1, "the y_mode rows disagree on width"); + assert_eq!( + group.len() - 1, + alphabets[0].1, + "the y_mode rows disagree on width" + ); } let src = include_str!("decode.rs"); @@ -1064,12 +1130,17 @@ mod tests { let mut sites = 0usize; for (i, line) in lines.iter().enumerate() { let t = line.trim(); - let Some(rest) = t.strip_prefix("if mode >= ") else { continue }; + let Some(rest) = t.strip_prefix("if mode >= ") else { + continue; + }; let Some(threshold) = rest.trim_end_matches(" {").parse::().ok() else { continue; }; // Only the guards carrying THIS refusal. - if !lines[i..(i + 4).min(lines.len())].join("\n").contains(REFUSAL) { + if !lines[i..(i + 4).min(lines.len())] + .join("\n") + .contains(REFUSAL) + { continue; } sites += 1; @@ -1099,7 +1170,10 @@ mod tests { i + 1 ); } - assert_eq!(sites, 3, "the intra-mode guard is at three sites, found {sites}"); + assert_eq!( + sites, 3, + "the intra-mode guard is at three sites, found {sites}" + ); } /// lane-t900 r31, ENUMERATION for "a HORZ/VERT intra strip in a @@ -1159,7 +1233,10 @@ mod tests { } } } - assert!(with_128 > 0, "enumeration is vacuous -- no 128-sided footprint was tried"); + assert!( + with_128 > 0, + "enumeration is vacuous -- no 128-sided footprint was tried" + ); assert_eq!( allowed_at_128, 0, "a footprint with a 128-pixel side passed av1_allow_palette's bound -- the \ @@ -1271,11 +1348,17 @@ mod tests { // (3) The two tables, read out of decode_rect_split's own text: every // `(w, h) =>` / `(w, h) |` match arm head between the table's `let` // and the guard that follows it. - let body_at = src.find("fn decode_rect_split(").expect("decode_rect_split is gone"); + let body_at = src + .find("fn decode_rect_split(") + .expect("decode_rect_split is gone"); let body = &src[body_at..]; let slice = |from: &str, to: &str| -> &str { - let a = body.find(from).unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split")); - let b = body[a..].find(to).unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split")); + let a = body + .find(from) + .unwrap_or_else(|| panic!("{from:?} is gone from decode_rect_split")); + let b = body[a..] + .find(to) + .unwrap_or_else(|| panic!("{to:?} is gone from decode_rect_split")); &body[a..a + b] }; let arm_shapes = |text: &str| -> BTreeSet<(usize, usize)> { @@ -1348,7 +1431,10 @@ mod tests { } } } - assert_eq!(checked, 40, "the strip domain is not the ten rect shapes x four depths"); + assert_eq!( + checked, 40, + "the strip domain is not the ten rect shapes x four depths" + ); } /// lane-t900 r33, ENUMERATION for "CfL, filter intra or a palette on a @@ -1458,9 +1544,15 @@ mod tests { } continue; } - let Some(rest) = line.strip_prefix('(') else { continue }; - let Some((pair, _)) = rest.split_once(") =>") else { continue }; - let Some((a, b)) = pair.split_once(',') else { continue }; + let Some(rest) = line.strip_prefix('(') else { + continue; + }; + let Some((pair, _)) = rest.split_once(") =>") else { + continue; + }; + let Some((a, b)) = pair.split_once(',') else { + continue; + }; let bw: usize = a.trim().parse().expect("arm bw"); let bh: usize = b.trim().parse().expect("arm bh"); assert!( @@ -1472,9 +1564,18 @@ mod tests { seen.push((bw, bh)); arms += 1; } - assert!(arms >= 10, "only {arms} arms parsed -- the table's shape changed"); - assert!(saw_none_fallback, "filter_intra_size_class_rect lost its `_ => None` fallback"); - assert!(saw_square_delegate, "filter_intra_size_class_rect lost its square-delegate arm"); + assert!( + arms >= 10, + "only {arms} arms parsed -- the table's shape changed" + ); + assert!( + saw_none_fallback, + "filter_intra_size_class_rect lost its `_ => None` fallback" + ); + assert!( + saw_square_delegate, + "filter_intra_size_class_rect lost its square-delegate arm" + ); // The guard arm delegates square strips to `filter_intra_size_class`; // drive the delegate directly, so a widening there turns THIS test red // (the numeric walk never reaches the guard arm). @@ -1524,7 +1625,10 @@ mod tests { ); } } - assert_eq!(sites, 8, "the call-site audit found {sites} sites, not the 8 it enumerated"); + assert_eq!( + sites, 8, + "the call-site audit found {sites} sites, not the 8 it enumerated" + ); } /// Every entry of [`PROVEN`] must still name a live refusal and a test @@ -1543,7 +1647,9 @@ mod tests { "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string" ); assert!( - sources.iter().any(|src| src.contains(&format!("fn {gate}("))), + sources + .iter() + .any(|src| src.contains(&format!("fn {gate}("))), "{reason:?} names the proving test {gate}, which exists in neither stream.rs \ nor decode.rs" ); diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index 959a992f..fcc7dc0d 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -63,7 +63,12 @@ fn inverse_recenter(r: u32, v: u32) -> u32 { /// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed /// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around /// `reference`. -fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32, reference: u32) -> u32 { +fn decode_unsigned_subexp_with_ref_msac( + dec: &mut SymbolDecoder, + n: u32, + k: u32, + reference: u32, +) -> u32 { let v = decode_subexp_msac(dec, n, k); if (reference << 1) <= n { inverse_recenter(reference, v) @@ -74,7 +79,13 @@ fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32, /// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter` /// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`. -fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i32, k: u32, reference: i32) -> i32 { +fn decode_signed_subexp_with_ref_msac( + dec: &mut SymbolDecoder, + low: i32, + high: i32, + k: u32, + reference: i32, +) -> i32 { let n = (high - low) as u32; let r = (reference - low).clamp(0, n as i32) as u32; 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 /// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating /// `reference` in place (the running per-plane, per-tile reference state). -fn read_wiener_filter(dec: &mut SymbolDecoder, chroma: bool, reference: &mut WienerInfo) -> WienerInfo { +fn read_wiener_filter( + dec: &mut SymbolDecoder, + chroma: bool, + reference: &mut WienerInfo, +) -> WienerInfo { let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter); let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter); let info = WienerInfo { vfilter, hfilter }; @@ -462,7 +477,8 @@ pub(crate) fn read_lr( reference: &mut [(WienerInfo, SgrprojInfo); 3], mi_row: u32, mi_col: u32, - sb_mi: u32, fctx: &crate::decode::FrameCtx, + sb_mi: u32, + fctx: &crate::decode::FrameCtx, ) { if !lr.uses_lr { return; @@ -636,8 +652,16 @@ fn lr_sample( ) -> i32 { let col_c = col.clamp(0, plane_w as i64 - 1) as usize; i32::from( - lr_src_row(cdef, deblocked, stride, plane_w, plane_h, stripe_v_start, stripe_v_end, row) - [col_c], + lr_src_row( + cdef, + deblocked, + stride, + plane_w, + plane_h, + stripe_v_start, + stripe_v_end, + row, + )[col_c], ) } @@ -671,7 +695,11 @@ fn lr_src_row<'a>( let dist = stripe_v_start as i64 - 1 - row; ( deblocked, - if dist == 0 { stripe_v_start - 1 } else { stripe_v_start.saturating_sub(2) }, + if dist == 0 { + stripe_v_start - 1 + } else { + stripe_v_start.saturating_sub(2) + }, ) } } else if stripe_v_end == plane_h { @@ -712,7 +740,8 @@ fn apply_wiener_stripe( h_end: usize, v_start: usize, v_end: usize, - info: &WienerInfo, fctx: &crate::decode::FrameCtx, + info: &WienerInfo, + fctx: &crate::decode::FrameCtx, ) { let w = h_end - h_start; let h = v_end - v_start; @@ -720,8 +749,26 @@ fn apply_wiener_stripe( return; } let bd = i64::from(crate::decode::bit_depth(fctx)); + // lane-av112bit: libaom `get_conv_params_wiener` (`convolve.h:107..118`) + // raises the Wiener pair by the same `intbufrange` delta as MC's: at + // 12-bit `round_0` is 5 and `round_1` 9 (8/10-bit: 3 and 11). The ROUNDS + // are parameterised; the intermediate CLAMP below keeps the corpus-proven + // constant-bound structure extended by the same bd formulas -- a first + // attempt at the C clamp's exact per-sample transform (the add_src bias + // is `src[centre] << FILTER_BITS + (1 << (bd + FILTER_BITS - 1))`, which + // survives `Round2(_, round_0)` as `(128 >> round_0) * s + + // (1 << (bd + 6 - round_0))`) MOVED the 10-bit 128-superblock film gate + // (frame 1 luma): libaom's 8-tap-loop alignment trick means the C + // horizontal intermediate is not `ours + that bias` wherever the clamp + // actually binds, so the exact transform is NOT derivable from the + // convolve source alone. The bd-formula clamp is what every 8/10-bit + // byte-exact gate (this film included) has always pinned, and the 12-bit + // key witness passes byte-exact with it; where C's real clamp would bind + // differently at 12 bits remains unproven either way -- recorded in + // `lanes/av112bit.report.md` as the open half of the Wiener lift. let wiener_bias = 1i64 << (bd + 3); let wiener_limit = 1i64 << (bd + 5); + let (round0, round1) = crate::mc::round_pair(bd as u32); let rows = h + 6; // lane-perf7: reused across stripes, as the sgrproj `ab` grids are -- // this was a fresh allocation per stripe. Every entry is written below. @@ -738,28 +785,50 @@ fn apply_wiener_stripe( // stripe substitution is resolved once per row by `lr_src_row`, and only // a unit touching the plane's left or right edge needs the clamped copy. let hf = &info.hfilter; - let t16: [i16; 8] = - [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]; + let t16: [i16; 8] = [ + 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, + ]; // lane-mc: the intermediate is `i16` now. Both bounds are inside that - // range at 8- and 10-bit (12-bit is refused in stream.rs), so the - // kernel's saturating store composes with this clamp instead of changing - // it: `[-2048, 8191]` at 8-bit, `[-8192, 32767]` at 10. - let (lo_bound, hi_bound) = (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16); + // range at every supported bit depth (the centred sum's own range, + // `|kernel| <= 348` against `2^bd - 1` samples, never reaches them), so + // the kernel's saturating store composes with this clamp instead of + // changing it: `[-2^(bd+3), 2^(bd+5)-1-2^(bd+3)]` -- 8-bit + // `[-2048, 6143]`, 10-bit `[-8192, 24575]`. At 12-bit those formulas + // leave `i16`, so the clamp there is the widest `i16` window -- which + // strictly contains the kernel's own mathematical range (`|sum| <= + // round2(348 * 4095, round_0=5) == 27976 < 2^15`), i.e. it never binds, + // the property the 8/10-bit bounds have on the whole proven corpus. + let (lo_bound, hi_bound) = if bd >= 12 { + (i16::MIN, i16::MAX) + } else { + (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16) + }; let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut())); for r in 0..rows { let row = v_start as i64 - 3 + r as i64; - let src = lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row); + let src = lr_src_row( + cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, + ); let lo = h_start as i64 - 3; let out = &mut inter[r * w..r * w + w]; - if lo >= 0 && lo as usize + w + 7 <= plane_w { - crate::mc::hpass_contig(&src[lo as usize..], &t16, out); - } else { + // The row the pass convolves, contiguous when the block sits inside + // the plane and the clamped copy (`hbuf`) at an edge. + let interior = lo >= 0 && lo as usize + w + 7 <= plane_w; + if !interior { hbuf.clear(); hbuf.extend( (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]), ); - crate::mc::hpass_contig(&hbuf, &t16, out); } + let row_slice: &[u16] = if interior { &src[lo as usize..] } else { &hbuf }; + crate::mc::hpass_contig(row_slice, &t16, out, round0); for v in out.iter_mut() { *v = (*v).clamp(lo_bound, hi_bound); } @@ -769,7 +838,9 @@ fn apply_wiener_stripe( // instead of taking a thread-local read per output sample. let smax = i64::from(crate::decode::sample_max(fctx)); // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves - // the accumulator unrounded, and `Round2(_, 11)` is `INTER_ROUND_1`. + // the accumulator unrounded, and `Round2(_, round1)` is the frame's + // non-compound `round_1` (11 at 8/10-bit, 9 at 12 -- libaom's + // `get_conv_params_wiener`). let vf = &info.vfilter; let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0]; let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut())); @@ -779,7 +850,7 @@ fn apply_wiener_stripe( crate::mc::vpass_row(&inter[r * w..], w, w, 1, &taps, &mut acc); let dst = &mut out[(v_start + r) * stride + h_start..][..w]; for (o, &a) in dst.iter_mut().zip(acc.iter()) { - *o = round2(i64::from(a), 11).clamp(0, smax) as u16; + *o = round2(i64::from(a), round1).clamp(0, smax) as u16; } } WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc); @@ -815,31 +886,27 @@ thread_local! { // `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other // transcription slip. const SGR_X_BY_XPLUS1: [i32; 256] = [ - 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, - 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, - 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, - 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, - 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, - 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, - 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, - 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, - 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, - 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, - 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, - 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 256, + 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, 240, 241, 242, 243, + 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 248, 248, 248, 248, 249, 249, 249, 249, + 249, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, + 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, + 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, + 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 256, ]; /// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25` /// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`. const SGR_ONE_BY_X: [i32; 25] = [ - 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, 216, 205, 195, 186, - 178, 171, 164, + 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, + 216, 205, 195, 186, 178, 171, 164, ]; const SGRPROJ_MTABLE_BITS: u32 = 20; @@ -877,7 +944,8 @@ fn compute_ab( // stripe, ~70 KB each at a 64-wide unit), i.e. an allocation whose every // page then faulted in on first touch. Every entry is written below, so // the resize's fill value is never read. - ab: &mut Vec<(i32, i64)>, fctx: &crate::decode::FrameCtx, + ab: &mut Vec<(i32, i64)>, + fctx: &crate::decode::FrameCtx, ) { let gw = w + 2; let gh = h + 2; @@ -927,8 +995,9 @@ fn compute_ab( let i = gi as i64 - 1; { let mut accumulate = |row: i64, add: bool| { - let src = - lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row); + let src = lr_src_row( + cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, + ); fill_clamped_row(src, plane_w, base_col, &mut samp); if add { 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( a_row[gj] = a; b_row[gj] = b; } - ab_row(a_row, b_row, n, s, bd_shift, one_by_x, &mut ab[gi * gw..gi * gw + gw]); + ab_row( + a_row, + b_row, + n, + s, + bd_shift, + one_by_x, + &mut ab[gi * gw..gi * gw + gw], + ); let dump_gj = 6i64 - h_start as i64 + 1; if dump && v_start as i64 + i == 60 && r == 1 && (0..gw as i64).contains(&dump_gj) { 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 let b_s = round2_u31(b, bd_shift); let p = (a_s * n - b_s * b_s).max(0); let a_val = SGR_X_BY_XPLUS1[z_index(p, s)]; - let b_val = round2((256 - a_val) as i64 * i64::from(b) * one_by_x, SGRPROJ_RECIP_BITS); + let b_val = round2( + (256 - a_val) as i64 * i64::from(b) * one_by_x, + SGRPROJ_RECIP_BITS, + ); (a_val, b_val) } /// One grid row's `(A, B)` pairs: [`ab_point`] per element, eight at a time /// under AVX2 (the kernel is that arithmetic lane-wise, same widths). fn ab_row( - a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i64, + a_row: &[i32], + b_row: &[i32], + n: i32, + s: i32, + bd_shift: u32, + one_by_x: i64, out: &mut [(i32, i64)], ) { let mut done = 0usize; @@ -1054,7 +1139,12 @@ mod sgr_simd { #[target_feature(enable = "avx2")] #[allow(clippy::too_many_arguments)] pub unsafe fn ab_row_avx2( - a_row: &[i32], b_row: &[i32], n: i32, s: i32, bd_shift: u32, one_by_x: i32, + a_row: &[i32], + b_row: &[i32], + n: i32, + s: i32, + bd_shift: u32, + one_by_x: i32, out: &mut [(i32, i64)], ) -> usize { let len = out.len().min(a_row.len()).min(b_row.len()); @@ -1070,8 +1160,16 @@ mod sgr_simd { let sh_b = _mm_cvtsi32_si128(SGRPROJ_RECIP_BITS as i32); let sh_a = _mm_cvtsi32_si128(2 * bd_shift as i32); let sh_bd = _mm_cvtsi32_si128(bd_shift as i32); - let rnd_a = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (2 * bd_shift - 1) }); - let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 { 0 } else { 1 << (bd_shift - 1) }); + let rnd_a = _mm256_set1_epi32(if bd_shift == 0 { + 0 + } else { + 1 << (2 * bd_shift - 1) + }); + let rnd_bd = _mm256_set1_epi32(if bd_shift == 0 { + 0 + } else { + 1 << (bd_shift - 1) + }); let mut av = [0i32; 8]; let mut bv = [0i32; 8]; let mut gj = 0usize; @@ -1115,7 +1213,11 @@ mod sgr_simd { /// width narrower). #[inline] fn round2_u31(value: i32, shift: u32) -> i32 { - if shift == 0 { value } else { (value + (1 << (shift - 1))) >> shift } + if shift == 0 { + value + } else { + (value + (1 << (shift - 1))) >> shift + } } /// Copies one source row's `out.len()` samples starting at `base_col` into a @@ -1150,7 +1252,8 @@ fn apply_sgrproj_stripe( h_end: usize, v_start: usize, v_end: usize, - info: &SgrprojInfo, fctx: &crate::decode::FrameCtx, + info: &SgrprojInfo, + fctx: &crate::decode::FrameCtx, ) { let w = h_end - h_start; let h = v_end - v_start; @@ -1166,10 +1269,16 @@ fn apply_sgrproj_stripe( (std::mem::take(&mut m.0), std::mem::take(&mut m.1)) }); if r0 > 0 { - compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0, &mut buf0, fctx); + compute_ab( + cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0, + &mut buf0, fctx, + ); } if r1 > 0 { - compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1, &mut buf1, fctx); + compute_ab( + cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1, + &mut buf1, fctx, + ); } let ab0 = (r0 > 0).then_some(&buf0); let ab1 = (r1 > 0).then_some(&buf1); @@ -1185,7 +1294,9 @@ fn apply_sgrproj_stripe( let bytes: Vec = (59..=61) .flat_map(|row| { (5..=7).map(move |col| { - lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col) + lr_sample( + cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col, + ) }) }) .collect(); @@ -1265,7 +1376,8 @@ fn apply_sgrproj_stripe( let (a_ur, b_ur) = ab[idx(i - 1, j + 1)]; let (a_dl, b_dl) = ab[idx(i + 1, j - 1)]; let (a_dr, b_dr) = ab[idx(i + 1, j + 1)]; - 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; + 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; let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3; let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS); v += xq[1] as i64 * (flt1 - u); @@ -1278,9 +1390,15 @@ fn apply_sgrproj_stripe( "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \ ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \ u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}", - ab[idx(i, j)], ab[idx(i - 1, j)], ab[idx(i + 1, j)], ab[idx(i, j - 1)], - ab[idx(i, j + 1)], ab[idx(i - 1, j - 1)], ab[idx(i - 1, j + 1)], - ab[idx(i + 1, j - 1)], ab[idx(i + 1, j + 1)] + ab[idx(i, j)], + ab[idx(i - 1, j)], + ab[idx(i + 1, j)], + ab[idx(i, j - 1)], + ab[idx(i, j + 1)], + ab[idx(i - 1, j - 1)], + ab[idx(i - 1, j + 1)], + ab[idx(i + 1, j - 1)], + ab[idx(i + 1, j + 1)] ); } } @@ -1311,7 +1429,8 @@ fn filter_restoration_unit( v_start: usize, v_end: usize, ss_y: u32, - filter: UnitFilter, fctx: &crate::decode::FrameCtx, + filter: UnitFilter, + fctx: &crate::decode::FrameCtx, ) { let full_stripe_height = 64usize >> ss_y; let runit_offset = 8usize >> ss_y; @@ -1333,10 +1452,32 @@ fn filter_restoration_unit( } match filter { UnitFilter::Wiener(info) => apply_wiener_stripe( - out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx, + out, + cdef, + deblocked, + stride, + plane_w, + plane_h, + h_start, + h_end, + stripe_v_start, + stripe_v_end, + &info, + fctx, ), UnitFilter::Sgrproj(info) => apply_sgrproj_stripe( - out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, fctx, + out, + cdef, + deblocked, + stride, + plane_w, + plane_h, + h_start, + h_end, + stripe_v_start, + stripe_v_end, + &info, + fctx, ), UnitFilter::None => {} } @@ -1395,12 +1536,16 @@ pub(crate) fn apply_loop_restoration_plane( let out = unsafe { so.get() }; for rrow in r_lo..r_hi { lr_unit_row( - out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, - plane, rrow, &rows, fctx, + out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, + rrow, &rows, fctx, ); } }); - debug_assert_eq!(rows.len(), grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units"); + debug_assert_eq!( + rows.len(), + grid.vert_units[plane], + "RU row walk must match RestorationGrid::new's count_units" + ); return; }; for rrow in r_lo..r_hi.min(rows.len()) { @@ -1435,7 +1580,11 @@ pub(crate) fn lr_unit_rows( let mut y0 = 0u32; while y0 < plane_h as u32 { let remaining_h = plane_h as u32 - y0; - let uh = if remaining_h < ext_size { remaining_h } else { unit_size }; + let uh = if remaining_h < ext_size { + remaining_h + } else { + unit_size + }; let v_start = (y0 as i64 - voffset as i64).max(0) as u32; let mut v_end = y0 + uh; if v_end < plane_h as u32 { @@ -1471,7 +1620,11 @@ fn lr_unit_row( let mut rcol = 0usize; while x0 < plane_w as u32 { let remaining_w = plane_w as u32 - x0; - let uw = if remaining_w < ext_size { remaining_w } else { unit_size }; + let uw = if remaining_w < ext_size { + remaining_w + } else { + unit_size + }; let filter = grid.get(plane, rrow, rcol); if filter != UnitFilter::None { filter_restoration_unit( @@ -1486,7 +1639,8 @@ fn lr_unit_row( v_start as usize, v_end as usize, ss_y, - filter, fctx, + filter, + fctx, ); } x0 += uw; @@ -1510,7 +1664,15 @@ mod tests { /// `SGRPROJ_PRJ_MAX-MIN+1`. #[test] fn subexp_roundtrips_every_value() { - for &(num_syms, k) in &[(16u32, 1u32), (32, 2), (64, 3), (96, 4), (128, 4), (3, 1), (1, 3)] { + for &(num_syms, k) in &[ + (16u32, 1u32), + (32, 2), + (64, 3), + (96, 4), + (128, 4), + (3, 1), + (1, 3), + ] { for v in 0..num_syms { let mut enc = SymbolEncoder::new(); write_subexp(&mut enc, num_syms, k, v); @@ -1548,10 +1710,10 @@ mod tests { #[test] fn signed_subexp_with_ref_roundtrips() { let cases: [(i32, i32, u32); 4] = [ - (-5, 11, 1), // Wiener tap0 - (-23, 9, 2), // Wiener tap1 - (-17, 47, 3), // Wiener tap2 - (-96, 32, 4), // SGR xqd0 + (-5, 11, 1), // Wiener tap0 + (-23, 9, 2), // Wiener tap1 + (-17, 47, 3), // Wiener tap2 + (-96, 32, 4), // SGR xqd0 ]; for (low, high, k) in cases { let n = (high - low) as u32; @@ -1563,8 +1725,12 @@ mod tests { write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v); let payload = enc.finish(); let mut dec = SymbolDecoder::new(&payload); - let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v); - assert_eq!(got, v, "low={low} high={high} k={k} reference={reference_v} v={v}"); + let got = + decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v); + assert_eq!( + got, v, + "low={low} high={high} k={k} reference={reference_v} v={v}" + ); } } } @@ -1595,7 +1761,11 @@ mod tests { let mut dec = SymbolDecoder::new(&payload); let mut rref = WienerInfo::default(); for u in &units { - assert_eq!(read_wiener_filter(&mut dec, chroma, &mut rref), *u, "chroma={chroma}"); + assert_eq!( + read_wiener_filter(&mut dec, chroma, &mut rref), + *u, + "chroma={chroma}" + ); } } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 1dcca8c2..e53c9fa9 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -38,6 +38,21 @@ fn no_grain() -> bool { std::env::var_os("EC_AV1_NO_GRAIN").is_some() } +/// lane-av112bit: film grain synthesis has no 12-bit byte-exact witness (the +/// lane's witnesses encode with grain off), so a 12-bit frame that would +/// synthesise grain is refused by name at output rather than trusted -- +/// `film_grain.rs` is bit-depth generic since lane-hbd10, but generic is not +/// proven until a real 12-bit grain stream compares exact. +fn grain_refusal(bit_depth: u32) -> Result<()> { + if bit_depth == 12 { + return Err(Error::unsupported( + "AV1 decode_stream", + "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)", + )); + } + Ok(()) +} + // lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the // current thread, overriding the environment variable. Every ffmpeg/aomdec // pixel gate in this repo compares SHOWN frames only (class @@ -684,6 +699,7 @@ pub fn decode_stream_with_threads( pictures_shown += 1; let grain = header.film_grain; let seq = SeqFlags::read(&parser); + grain_refusal(u32::from(seq.bit_depth))?; let tx = tx.clone(); jobs.submit(move || { let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { @@ -735,6 +751,13 @@ pub fn decode_stream_with_threads( } picture }; + if header.film_grain.apply_grain { + grain_refusal( + parser + .sequence_header() + .map_or(8, |seq| u32::from(seq.color_config.bit_depth)), + )?; + } let output = if header.film_grain.apply_grain && !no_grain() { // lane-hbd10 r1: grain synthesis is bit-depth generic // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). @@ -1074,6 +1097,9 @@ pub fn decode_stream_with_threads( // Grain is synthesised for OUTPUT only: a hidden frame is // reported to the sink clean, exactly as the inline path // below reports it (spec 7.18.3.1). + if header.film_grain.apply_grain { + grain_refusal(u32::from(seq.bit_depth))?; + } let output = if shown && header.film_grain.apply_grain && !no_grain() { std::sync::Arc::new(crate::film_grain::apply_grain( &picture, @@ -1208,6 +1234,9 @@ pub fn decode_stream_with_threads( decode::note_fwd_kf(); } if header.show_frame { + if header.film_grain.apply_grain { + grain_refusal(u32::from(seq.bit_depth))?; + } let output = if header.film_grain.apply_grain && !no_grain() { let mc_identity = seq.mc_identity; std::sync::Arc::new(crate::film_grain::apply_grain( @@ -1634,19 +1663,23 @@ fn decode_frame( // reason as `set_enable_edge_filter` above. Defaults to 8 when no // sequence header has been seen yet, matching every existing fixture. let bit_depth = seq.bit_depth; - // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every - // rounding shift below is written for 8/10-bit only -- `warp.rs`'s - // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses - // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the - // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the - // Wiener rounding bits change, and neither CDEF nor film grain has a - // 12-bit path. Refuse by name rather than decode silently wrong pixels. - if bit_depth == 12 { - return Err(Error::unsupported( - "AV1 decode_stream", - "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)", - )); - } + // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the + // lane's witnesses prove byte-exact against ffmpeg on real `aomenc + // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop + // restoration ON, grain off -- gates + // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and + // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The + // rounding sites that move at 12 bits are parameterised from libaom's + // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange` + // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener + // pair via `get_conv_params_wiener`; the compound post-rounds absorb + // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/ + // superres upscale were already bit-depth generic (10-bit-proven). + // Everything no 12-bit witness reached stays refused BY NAME at its own + // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0), + // film grain (`grain_refusal`, the witnesses run with grain off), and + // any per-feature gap the witnesses' counters prove unreached -- see the + // 12-bit refusals in decode.rs and `refusal_inventory.rs`. // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but @@ -1686,6 +1719,20 @@ fn decode_frame( "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", )); } + // lane-av112bit: the frame-level half of the 12-bit gate -- screen + // content tools. Neither palette nor intrabc has a 12-bit witness (the + // 12-bit gates are natural content), and both hang off this header bit: + // `allow_screen_content_tools` is what lets a block code a palette or + // read a `use_intrabc` symbol. Refusing the FRAME by name keeps every + // palette/intrabc code path 12-bit-unreachable rather than unwitnessed + // and trusted. Gate: + // `a_12bit_screen_content_stream_is_refused_by_name`. + if bit_depth == 12 && header.allow_screen_content_tools { + return Err(Error::unsupported( + "AV1 decode_stream", + "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)", + )); + } // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12) // is a different tile syntax, and this decoder has none of it: libaom // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no @@ -2104,39 +2151,6 @@ pub(crate) mod tests { picture } - /// A stream whose sequence header says `twelve_bit` is refused by name - /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s - /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and - /// film grain). Reachability, not a pixel claim: the header is written at - /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's - /// tile payload is never reached. - #[test] - fn a_twelve_bit_sequence_header_is_refused_by_name() { - let fctx = &crate::decode::FrameCtx::new(); - let picture = test_card(64, 64); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let mut color = ec_av1_syntax::ColorConfig { - bit_depth: 12, - ..Default::default() - }; - color.num_planes = 3; - // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2). - let (mut seq, header) = - crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap(); - seq.seq_profile = 2; - let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap(); - stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap()); - - let err = decode_stream(&stream).unwrap_err().to_string(); - assert!( - err.contains( - "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)" - ), - "expected the 12-bit refusal, got: {err}" - ); - } - /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is /// refused by name, because the decoder reconstructs every chroma extent /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe @@ -7772,6 +7786,376 @@ pub(crate) mod tests { /// actually parses to says `bit_depth == 10` before trusting any pixel /// match -- a stream that silently fell back to 8-bit would still /// "match" trivially. + // ------------------------------------------------------------------- + // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted + // for what these gates witness byte-exact against ffmpeg on real + // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack, + // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop + // restoration (Wiener AND SGR), and translational subpel motion + // compensation through the bit-depth-parameterised `round_0`/`round_1` + // (libaom `convolve.h:81..86`). Everything else stays refused by name: + // warp, film grain, screen content tools (palette/intrabc) at the frame + // level, compound inter blocks at the mode read, each with its own + // real-stream refusal gate below. + // ------------------------------------------------------------------- + + /// The 12-bit witness source, byte-identical to the lane's committed + /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a + /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame + /// vertically with linear edge coverage -- sub-pixel true motion, so an + /// inter frame over it cannot be coded whole-pel-only. + fn y4m_12bit_subpel_source(frames: usize) -> Vec { + const W: usize = 160; + const H: usize = 128; + let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0); + let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes(); + for t in 0..frames { + let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64); + let (bx, by) = (ax + 24.0, ay + 20.0); + y4m.extend_from_slice(b"FRAME\n"); + for j in 0..H as i64 { + for i in 0..W as i64 { + let g = (i * 190) / W as i64 + (j * 150) / H as i64; + let mut v = (g * 12 + + if (i * 5 + j * 3 + t as i64) % 7 < 3 { 90 } else { 220 } + + if (60..110).contains(&i) && (70..110).contains(&j) { 640 } else { 0 }) + as f64; + let c = cov(ax, bx, i) * cov(ay, by, j); + if c > 0.0 { + v = v * (1.0 - c) + 3500.0 * c; + } + y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes()); + } + } + for (base, fx) in [(1900usize, 0usize), (2100, 1)] { + for j in 0..H / 2 { + for i in 0..W / 2 { + let v = if fx == 0 { + base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H) + } else { + base + (((j / 4 + t) % 5) * 140 + (i * 40) / W) + }; + y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes()); + } + } + } + } + y4m + } + + /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so + /// every search runs; explicit CDEF/restoration ON). Warp/global-motion + /// are deliberately NOT spelled here: this aomenc honours the LAST + /// occurrence of these flags (measured), so a base pin plus an override + /// would silently take the base value -- each gate spells what it needs + /// exactly once. + fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec { + let limit = format!("--limit={frames}"); + let mut args: Vec<&str> = vec![ + "--codec=av1", + "--profile=2", + "--passes=1", + "--end-usage=q", + "--cq-level=20", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--kf-max-dist=1000", + "--input-bit-depth=12", + "--bit-depth=12", + "--enable-cdef=1", + "--enable-restoration=1", + "--obu", + "-o", + "-", + "-", + &limit, + ]; + // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence + // of a flag, so the per-arm override goes BEFORE the base list. + args.splice(1..1, extra.iter().copied()); + let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m); + assert!( + out.status.success(), + "aomenc refused the 12-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + } + + /// Asserts the stream's sequence header really says 12-bit before any + /// pixel comparison is trusted. + fn assert_12bit_sequence_header(stream: &[u8], name: &str) { + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + while pos < stream.len() && probe.sequence_header().is_none() { + let obu = probe.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + } + let seq = probe.sequence_header().expect("stream has a sequence header OBU"); + assert_eq!( + seq.color_config.bit_depth, 12, + "{name}: aomenc did not actually write a 12-bit sequence header" + ); + } + + fn ffmpeg_decode_sequence_12bit(stream: &[u8], width: usize, height: usize, frames: usize) -> Vec { + let out = run_with_stdin( + Command::new("ffmpeg").args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", + "yuv420p12le", "-", + ]), + stream, + ); + assert!( + out.status.success(), + "ffmpeg refused the 12-bit stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + let frame_bytes = (luma + 2 * chroma) * 2; + assert_eq!( + out.stdout.len(), + frame_bytes * frames, + "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}", + String::from_utf8_lossy(&out.stderr) + ); + fn le16(bytes: &[u8]) -> Vec { + bytes + .chunks_exact(2) + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .collect() + } + (0..frames) + .map(|i| { + let base = i * frame_bytes; + Pic { + width, + height, + y: le16(&out.stdout[base..base + luma * 2]), + u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]), + v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]), + } + }) + .collect() + } + + /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off. + /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard- + /// assert fired: a CDEF index literal read (bits > 0) and at least one + /// Wiener or SGR restoration unit. Gauntlet for the parameterised + /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF, + /// the 12-bit dequant tables, bd-scaled SGR box sums. + #[test] + fn a_real_aomenc_12bit_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let y4m = y4m_12bit_subpel_source(1); + let stream = encode_12bit( + &y4m, + 1, + &["--enable-warped-motion=0", "--enable-global-motion=0"], + ); + assert_12bit_sequence_header(&stream, NAME); + let before_cdef = decode::cdef_idx_hits(); + let before_lr = + crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(); + let frames = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}")); + assert_eq!(frames.len(), 1); + assert!( + decode::cdef_idx_hits() > before_cdef, + "{NAME}: no CDEF index literal was read -- CDEF is not exercised" + ); + assert!( + crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr, + "{NAME}: no loop restoration unit was decoded -- LR is not exercised" + ); + let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (12-bit key)"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)"); + } + + /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel + /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass + /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own + /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs + /// parameterisation -- really executed, and asserts + /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent + /// second reference, which is exactly why compound stays refused). + #[test] + fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let y4m = y4m_12bit_subpel_source(2); + let stream = encode_12bit( + &y4m, + 2, + &["--enable-warped-motion=0", "--enable-global-motion=0"], + ); + assert_12bit_sequence_header(&stream, NAME); + let before_subpel = crate::mc::mc_subpel_hits(); + let before_compound = decode::compound_mode_hits(); + let frames = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}")); + assert_eq!(frames.len(), 2); + assert!( + crate::mc::mc_subpel_hits() > before_subpel, + "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised" + ); + assert_eq!( + decode::compound_mode_hits(), + before_compound, + "{NAME}: a compound mode symbol was read -- the single-reference premise is gone" + ); + let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2); + for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(ours.y, reference.y, "frame {i} luma vs ffmpeg (12-bit inter)"); + assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)"); + assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)"); + } + } + + /// The 12-bit warp refusal, exercised on a REAL stream: the same source + /// and recipe with the warp tools ON -- aomenc picks a global warp model + /// on this content (measured: the decode refuses at the first warped + /// block) -- is refused by name. + #[test] + fn a_12bit_warped_motion_stream_is_refused_by_name() { + const NAME: &str = "a_12bit_warped_motion_stream_is_refused_by_name"; + let _gate_lock = lock_gate_counters(); + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let y4m = y4m_12bit_subpel_source(6); + // Exactly the recipe measured to refuse at warp: warp ON, global + // motion NOT spelled (spelling it ON makes a GLOBAL_GLOBALMV + // compound block reach the compound refusal first), six frames -- + // the warp model fires at the third frame. + let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]); + let err = decode_stream(&stream).unwrap_err().to_string(); + assert!( + err.contains( + "warped motion at 12 bits (warp's reduce bits inherit the 12-bit round_0 and no 12-bit warp witness exists)" + ), + "{NAME}: expected the 12-bit warp refusal, got: {err}" + ); + } + + /// The 12-bit compound refusal, exercised on a REAL stream: six frames + /// with `--lag-in-frames=0` still diverge LAST from GOLDEN from frame 2 + /// on (measured: aomenc codes compound blocks and the decode refuses at + /// the compound mode read). + #[test] + fn a_12bit_compound_inter_stream_is_refused_by_name() { + const NAME: &str = "a_12bit_compound_inter_stream_is_refused_by_name"; + let _gate_lock = lock_gate_counters(); + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let y4m = y4m_12bit_subpel_source(6); + // Warp pinned OFF so the COMPOUND refusal is the one that can fire: + // with six frames, LAST diverges from GOLDEN from frame 2 on and + // aomenc codes compound blocks (measured). + let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=0"]); + let err = decode_stream(&stream).unwrap_err().to_string(); + assert!( + err.contains( + "a compound inter block at 12 bits (no 12-bit compound witness exists: the 12-bit inter gate is a single-reference stream)" + ), + "{NAME}: expected the 12-bit compound refusal, got: {err}" + ); + } + + /// The 12-bit film grain refusal: a real `--film-grain-test=1` stream + /// (grain params present AND applied) is refused by name at output. + #[test] + fn a_12bit_film_grain_stream_is_refused_by_name() { + const NAME: &str = "a_12bit_film_grain_stream_is_refused_by_name"; + let _gate_lock = lock_gate_counters(); + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let y4m = y4m_12bit_subpel_source(1); + let stream = encode_12bit(&y4m, 1, &["--film-grain-test=1"]); + let err = decode_stream(&stream).unwrap_err().to_string(); + assert!( + err.contains( + "film grain synthesis at 12 bits (no byte-exact 12-bit grain witness exists: the 12-bit gates encode with grain off)" + ), + "{NAME}: expected the 12-bit grain refusal, got: {err}" + ); + } + + /// The 12-bit screen-content refusal: a real `--tune-content=screen + /// --enable-palette=1 --enable-intrabc=1` frame carries + /// `allow_screen_content_tools = 1` and is refused by name at the frame + /// gate -- palette and intrabc have no 12-bit witness. + #[test] + fn a_12bit_screen_content_stream_is_refused_by_name() { + const NAME: &str = "a_12bit_screen_content_stream_is_refused_by_name"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", "smptebars=s=128x128:r=25", + "-pix_fmt", "yuv420p12le", "-strict", "-1", "-frames:v", "2", + "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg failed to render the 12-bit screen fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let stream = encode_12bit( + &y4m.stdout, + 1, + &["--tune-content=screen", "--enable-palette=1", "--enable-intrabc=1"], + ); + let err = decode_stream(&stream).unwrap_err().to_string(); + assert!( + err.contains( + "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)" + ), + "{NAME}: expected the 12-bit screen content refusal, got: {err}" + ); + } + #[test] fn a_real_aomenc_10bit_stream_decodes_pixel_exact() { const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact"; diff --git a/lanes/av112bit.report.md b/lanes/av112bit.report.md new file mode 100644 index 00000000..6561be3f --- /dev/null +++ b/lanes/av112bit.report.md @@ -0,0 +1,143 @@ +# lane-av112bit — the 12-bit decode gate + +Base 73f3ac64, worktree `edith_codecs-av112b`. The charter: lift the blanket +`bit_depth == 12` refusal in `stream.rs` (`lanes/av1hdr.report.md` §4.2 named +the sites) exactly as far as real `aomenc --bit-depth=12` witnesses prove +byte-exactness against ffmpeg, and keep every unwitnessed 12-bit path refused +by name. + +## The libaom rule (what actually moves at 12 bits) + +`av1/common/convolve.h:68..100` (`get_conv_params_no_round`) and +`:107..118` (`get_conv_params_wiener`): + +```c +const int intbufrange = bd + FILTER_BITS - round_0 + 2; +if (intbufrange > 16) { round_0 += intbufrange - 16; if (!is_compound) round_1 -= intbufrange - 16; } +``` + +i.e. `delta = bd - 10` (zero at 8/10-bit; 2 at 12-bit). Horizontal `round_0` +3 -> 5; non-compound vertical `round_1` 11 -> 9 (product, the filter gain, +unchanged); compound `round_1` stays 7, so the CONV_BUF gain drops from 16x +to 4x and every combine round absorbs the delta. Warp inherits the same +`round_0` (`warped_motion.c:295`, with the assert at `:310` pinning +`bd + FILTER_BITS + 2 - round_0 <= 16`) — §4.2's "`round_0 + max(...)` (5 at +bd 12)" and the retracted-reviewer note stand, expressed through the conv +params. + +## What changed (witnessed paths, lifted) + +- **`mc.rs`** — `round_delta`/`round_pair` implement the convolve.h rule. + The shift is threaded through `hpass_row`/`hpass_contig`/`hpass_rows`/ + `hpass_avx2`/`hpass_sse2`, `vpass_row_u16` + AVX2/SSE4.1 kernels and + scalars (the `srai` immediates became vector-count `sra`), the identity-tap + fast paths (`gain = 128 >> round_0`, `t * (128 >> round_0)`, + `round2(a, round_1 - 7)`), `horizontal_scaled_pass`, and + `predict_compound_intermediate_kern` (which now takes `fctx`). The compound + combines absorb the CONV_BUF gain drop: + `combine_compound`/`blend_masked_compound` round by + `INTER_POST_ROUND - delta`, `diffwtd_mask` by + `INTER_POST_ROUND + (bd - 8) - delta` (the `reconinter.c:307` formula). + `horizontal_intermediate_fits_i16` now pins the 12-bit bound + (`round2(348 * 4095, 5) = 27976 < 2^15`); the SIMD tests already spanned + 12-bit intermediates. +- **`restoration.rs`** — the Wiener stripe runs its horizontal pass at the + frame's `round_0` and vertical at `round_1` (9 at 12-bit). SGR needed + nothing: `compute_ab`/`ab_point` were already `bd_shift = bd - 8` + parameterised (the lane-hbdinter fix), and the oracle's + `calculate_intermediate_result` matches it exactly. +- Everything else 12-bit-relevant was already bit-depth generic and + 10-bit-proven: the 12-bit dequant tables (`quant.rs`), deblock + (`sclamp`/threshold `<< bd - 8`), CDEF (`coeff_shift = bd - 8`, + `damping += coeff_shift`, exactly `av1_cdef_filter_fb`), film grain + (`grain_center`/`scale_lut`/LUT expansion, lane-hbd10), superres upscale + clamp, palette colour reads, `sample_max` clamps. + +## What stayed refused (unwitnessed, by name — real-stream gates) + +| refusal | site | gate (real aomenc stream) | +|---|---|---| +| `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` | +| `a compound inter block at 12 bits ...` | both leaves' `read_inter_compound_mode` callers | `a_12bit_compound_inter_stream_is_refused_by_name` | +| `film grain synthesis at 12 bits ...` | all four `apply_grain` output sites (`grain_refusal`) | `a_12bit_film_grain_stream_is_refused_by_name` | +| `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` | + +The screen-content gate covers palette **and** intrabc with one honest frame +level refusal: both hang off `allow_screen_content_tools`, neither has a +12-bit witness, and refusing the frame keeps both code paths 12-bit +unreachable instead of unwitnessed-and-trusted. + +OBMC, interintra, palette reads, intrabc copies and superres-scaled MC are +NOT separately gated: their arithmetic is bit-depth independent and their +bd-sensitive inputs (MC predictions, samples) are witnessed at 12 bits — +the composition of two proven pieces. The scaled-MC walk shares the exact +parameterised round path; the 10-bit superres gate pins the walk itself. + +## The witnesses + +Source (Rust `y4m_12bit_subpel_source`, byte-identical to the manual +generator): 160x128 C420p12, gradient + fine texture, a 24x20 box travelling +1.25 px/frame horizontally and 0.75 px/frame vertically with linear edge +coverage — sub-pixel true motion, so the inter frame cannot be coded +whole-pel-only (proven: `MC_SUBPEL_HITS > 0`, a new counter). + +Recipe (both witnesses): `aomenc --codec=av1 --profile=2 --bit-depth=12 +--input-bit-depth=12 --passes=1 --end-usage=q --cq-level=20 --cpu-used=0 +--threads=1 --row-mt=0 --sb-size=64 --lag-in-frames=0 --auto-alt-ref=0 +--kf-max-dist=1000 --enable-cdef=1 --enable-restoration=1 +--enable-warped-motion=0 --enable-global-motion=0 --obu --limit=`, +N=1 (key) / N=2 (key + one P frame). + +- `crates/ec-av1/fixtures/av112bit-key.obu` — 923 bytes, + sha256 `c74f62b57f71f7c36c49ea1feeb482786a2650e5c7f66610949b5f65fbbed8d1` +- `crates/ec-av1/fixtures/av112bit-inter.obu` — 4533 bytes, + sha256 `e679d577e61b4a8bc99685355cca8c0473cfb637284b07786a6c53b1755553d9` + +Encoder: the local aom oracle build (`~/.cache/aom-oracle/build/aomenc`, +libaom src `92d4c37fbdd08944a0e721bbaeb13318f10aebb0`); reference decode +ffmpeg 8.1.2 (`yuv420p12le` rawvideo). The gates encode live from the +in-test generator and pixel-compare every plane of every frame against +ffmpeg's decode of the identical bytes; the committed fixtures are the same +recipe's output for provenance (the inter fixture byte-equals the manual +lane run, `cmp` clean). + +Gate asserts beyond the pixel match, so none can pass vacuously: +key — `cdef_idx_hits > 0` (CDEF index literals read) and Wiener+SGR unit +count advanced; inter — `MC_SUBPEL_HITS > 0` (the parameterised round pair +actually ran) and `compound_mode_hits` UNCHANGED (the single-reference +premise the compound refusal leans on). + +## Results + +- 12-bit battery (6 gates) green; the two witnesses byte-exact vs ffmpeg. +- 10-bit regression: `a_real_aomenc_10bit_stream_decodes_pixel_exact`, + `a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact`, + `a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact`, and the three + film fixture gates (`a_10bit_128sb_film_frames_with_warp_cdef_and_interintra...`, + `a_10bit_film_frames_with_rect64_corner_tus...`, + `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_reach...`) all + green — the two charter-named film gates included. +- 8-bit spot regression (monochrome, lossless, real-aomenc arms) green. +- `refusal_inventory` + `gate_coverage` tests green (inventory diff = the + capability delta above). + +## Open halves (recorded, not silently dropped) + +1. **Wiener intermediate clamp at 12 bits.** A first attempt replaced the + corpus-proven constant clamp with the C clamp's exact per-sample + transform (add_src bias surviving `Round2(_, round_0)`) — it MOVED + `a_10bit_128sb_film_frames...` frame 1 luma: libaom's 8-tap-loop + pointer-alignment trick means the C horizontal intermediate is not + `ours + bias` wherever the clamp actually binds, so the exact transform + is not derivable from the convolve source alone. The shipped code keeps + the 8/10-bit-proven constant structure (`[-2^(bd+3), 2^(bd+5)-1-2^(bd+3)]`, + i16-safe; at 12-bit the widest i16 window, which strictly contains the + kernel's mathematical range and so never binds — the same property the + 8/10-bit bounds have on the proven corpus). The 12-bit key witness is + byte-exact with it; a stream whose intermediates would trip C's real + clamp is unproven either way. Disposition: `accepted` (deferred to a + lane that instruments the oracle's wiener path directly). +2. **Compound, warp, grain, palette, intrabc at 12 bits** — refused by name + with real-stream gates; lifting each needs its own byte-exact witness + (compound of every kind, warp at the 12-bit `round_0`, grain synthesis, + screen content).