forge
Explore
Log in

Don't you dare go Hollow

Merge main (937fb4a1) into lane-av1ibc

Browse files at this commit

b42af30be70e48ec8ad1c40b2728f33a6b00372cAhmet Kaan GümüşParent: ffa03f8c759b78
crates/ec-av1/src/encode.rsmodified+321 -106
@@ -190,6 +190,21 @@ fn extra_new_skip_margin() -> f64 {
190 }190 }
191 }191 }
192 192
193+/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
194+/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
195+/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
196+/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
197+/// was missing was the encoder ever forming one below 32x32.
198+const LEAF_COMPOUND: bool = true;
199+
200+/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
201+fn leaf_compound() -> bool {
202+ match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
203+ Some(v) => v != "0",
204+ None => LEAF_COMPOUND,
205+ }
206+}
207+
193 /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.208 /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
194 fn leaf_new_mv() -> bool {209 fn leaf_new_mv() -> bool {
195 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {210 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
@@ -3248,7 +3263,12 @@ fn code_square_inter(
3248 search: &Search,3263 search: &Search,
3249 mode_bits: &[f64; 13],3264 mode_bits: &[f64; 13],
3250 reference: &Picture,3265 reference: &Picture,
3251- stack: &MvStack, fctx: &crate::decode::FrameCtx,3266+ stack: &MvStack,
3267+ // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
3268+ // leaf's own `bw4`/`bh4` (empty on a frame that does not code
3269+ // `reference_select`, and at the straddling call sites).
3270+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3271+ fctx: &crate::decode::FrameCtx,
3252 ) -> (BlockCoeffs, f64) {3272 ) -> (BlockCoeffs, f64) {
3253 let (intra_block, intra_cost) =3273 let (intra_block, intra_cost) =
3254 code_square(3274 code_square(
@@ -3386,7 +3406,12 @@ fn code_square_inter(
3386 // not code the movement it split for. Same candidate `search_inter_block`3406 // not code the movement it split for. Same candidate `search_inter_block`
3387 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to3407 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
3388 // a vector the residual syntax can name -- at this leaf's own side.3408 // a vector the residual syntax can name -- at this leaf's own side.
3389- let mut best = (inter_cost, None);3409+ let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
3410+ // This leaf's own `NEWMV` vector, kept whether or not it won the
3411+ // single-reference comparison: it seeds the compound half-new candidate
3412+ // below, exactly as `search_inter_block` seeds its own from the searches
3413+ // it already ran.
3414+ let mut searched_new: Option<(i32, i32)> = None;
3390 if leaf_new_mv() {3415 if leaf_new_mv() {
3391 let source_block = luma.source_block(x, y, side);3416 let source_block = luma.source_block(x, y, side);
3392 let (seeds, seed_n) = mv_seeds(stack);3417 let (seeds, seed_n) = mv_seeds(stack);
@@ -3407,6 +3432,7 @@ fn code_square_inter(
3407 );3432 );
3408 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);3433 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
3409 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {3434 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
3435+ searched_new = Some(new_mv);
3410 // Same reuse as `search_inter_block`: a NEWMV equal to the3436 // Same reuse as `search_inter_block`: a NEWMV equal to the
3411 // stack's NEARESTMV is the same three trials, already run above.3437 // stack's NEARESTMV is the same three trials, already run above.
3412 let (luma_new, u_new, v_new) = if new_mv == mv {3438 let (luma_new, u_new, v_new) = if new_mv == mv {
@@ -3453,15 +3479,170 @@ fn code_square_inter(
3453 luma_new.bits + u_new.bits + v_new.bits3479 luma_new.bits + u_new.bits + v_new.bits
3454 });3480 });
3455 if cost_new < best.0 {3481 if cost_new < best.0 {
3456- best = (cost_new, Some((luma_new, u_new, v_new, skip_new, new_mv)));3482+ best = (
3483+ cost_new,
3484+ Some((
3485+ luma_new,
3486+ u_new,
3487+ v_new,
3488+ skip_new,
3489+ InterInfo {
3490+ ref1: None,
3491+ mv1: (0, 0),
3492+ ref_frame: crate::mvstack::LAST_FRAME,
3493+ mode: InterMode::NewMv,
3494+ mv: new_mv,
3495+ ref_mv_idx: 0,
3496+ },
3497+ )),
3498+ );
3457 }3499 }
3458 }3500 }
3459 }3501 }
3460- if let (cost, Some((luma_new, u_new, v_new, skip_new, new_mv))) = best {3502+
3461- if cost < intra_cost {3503+ // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
3462- let (levels, tx_depth, dcost) = commit_inter_luma(3504+ // `search_inter_block` prices for a whole 32x32 block minus the two that
3463- luma, (x, y), side, new_mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_new, skip_new, fctx,3505+ // need a motion search against the SECOND reference: a leaf never runs
3506+ // one (`NEAREST_NEWMV`/`NEW_NEWMV` would each cost another
3507+ // `motion::search` per extra reference per leaf), so the set here is
3508+ // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` off the
3509+ // vector this leaf already searched. Priced with the same static-CDF
3510+ // approximation, plus the compound-only syntax the writer emits.
3511+ for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
3512+ let (ref1, g) = (*ref1, *g);
3513+ let uni =
3514+ (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
3515+ let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
3516+ + if uni {
3517+ symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
3518+ + symbol_bits(&cdf::COMP_REF[0][0], 0)
3519+ + symbol_bits(&cdf::COMP_REF[0][1], 0)
3520+ + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
3521+ } else {
3522+ symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
3523+ + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
3524+ + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
3525+ + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
3526+ };
3527+ let mode_ctx =
3528+ cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
3529+ let mode_bits_of =
3530+ |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
3531+ let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
3532+ (
3533+ cstack.nearest_mv,
3534+ mode_bits_of(0),
3535+ InterInfo {
3536+ ref_frame: crate::mvstack::LAST_FRAME,
3537+ mode: InterMode::NearestNearestMv,
3538+ mv: cstack.nearest_mv.0,
3539+ mv1: cstack.nearest_mv.1,
3540+ ref1: Some(ref1),
3541+ ref_mv_idx: 0,
3542+ },
3543+ ),
3544+ (
3545+ ((0, 0), (0, 0)),
3546+ mode_bits_of(6),
3547+ InterInfo {
3548+ ref_frame: crate::mvstack::LAST_FRAME,
3549+ mode: InterMode::GlobalGlobalMv,
3550+ mv: (0, 0),
3551+ mv1: (0, 0),
3552+ ref1: Some(ref1),
3553+ ref_mv_idx: 0,
3554+ },
3555+ ),
3556+ ];
3557+ // `NEW_NEARESTMV`: the NEW half is this leaf's own searched vector,
3558+ // its residual priced against compound stack entry 0 (what
3559+ // `assign_compound_mv` predicts from at `ref_mv_idx = 0`).
3560+ let cbase = cstack
3561+ .entries
3562+ .first()
3563+ .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
3564+ if let Some(new_mv) = searched_new {
3565+ if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
3566+ ccands.push((
3567+ (new_mv, cstack.nearest_mv.1),
3568+ mode_bits_of(3) + b0,
3569+ InterInfo {
3570+ ref_frame: crate::mvstack::LAST_FRAME,
3571+ mode: InterMode::NewNearestMv,
3572+ mv: new_mv,
3573+ mv1: cstack.nearest_mv.1,
3574+ ref1: Some(ref1),
3575+ ref_mv_idx: 0,
3576+ },
3577+ ));
3578+ }
3579+ }
3580+ ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
3581+ ccands.dedup_by_key(|c| c.0);
3582+ let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
3583+ let g_u = (
3584+ g.u.as_slice(),
3585+ g.width / 2,
3586+ chroma[0].true_width,
3587+ chroma[0].true_height,
3588+ );
3589+ let g_v = (
3590+ g.v.as_slice(),
3591+ g.width / 2,
3592+ chroma[1].true_width,
3593+ chroma[1].true_height,
3594+ );
3595+ for (mvs, bits, info) in ccands {
3596+ let luma_c = mc_trial_compound(
3597+ luma, x, y, side, mvs, true,
3598+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
3599+ search.base_q_idx, search.deadzone, luma_set, fctx,
3600+ );
3601+ let u_c = mc_trial_compound(
3602+ &chroma[0], x / 2, y / 2, side / 2, mvs, false,
3603+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
3604+ search.base_q_idx, search.deadzone, chroma_set, fctx,
3464 );3605 );
3606+ let v_c = mc_trial_compound(
3607+ &chroma[1], x / 2, y / 2, side / 2, mvs, false,
3608+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
3609+ search.base_q_idx, search.deadzone, chroma_set, fctx,
3610+ );
3611+ let skip_c = luma_c.levels.iter().all(|&l| l == 0)
3612+ && u_c.levels.iter().all(|&l| l == 0)
3613+ && v_c.levels.iter().all(|&l| l == 0);
3614+ let cost_c = luma_c.sse
3615+ + u_c.sse
3616+ + v_c.sse
3617+ + search.lambda
3618+ * (skip_bits(skip_c)
3619+ + intra_inter_bits(true)
3620+ + bits
3621+ + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
3622+ if cost_c < best.0 {
3623+ best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
3624+ }
3625+ }
3626+ }
3627+
3628+ if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
3629+ if cost < intra_cost {
3630+ // A compound winner commits the flat trial it was priced from:
3631+ // `commit_inter_luma`'s var-tx trial set is single-reference
3632+ // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3633+ // corner-cut: no var-tx split for a compound leaf -- ceiling is
3634+ // the split gain on 16x16 compound blocks; upgrade path is a
3635+ // compound `commit_inter_luma` taking both references.
3636+ let (levels, tx_depth, dcost) = if info.ref1.is_some() {
3637+ luma.commit(x, y, side, &luma_new);
3638+ (luma_new.levels.clone(), 0, 0.0)
3639+ } else {
3640+ commit_inter_luma(
3641+ luma, (x, y), side, info.mv,
3642+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3643+ search, &luma_new, skip_new, fctx,
3644+ )
3645+ };
3465 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);3646 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
3466 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);3647 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
3467 return (3648 return (
@@ -3477,14 +3658,7 @@ fn code_square_inter(
3477 palette: None,3658 palette: None,
3478 palette_uv: None,3659 palette_uv: None,
3479 tx_depth,3660 tx_depth,
3480- inter: Some(InterInfo {3661+ inter: Some(info),
3481- ref1: None,
3482- mv1: (0, 0),
3483- ref_frame: crate::mvstack::LAST_FRAME,
3484- mode: InterMode::NewMv,
3485- mv: new_mv,
3486- ref_mv_idx: 0,
3487- }),
3488 },3662 },
3489 cost + dcost,3663 cost + dcost,
3490 );3664 );
@@ -6286,6 +6460,30 @@ pub(crate) fn encode_inter_frame(
6286 let stack = find_mv_stack(6460 let stack = find_mv_stack(
6287 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,6461 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
6288 );6462 );
6463+ let cstacks: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6464+ if header.reference_select && leaf_compound() {
6465+ [
6466+ (crate::mvstack::GOLDEN_FRAME, golden),
6467+ (crate::mvstack::ALTREF_FRAME, altref),
6468+ ]
6469+ .into_iter()
6470+ .filter_map(|(r, pic)| {
6471+ pic.map(|p| {
6472+ (
6473+ r,
6474+ p,
6475+ crate::mvstack::find_mv_stack_compound(
6476+ &grid, mi_row, mi_col, 4, 4,
6477+ (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6478+ grid.sign_bias_table(), &[(0, 0); 7], None,
6479+ ),
6480+ )
6481+ })
6482+ })
6483+ .collect()
6484+ } else {
6485+ Vec::new()
6486+ };
6289 let (leaf, leaf_cost) = code_square_inter(6487 let (leaf, leaf_cost) = code_square_inter(
6290 &mut luma,6488 &mut luma,
6291 &mut chroma,6489 &mut chroma,
@@ -6294,7 +6492,7 @@ pub(crate) fn encode_inter_frame(
6294 &search,6492 &search,
6295 &mode_bits_table,6493 &mode_bits_table,
6296 reference,6494 reference,
6297- &stack, fctx,6495+ &stack, &cstacks, fctx,
6298 );6496 );
6299 let leaf_cost = leaf_cost6497 let leaf_cost = leaf_cost
6300 + search.lambda * partition_bits(SUB, false);6498 + search.lambda * partition_bits(SUB, false);
@@ -6323,6 +6521,30 @@ pub(crate) fn encode_inter_frame(
6323 let stack8 = find_mv_stack(6521 let stack8 = find_mv_stack(
6324 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,6522 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
6325 );6523 );
6524+ let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6525+ if header.reference_select && leaf_compound() {
6526+ [
6527+ (crate::mvstack::GOLDEN_FRAME, golden),
6528+ (crate::mvstack::ALTREF_FRAME, altref),
6529+ ]
6530+ .into_iter()
6531+ .filter_map(|(r, pic)| {
6532+ pic.map(|p| {
6533+ (
6534+ r,
6535+ p,
6536+ crate::mvstack::find_mv_stack_compound(
6537+ &grid, mr, mc, 2, 2,
6538+ (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6539+ grid.sign_bias_table(), &[(0, 0); 7], None,
6540+ ),
6541+ )
6542+ })
6543+ })
6544+ .collect()
6545+ } else {
6546+ Vec::new()
6547+ };
6326 let (leaf8, cost) = code_square_inter(6548 let (leaf8, cost) = code_square_inter(
6327 &mut luma,6549 &mut luma,
6328 &mut chroma,6550 &mut chroma,
@@ -6331,7 +6553,7 @@ pub(crate) fn encode_inter_frame(
6331 &search,6553 &search,
6332 &mode_bits_table,6554 &mode_bits_table,
6333 reference,6555 reference,
6334- &stack8, fctx,6556+ &stack8, &cstacks8, fctx,
6335 );6557 );
6336 cost8 += cost;6558 cost8 += cost;
6337 record_mi(&mut grid, mr, mc, 2, leaf8.inter);6559 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
@@ -6432,42 +6654,15 @@ pub(crate) fn encode_inter_frame(
6432 &search,6654 &search,
6433 &mode_bits_table,6655 &mode_bits_table,
6434 reference,6656 reference,
6435- &stack, fctx,6657+ &stack, &[], fctx,
6436 );6658 );
6437- for dr in 0..4 {6659+ // One publication point for every coded leaf
6438- for dc in 0..4 {6660+ // (`record_mi`): this site used to spell the vote
6439- grid.set(6661+ // out with `ref_frame` pinned to LAST and `mv1`
6440- mi_row + dr,6662+ // to (0,0), which is the encoder-grid-drift class
6441- mi_col + dc,6663+ // -- correct only for as long as a leaf can never
6442- match block.inter {6664+ // be compound.
6443- Some(info) => MiInfo {6665+ record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
6444- is_inter: true,
6445- ref_frame: LAST_FRAME,
6446- ref_frame1: NO_REF1,
6447- mv1: (0, 0),
6448- mv: mv16(info.mv),
6449- is_new_mv: matches!(info.mode, InterMode::NewMv),
6450- size: 4,
6451- size_h: 4,
6452- is_global_mv0: false,
6453- is_global_mv1: false,
6454- },
6455- None => MiInfo {
6456- is_inter: false,
6457- ref_frame: -1,
6458- ref_frame1: NO_REF1,
6459- mv1: (0, 0),
6460- mv: (0, 0),
6461- is_new_mv: false,
6462- size: 4,
6463- size_h: 4,
6464- is_global_mv0: false,
6465- is_global_mv1: false,
6466- },
6467- },
6468- );
6469- }
6470- }
6471 leaves.push(block);6666 leaves.push(block);
6472 } else {6667 } else {
6473 let (x_sub, y_sub) = (sc * SUB, sr * SUB);6668 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
@@ -6492,45 +6687,11 @@ pub(crate) fn encode_inter_frame(
6492 &search,6687 &search,
6493 &mode_bits_table,6688 &mode_bits_table,
6494 reference,6689 reference,
6495- &stack, fctx,6690+ &stack, &[], fctx,
6496 );6691 );
6497- for dr in 0..2 {6692+ // Same publication point as the 16x16
6498- for dc in 0..2 {6693+ // straddling leaf above (`record_mi`).
6499- grid.set(6694+ record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
6500- mi_row + dr,
6501- mi_col + dc,
6502- match leaf.inter {
6503- Some(info) => MiInfo {
6504- is_inter: true,
6505- ref_frame: LAST_FRAME,
6506- ref_frame1: NO_REF1,
6507- mv1: (0, 0),
6508- mv: mv16(info.mv),
6509- is_new_mv: matches!(
6510- info.mode,
6511- InterMode::NewMv
6512- ),
6513- size: 2,
6514- size_h: 2,
6515- is_global_mv0: false,
6516- is_global_mv1: false,
6517- },
6518- None => MiInfo {
6519- is_inter: false,
6520- ref_frame: -1,
6521- ref_frame1: NO_REF1,
6522- mv1: (0, 0),
6523- mv: (0, 0),
6524- is_new_mv: false,
6525- size: 2,
6526- size_h: 2,
6527- is_global_mv0: false,
6528- is_global_mv1: false,
6529- },
6530- },
6531- );
6532- }
6533- }
6534 eight.push(leaf);6695 eight.push(leaf);
6535 }6696 }
6536 leaves.push(BlockCoeffs {6697 leaves.push(BlockCoeffs {
@@ -9775,11 +9936,32 @@ mod tests {
9775 (ladder, wall)9936 (ladder, wall)
9776 }9937 }
9777 9938
9939+ /// First differing sample between two pictures, as
9940+ /// `(plane, index, left, right)` -- so a gate failure names the plane and
9941+ /// the sample instead of just "differs". A length difference counts as a
9942+ /// mismatch of that plane at the first index past the shorter one.
9943+ fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
9944+ for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
9945+ if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
9946+ return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
9947+ }
9948+ if l.len() != r.len() {
9949+ return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
9950+ }
9951+ }
9952+ None
9953+ }
9954+
9778 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR9955 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
9779- /// comes from ffmpeg's decode of our own stream, and every frame of that9956+ /// comes from ffmpeg's decode of our own stream, and at EVERY point the
9780- /// decode is asserted sample-exact against our reconstruction -- which is9957+ /// stream is decoded twice -- by ffmpeg and by our own
9781- /// itself a gate: it proves the bitstream says what the encoder thinks.9958+ /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
9959+ /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
9960+ /// in Y, U and V over every shown frame in display order. That is itself
9961+ /// a gate: it proves the bitstream says what the encoder thinks, in the
9962+ /// only two decoders that read it.
9782 fn our_ladder(9963 fn our_ladder(
9964+ name: &str,
9783 source: &[Picture],9965 source: &[Picture],
9784 width: usize,9966 width: usize,
9785 height: usize,9967 height: usize,
@@ -9792,13 +9974,27 @@ mod tests {
9792 let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();9974 let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();
9793 wall += start.elapsed().as_secs_f64();9975 wall += start.elapsed().as_secs_f64();
9794 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());9976 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
9977+ let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
9978+ assert_eq!(
9979+ ours.len(),
9980+ source.len(),
9981+ "{name} q={q}: our decoder's display-order frame count"
9982+ );
9795 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {9983 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
9796- assert!(9984+ if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
9797- d.y == e.reconstruction.y9985+ panic!(
9798- && d.u == e.reconstruction.u9986+ "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
9799- && d.v == e.reconstruction.v,9987+ {got}, the encoder reconstructed {want}"
9800- "q={q} frame {i}: ffmpeg's decode differs from our reconstruction"9988+ );
9801- );9989+ }
9990+ }
9991+ for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
9992+ if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
9993+ panic!(
9994+ "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
9995+ {got}, the encoder reconstructed {want}"
9996+ );
9997+ }
9802 }9998 }
9803 let mean: f64 = decoded9999 let mean: f64 = decoded
9804 .iter()10000 .iter()
@@ -9835,6 +10031,7 @@ mod tests {
9835 /// the ladder, the wall, and — per pyramid level over the whole ladder —10031 /// the ladder, the wall, and — per pyramid level over the whole ladder —
9836 /// how many frames and how many bytes it spent.10032 /// how many frames and how many bytes it spent.
9837 fn our_ladder_pyramid(10033 fn our_ladder_pyramid(
10034+ name: &str,
9838 source: &[Picture],10035 source: &[Picture],
9839 width: usize,10036 width: usize,
9840 height: usize,10037 height: usize,
@@ -9879,10 +10076,15 @@ mod tests {
9879 // source picture, in the right order -- checked against our own10076 // source picture, in the right order -- checked against our own
9880 // decoder as well as ffmpeg's, both below.10077 // decoder as well as ffmpeg's, both below.
9881 let ours = crate::stream::decode_stream(&stream).expect("our decoder");10078 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
9882- assert_eq!(ours.len(), source.len(), "q={q}: our display-order count");10079+ assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
9883 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());10080 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
9884 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {10081 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
9885- assert!(d.y == o.y, "q={q} display frame {i}: ffmpeg differs from our decoder");10082+ if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
10083+ panic!(
10084+ "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
10085+ decoded {got}, our decoder decoded {want}"
10086+ );
10087+ }
9886 }10088 }
9887 let mean: f64 = decoded10089 let mean: f64 = decoded
9888 .iter()10090 .iter()
@@ -9927,7 +10129,7 @@ mod tests {
9927 })10129 })
9928 };10130 };
9929 let pins: [(u8, usize, u64); 2] =10131 let pins: [(u8, usize, u64); 2] =
9930- [(150, 7103, 0xb9b7_763b_6f18_a887), (60, 26778, 0x4071_f16e_1e5d_87c3)];10132+ [(150, 7084, 0xe6a9_2f62_3855_0eee), (60, 26116, 0xa831_9866_b799_80fc)];
9931 for (q, bytes, hash) in pins {10133 for (q, bytes, hash) in pins {
9932 let encoded = encode_sequence(&source, q, 0.5).unwrap();10134 let encoded = encode_sequence(&source, q, 0.5).unwrap();
9933 assert_eq!(10135 assert_eq!(
@@ -10081,8 +10283,15 @@ mod tests {
10081 /// search's own cost, uncut: see the two intra-pruning variants measured10283 /// search's own cost, uncut: see the two intra-pruning variants measured
10082 /// and rejected in the lane report). No10284 /// and rejected in the lane report). No
10083 /// threshold is asserted yet -- this run sets the baseline; the gate10285 /// threshold is asserted yet -- this run sets the baseline; the gate
10084- /// asserts only four monotone points per ladder and that ffmpeg decodes10286+ /// asserts four monotone points per ladder, and at EVERY ladder point of
10085- /// our stream sample-exact against our reconstruction.10287+ /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
10288+ /// `crate::stream::decode_stream` -- and asserts the encoder's
10289+ /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
10290+ /// and V over every shown frame in display order. A failure names the
10291+ /// clip, the q, the frame, the plane and the first differing sample.
10292+ /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
10293+ /// which exposes no per-packet reconstruction, so that path asserts the
10294+ /// two decoders against each other on all three planes.)
10086 ///10295 ///
10087 /// Run:10296 /// Run:
10088 /// cargo test -p ec-av1 --release --lib -- --ignored \10297 /// cargo test -p ec-av1 --release --lib -- --ignored \
@@ -10162,12 +10371,13 @@ mod tests {
10162 let _ = crate::tile::take_ref_hits();10371 let _ = crate::tile::take_ref_hits();
10163 let _ = crate::tile::take_compound_mode_hits();10372 let _ = crate::tile::take_compound_mode_hits();
10164 let _ = crate::tile::take_compound_pair_hits();10373 let _ = crate::tile::take_compound_pair_hits();
10374+ let _ = crate::tile::take_compound_size_hits();
10165 let _ = crate::motion::take_census();10375 let _ = crate::motion::take_census();
10166 let (ours, ours_wall) = match pyramid_from_env() {10376 let (ours, ours_wall) = match pyramid_from_env() {
10167- None => our_ladder(&source, width, height, fctx),10377+ None => our_ladder(name, &source, width, height, fctx),
10168 Some(pyramid) => {10378 Some(pyramid) => {
10169 let (ladder, wall, counts, bytes) =10379 let (ladder, wall, counts, bytes) =
10170- our_ladder_pyramid(&source, width, height, pyramid);10380+ our_ladder_pyramid(name, &source, width, height, pyramid);
10171 eprintln!(10381 eprintln!(
10172 "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \10382 "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \
10173 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",10383 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
@@ -10203,6 +10413,7 @@ mod tests {
10203 // picks cannot be what a BD number credits).10413 // picks cannot be what a BD number credits).
10204 let comp_modes = crate::tile::take_compound_mode_hits();10414 let comp_modes = crate::tile::take_compound_mode_hits();
10205 let comp_pairs = crate::tile::take_compound_pair_hits();10415 let comp_pairs = crate::tile::take_compound_pair_hits();
10416+ let comp_sizes = crate::tile::take_compound_size_hits();
10206 let comp_total: usize = comp_modes.iter().sum();10417 let comp_total: usize = comp_modes.iter().sum();
10207 eprintln!(10418 eprintln!(
10208 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \10419 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
@@ -10214,6 +10425,10 @@ mod tests {
10214 comp_modes[6], comp_modes[7],10425 comp_modes[6], comp_modes[7],
10215 comp_pairs[3], comp_pairs[6],10426 comp_pairs[3], comp_pairs[6],
10216 );10427 );
10428+ eprintln!(
10429+ "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
10430+ comp_sizes[1], comp_sizes[2], comp_sizes[3],
10431+ );
10217 // Where the wall-owning stage actually goes: how many candidate10432 // Where the wall-owning stage actually goes: how many candidate
10218 // evaluations (one `mc::predict` + SAD each) a search spends, how10433 // evaluations (one `mc::predict` + SAD each) a search spends, how
10219 // many of them are subpel, and how often the winner is the seed10434 // many of them are subpel, and how often the winner is the seed
crates/ec-av1/src/tile.rsmodified+15 -0
@@ -525,6 +525,19 @@ pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
525 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))525 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
526 }526 }
527 527
528+/// Per-SIZE fire counts of [`write_compound_block`], indexed by
529+/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
530+/// 32x32-only tool, so the share by size is what says whether the leaf
531+/// candidates fire at all (gate-blind-to-feature).
532+static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
533+ [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
534+
535+/// Takes and clears the compound size histogram.
536+#[cfg(test)]
537+pub(crate) fn take_compound_size_hits() -> [usize; 4] {
538+ std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
539+}
540+
528 /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side541 /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
529 /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /542 /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
530 /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that543 /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
@@ -662,6 +675,8 @@ fn write_compound_block(
662 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);675 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
663 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]676 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
664 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);677 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
678+ COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
679+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
665 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {680 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
666 eprintln!(681 eprintln!(
667 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",682 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",