diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 27fddbd7..26d296ac 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -762,6 +762,30 @@ fn b128_residual() -> bool { && b128_root() } +/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64 +/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, +/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's +/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this +/// arm's attribution control; the writer has always had the path +/// (`write_inter_block_128` calls `write_compound_block` for a block that +/// names a second reference). +fn b128_compound() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0") + }); + ENV.unwrap_or(true) && b128_root() +} + +/// How many 128 roots came out COMPOUND since the last +/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`). +static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// The compound-128 count since the last call, and zero it. +pub fn take_b128_compound_hits() -> usize { + B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// Test-only: take the 128 root's residual arm whatever it costs, so a /// witness clip codes the shape rather than waiting for content on which the /// RD picks it (the same role [`force_sb128`] plays for the superblock size). @@ -769,10 +793,25 @@ fn b128_residual() -> bool { static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Arms [`FORCE_B128_RESIDUAL`] for the rest of the process. +/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take +/// the 128 root whenever it produced a candidate at all, whatever its four +/// cells cost, so a witness codes the block it is about rather than waiting +/// for content on which the root also wins its own comparison. +static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a +/// forced residual block only reaches the writer if its root is taken. #[cfg(test)] pub(crate) fn force_b128_residual(on: bool) { FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed); + force_b128_root(on); +} + +/// Arms [`FORCE_B128_ROOT`] for the rest of the process. +#[cfg(test)] +pub(crate) fn force_b128_root(on: bool) { + FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed); } /// How many 128 roots came out cheaper WITH a residual than skipped, since @@ -9445,6 +9484,11 @@ fn search_root_128( tpl_cells_x: usize, base_q_idx: u8, reference: &Picture, + // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window, + // built by the caller off the same grid the tile writer rebuilds its + // stack from (empty unless the frame carries `reference_select` and + // [`b128_compound`] is on). + compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, ) -> Option<(f64, f64, BlockCoeffs, [(Vec, Vec); 3])> { const SIDE: usize = SUPERBLOCK * 2; @@ -9510,10 +9554,13 @@ fn search_root_128( false, reference, &stack, - &[], + compound, fctx, ); let (mut cost, mut block) = found?; + if block.inter.is_some_and(|i| i.ref1.is_some()) { + B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } // lane-b128r: the same prediction with a REAL residual, priced against // the skip arm the search just committed to the planes (which IS the // winner's prediction, sample for sample). The block's residual is four @@ -12263,6 +12310,40 @@ pub(crate) fn encode_inter_frame( // 128x128 candidate is weighed. let mark128 = blocks.len(); let mut root_cost = 0.0f64; + // The 128 root's own compound pairs, at its 32x32-mi window (the 64 + // root builds the same list one size down, per superblock). + let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = + if header.reference_select && b128_compound() && !screen && sb128_search { + [ + (crate::mvstack::GOLDEN_FRAME, golden), + (crate::mvstack::ALTREF_FRAME, altref), + ] + .into_iter() + .filter_map(|(r, pic)| { + pic.map(|p| { + ( + r, + p, + crate::mvstack::find_mv_stack_compound( + &grid, + root_r * 16, + root_c * 16, + 32, + 32, + (crate::mvstack::LAST_FRAME, r), + mi_cols, + mi_rows, + grid.sign_bias_table(), + &[(0, 0); 7], + None, + ), + ) + }) + }) + .collect() + } else { + Vec::new() + }; let root128 = (sb128_search && b128_root() && cells.len() == 4) .then(|| search_root_128( &mut luma, @@ -12278,6 +12359,7 @@ pub(crate) fn encode_inter_frame( tpl_cells_x, base_q_idx, reference, + &root_compound, fctx, )) .flatten(); @@ -12863,7 +12945,7 @@ pub(crate) fn encode_inter_frame( && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true) // The witness knob takes the root whatever it costs, so the // forced residual block really reaches the writer. - || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed)) + || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)) { B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); @@ -12920,8 +13002,17 @@ pub(crate) fn encode_inter_frame( .iter() .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip)) .count(); + // lane-b128r: and how many named a second reference (the compound + // arm at the 128 root). + let compound = blocks + .iter() + .filter(|q| { + matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())) + }) + .count(); eprintln!( - "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual), {roots} coded blocks ({:.1}% of the frame's area at 128)", + "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \ + {compound} compound), {roots} coded blocks ({:.1}% of the frame's area at 128)", 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64, ); } @@ -16285,6 +16376,73 @@ mod tests { } } + /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block + /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same + /// `write_compound_block` chain every smaller compound block takes, at a + /// window it had never been exercised at. RED before this lane: the + /// search passed an empty compound list at the 128 root, so the count was + /// 0 and no such block existed to decode. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_128_root_compound_block --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_128_root_compound_block_decodes_exact_through_both_decoders() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } + force_sb128(true); + let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let clip = dir.join("testsrc2-1280x768.y4m"); + // Moving objects that occlude each other: a pan is coded by one + // reference outright, and a compound pair only pays where the two + // references disagree. + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi"]) + .args(["-i", "testsrc2=size=1280x768:rate=24"]) + .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) + .arg(&clip) + .status() + .expect("ffmpeg failed to run") + .success(); + assert!(ok, "ffmpeg could not write the synthetic clip"); + let (width, height) = (1280usize, 768usize); + let pictures = + crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); + // The compound candidate wins the 128 block's own search on this pan + // but the root then loses to its four cells, so the root is forced + // (the residual arm is left at its default, off). + force_b128_root(true); + let _ = take_b128_compound_hits(); + let _ = crate::tile::take_sb128_compound_hits(); + let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); + let (won, coded) = + (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits()); + eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}"); + assert!(coded > 0, "no compound 128x128 block was coded on this clip"); + let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + for (plane, got, want) in [ + ("luma", &dec.y, &frame.reconstruction.y), + ("U", &dec.u, &frame.reconstruction.u), + ("V", &dec.v, &frame.reconstruction.v), + ] { + let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); + } + } + let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); + for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { + assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); + assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); + assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); + } + } + #[test] #[ignore = "sets the process-global superblock size: run it alone"] fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() { @@ -17751,7 +17909,12 @@ mod tests { // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053. // Re-taken at the merge of lane-b128m onto main (128 superblocks on // by default, on top of the ARF temporal filter). - let pins: [(u8, usize, u64); 2] = [(150, 8354, 0x1290b8628438c6d4), (60, 33222, 0xc7f92971ab1264c3)]; + // Re-taken on lane-b128r: the 128 root now offers the COMPOUND + // candidates the 64 root already did ([`b128_compound`]), so every + // inter frame that carries `reference_select` codes different blocks + // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60. + // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly. + let pins: [(u8, usize, u64); 2] = [(150, 8364, 0xcb2ad7936d5127c5), (60, 33257, 0x87db250ba556e5a6)]; let coded: Vec<(u8, usize, u64)> = pins .iter() .map(|&(q, _, _)| { diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index ee74ee51..a935fd4e 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -458,6 +458,9 @@ fn write_inter_block_128( if !block.skip { SB128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } + if info.ref1.is_some() { + SB128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } Ok(()) } @@ -472,6 +475,17 @@ pub fn take_sb128_residual_hits() -> usize { SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) } +/// lane-b128r: how many of those blocks named a SECOND reference (the +/// compound arm at the 128 root), since the last +/// [`take_sb128_compound_hits`]. +static SB128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// The compound-128 count since the last call, and zero it. +pub fn take_sb128_compound_hits() -> usize { + SB128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since /// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`). static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);