forge
Explore
Log in

Don't you dare go Hollow

wip(av1): lane-b128hv search-side HORZ/VERT at the 128 root, snapshot (orchestrator)

Browse files at this commit

4568a63cb7c80fa383e427401c006002b7daa6beAhmet Kaan GümüşParent: b52bd17
crates/ec-av1/src/encode.rsmodified+423 -9
@@ -786,6 +786,46 @@ pub fn take_b128_compound_hits() -> usize {
786 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)786 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
787 }787 }
788 788
789+/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
790+/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
791+/// same skip-only single-reference/compound machinery the NONE arm ships,
792+/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
793+/// `EC_AV1_B128HV=0` is this arm's attribution control.
794+fn b128_rect() -> bool {
795+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
796+ crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0")
797+ });
798+ ENV.unwrap_or(true) && b128_root()
799+}
800+
801+/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
802+/// halves since the last take (class `gate-blind-to-feature`).
803+static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
804+/// The VERT twin of [`B128_HORZ_HITS`].
805+static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
806+
807+/// The HORZ-128-root count since the last call, and zero it.
808+pub fn take_b128_horz_hits() -> usize {
809+ B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
810+}
811+
812+/// The VERT-128-root count since the last call, and zero it.
813+pub fn take_b128_vert_hits() -> usize {
814+ B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
815+}
816+
817+/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
818+/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
819+/// synthetic content is where the shape is cheapest to decode-check and the
820+/// RD there prefers one whole block; the gate census is the unforced count.
821+static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
822+
823+/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
824+#[cfg(test)]
825+pub(crate) fn force_b128_rect(which: u8) {
826+ FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
827+}
828+
789 /// Test-only: take the 128 root's residual arm whatever it costs, so a829 /// Test-only: take the 128 root's residual arm whatever it costs, so a
790 /// witness clip codes the shape rather than waiting for content on which the830 /// witness clip codes the shape rather than waiting for content on which the
791 /// RD picks it (the same role [`force_sb128`] plays for the superblock size).831 /// RD picks it (the same role [`force_sb128`] plays for the superblock size).
@@ -7379,6 +7419,31 @@ fn record_mi(
7379 }7419 }
7380 }7420 }
7381 7421
7422+/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
7423+/// writer's own `write_inter_block_128_rect` makes, so the second half of a
7424+/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
7425+fn record_mi_rect(
7426+ grid: &mut MiGrid,
7427+ mi_row: usize,
7428+ mi_col: usize,
7429+ (w_mi, h_mi): (usize, usize),
7430+ inter: Option<InterInfo>,
7431+ skip: bool,
7432+) {
7433+ record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
7434+ // `record_mi` stamped the square corner; widen it to the true footprint,
7435+ // with the block's own (rect) size fields.
7436+ let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
7437+ info.size = w_mi as u8;
7438+ info.size_h = h_mi as u8;
7439+ for dr in 0..h_mi {
7440+ for dc in 0..w_mi {
7441+ grid.set(mi_row + dr, mi_col + dc, info);
7442+ grid.set_skip(mi_row + dr, mi_col + dc, skip);
7443+ }
7444+ }
7445+}
7446+
7382 /// The reconstructed samples one 32x32 square covers in all three planes, so7447 /// The reconstructed samples one 32x32 square covers in all three planes, so
7383 /// that a partition trial can be undone.7448 /// that a partition trial can be undone.
7384 /// One square of a plane, row-major, the inverse of [`Plane::restore`].7449 /// One square of a plane, row-major, the inverse of [`Plane::restore`].
@@ -9659,6 +9724,165 @@ fn search_root_128(
9659 ))9724 ))
9660 }9725 }
9661 9726
9727+/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
9728+/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
9729+/// shipped NONE machinery halved. Skip only, single reference or compound,
9730+/// exactly what `crate::tile::write_inter_block_128_rect` codes and
9731+/// `decode_inter_block` reads at `sb128_rect`.
9732+///
9733+/// The FIRST half is published into `grid` before the second is searched --
9734+/// the writer publishes it too, so a second half searched against the stale
9735+/// grid would be priced (and its mv predicted) off a stack the decoder never
9736+/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
9737+/// both planes are put back before returning; the caller re-applies the
9738+/// winner.
9739+///
9740+/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
9741+/// carrying the root's own partition symbol so it ranks against
9742+/// [`search_root_128`] and against the four superblocks below.
9743+#[allow(clippy::too_many_arguments)]
9744+fn search_root_128_rect(
9745+ luma: &mut Plane,
9746+ chroma: &mut [Plane; 2],
9747+ grid: &mut crate::mvstack::MiGrid,
9748+ (root_r, root_c): (usize, usize),
9749+ (rows, cols): (usize, usize),
9750+ (mi_cols, mi_rows): (u32, u32),
9751+ search: Search<'_>,
9752+ tpl_factors: &Option<Vec<f64>>,
9753+ sb_q: Option<&Vec<u8>>,
9754+ sb_cols: usize,
9755+ tpl_cells_x: usize,
9756+ base_q_idx: u8,
9757+ reference: &Picture,
9758+ // The `LAST` + extra-reference pairs offered at this root; only the
9759+ // reference and its picture are read here, since each HALF derives its
9760+ // own compound stack at its own rectangular window.
9761+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9762+ horz: bool,
9763+ fctx: &crate::decode::FrameCtx,
9764+) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
9765+ const SIDE: usize = SUPERBLOCK * 2;
9766+ const SIDE_MI: usize = SIDE / 4;
9767+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9768+ let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9769+ if root_r * 2 + 3 >= rows
9770+ || root_c * 2 + 3 >= cols
9771+ || (mi_row + SIDE_MI) as u32 > mi_rows
9772+ || (mi_col + SIDE_MI) as u32 > mi_cols
9773+ || x128 + SIDE > luma.true_width
9774+ || y128 + SIDE > luma.true_height
9775+ {
9776+ return None;
9777+ }
9778+ // The root's own lambda, the mean of its four superblocks' -- the same
9779+ // one [`search_root_128`] prices with, so the three root candidates and
9780+ // the four-superblock arm are all comparable.
9781+ let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9782+ (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9783+ (None, Some(f)) => {
9784+ let mean = (0..16)
9785+ .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9786+ .sum::<f64>()
9787+ / 16.0;
9788+ search.lambda * mean
9789+ }
9790+ (None, None) => search.lambda,
9791+ };
9792+ let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9793+ .iter()
9794+ .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9795+ .sum::<f64>()
9796+ / 4.0;
9797+ let root_search = Search {
9798+ lambda,
9799+ ..match sb_q {
9800+ Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9801+ None => search,
9802+ }
9803+ };
9804+ let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) };
9805+ let (w_mi, h_mi) = (w / 4, h / 4);
9806+ let base = snapshot(luma, chroma, (x128, y128), SIDE);
9807+ let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
9808+ let mut cost = 0.0f64;
9809+ let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
9810+ for i in 0..2usize {
9811+ let (mr, mc) = if horz {
9812+ (mi_row + i * 16, mi_col)
9813+ } else {
9814+ (mi_row, mi_col + i * 16)
9815+ };
9816+ let stack = find_mv_stack(
9817+ grid,
9818+ mr,
9819+ mc,
9820+ w_mi,
9821+ h_mi,
9822+ LAST_FRAME,
9823+ mi_cols as usize,
9824+ mi_rows as usize,
9825+ );
9826+ let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
9827+ .iter()
9828+ .map(|&(r, pic, _)| {
9829+ (
9830+ r,
9831+ pic,
9832+ crate::mvstack::find_mv_stack_compound(
9833+ grid,
9834+ mr,
9835+ mc,
9836+ w_mi,
9837+ h_mi,
9838+ (LAST_FRAME, r),
9839+ mi_cols as usize,
9840+ mi_rows as usize,
9841+ grid.sign_bias_table(),
9842+ &[(0, 0); 7],
9843+ None,
9844+ ),
9845+ )
9846+ })
9847+ .collect();
9848+ let found = search_skip_64(
9849+ luma,
9850+ chroma,
9851+ (mc * 4, mr * 4),
9852+ (w, h),
9853+ &root_search,
9854+ false,
9855+ reference,
9856+ &stack,
9857+ &half_compound,
9858+ fctx,
9859+ );
9860+ match found {
9861+ Some((c, block)) => {
9862+ cost += c;
9863+ record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
9864+ halves.push(block);
9865+ }
9866+ None => {
9867+ restore(luma, chroma, (x128, y128), SIDE, &base);
9868+ grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
9869+ return None;
9870+ }
9871+ }
9872+ }
9873+ let after = snapshot(luma, chroma, (x128, y128), SIDE);
9874+ restore(luma, chroma, (x128, y128), SIDE, &base);
9875+ grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
9876+ let symbol = if horz { 1 } else { 2 };
9877+ let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
9878+ Some((
9879+ cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
9880+ lambda,
9881+ [b0, b1],
9882+ after,
9883+ ))
9884+}
9885+
9662 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):9886 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
9663 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded9887 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
9664 /// SKIP, priced through the same `symbol_bits` path every other candidate9888 /// SKIP, priced through the same `symbol_bits` path every other candidate
@@ -12389,6 +12613,44 @@ pub(crate) fn encode_inter_frame(
12389 fctx,12613 fctx,
12390 ))12614 ))
12391 .flatten();12615 .flatten();
12616+ // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
12617+ // are priced; the cheaper one competes with the NONE block and with
12618+ // the four superblocks below.
12619+ let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
12620+ let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
12621+ .then(|| {
12622+ let mut best: Option<(bool, _)> = None;
12623+ for horz in [true, false] {
12624+ if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
12625+ continue;
12626+ }
12627+ let Some(found) = search_root_128_rect(
12628+ &mut luma,
12629+ &mut chroma,
12630+ &mut grid,
12631+ (root_r, root_c),
12632+ (rows, cols),
12633+ (header.mi_cols, header.mi_rows),
12634+ search,
12635+ &tpl_factors,
12636+ sb_q.as_ref(),
12637+ sb_cols,
12638+ tpl_cells_x,
12639+ base_q_idx,
12640+ reference,
12641+ &root_compound,
12642+ horz,
12643+ fctx,
12644+ ) else {
12645+ continue;
12646+ };
12647+ if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) {
12648+ best = Some((horz, found));
12649+ }
12650+ }
12651+ best
12652+ })
12653+ .flatten();
12392 for (sb_r, sb_c) in cells {12654 for (sb_r, sb_c) in cells {
12393 // lane-b64: the whole superblock as ONE 64x64 block, tried before12655 // lane-b64: the whole superblock as ONE 64x64 block, tried before
12394 // its quadrants are (`search_skip_64`) and compared against the12656 // its quadrants are (`search_skip_64`) and compared against the
@@ -12967,18 +13229,56 @@ pub(crate) fn encode_inter_frame(
12967 // `partition_w128` symbol) against what its four superblocks really13229 // `partition_w128` symbol) against what its four superblocks really
12968 // cost, the same weighing the 64 root does one size down. Both sides13230 // cost, the same weighing the 64 root does one size down. Both sides
12969 // carry their own partition symbol, so the comparison is complete.13231 // carry their own partition symbol, so the comparison is complete.
12970- if let Some((cost128, lambda128, block, after)) = root12813232+ // lane-b128hv: `None` is the NONE arm, `Some(horz)` a rect cut.
13233+ let mut cands: Vec<(f64, f64, Option<bool>, Vec<BlockCoeffs>, _)> = Vec::new();
13234+ if let Some((c, l, b, a)) = root128 {
13235+ cands.push((c, l, None, vec![b], a));
13236+ }
13237+ if let Some((horz, (c, l, halves, a))) = root_rect {
13238+ cands.push((c, l, Some(horz), halves.to_vec(), a));
13239+ }
13240+ // The rect witness knob drops the NONE arm outright: on synthetic
13241+ // content the whole block always wins its own comparison.
13242+ if forced_rect != 0 {
13243+ cands.retain(|c| c.2.is_some());
13244+ }
13245+ cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13246+ if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
12971 && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)13247 && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)
12972- // The witness knob takes the root whatever it costs, so the13248+ // The witness knobs take the root whatever it costs, so the
12973- // forced residual block really reaches the writer.13249+ // forced block really reaches the writer.
12974- || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed))13250+ || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
13251+ || forced_rect != 0)
12975 {13252 {
12976- B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12977 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);13253 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
12978 blocks.truncate(mark128);13254 blocks.truncate(mark128);
12979 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);13255 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
12980- record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);13256+ let at = (root_r * 2) * cols + root_c * 2;
12981- blocks.push(((root_r * 2) * cols + root_c * 2, Quadrant::Whole128(block)));13257+ match shape {
13258+ None => {
13259+ B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13260+ let block = halves.into_iter().next().expect("the NONE arm's block");
13261+ record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
13262+ blocks.push((at, Quadrant::Whole128(block)));
13263+ }
13264+ Some(horz) => {
13265+ if horz {
13266+ B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13267+ } else {
13268+ B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13269+ }
13270+ let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
13271+ for (i, half) in halves.iter().enumerate() {
13272+ let (mr, mc) = if horz {
13273+ (root_r * 16 + i * 16, root_c * 16)
13274+ } else {
13275+ (root_r * 16, root_c * 16 + i * 16)
13276+ };
13277+ record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
13278+ }
13279+ blocks.push((at, Quadrant::Rect128(horz, halves)));
13280+ }
13281+ }
12982 for q in 1..16 {13282 for q in 1..16 {
12983 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);13283 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
12984 blocks.push((r32 * cols + c32, Quadrant::Covered));13284 blocks.push((r32 * cols + c32, Quadrant::Covered));
@@ -13036,10 +13336,28 @@ pub(crate) fn encode_inter_frame(
13036 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))13336 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
13037 })13337 })
13038 .count();13338 .count();
13339+ // lane-b128hv: and how many roots took a rect cut instead, per shape
13340+ // -- the HORZ/VERT fire count the gate rows are read against.
13341+ let horz = blocks
13342+ .iter()
13343+ .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
13344+ .count();
13345+ let vert = blocks
13346+ .iter()
13347+ .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
13348+ .count();
13349+ let rect_compound = blocks
13350+ .iter()
13351+ .filter(|q| {
13352+ matches!(q, Quadrant::Rect128(_, hs)
13353+ if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
13354+ })
13355+ .count();
13039 eprintln!(13356 eprintln!(
13040 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \13357 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
13041- {compound} compound), {roots} coded blocks ({:.1}% of the frame's area at 128)",13358+ {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
13042- 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,13359+ compound half), {roots} coded blocks ({:.1}% of the frame's area at 128)",
13360+ 100.0 * ((whole + horz + vert) * 16) as f64 / blocks.len().max(1) as f64,
13043 );13361 );
13044 }13362 }
13045 let modes = blocks13363 let modes = blocks
@@ -16469,6 +16787,102 @@ mod tests {
16469 }16787 }
16470 }16788 }
16471 16789
16790+ /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
16791+ /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
16792+ /// square. Three passes over one `testsrc2` clip:
16793+ ///
16794+ /// * HORZ forced at every root ([`force_b128_rect`]), so every context
16795+ /// the 128x64 shape reads is exercised rather than the handful the RD
16796+ /// would pick;
16797+ /// * VERT forced the same way;
16798+ /// * UNFORCED, which is the count the gate rows are read against -- the
16799+ /// same clip with the RD free to choose among NONE / HORZ / VERT /
16800+ /// four superblocks.
16801+ ///
16802+ /// Each pass is sample-exact against the encoder's own reconstruction
16803+ /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
16804+ /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
16805+ /// before this lane by construction: `write_sb128_root` could only name
16806+ /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
16807+ ///
16808+ /// cargo test -p ec-av1 --release --lib -- --ignored \
16809+ /// a_128_root_horz_and_vert --nocapture
16810+ #[test]
16811+ #[ignore = "sets the process-global superblock size: run it alone"]
16812+ fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
16813+ let _knobs = crate::speed::knob_write();
16814+ if !have_ffmpeg() {
16815+ eprintln!("SKIP: no ffmpeg");
16816+ return;
16817+ }
16818+ force_sb128(true);
16819+ let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
16820+ std::fs::create_dir_all(&dir).unwrap();
16821+ let clip = dir.join("testsrc2-1280x768.y4m");
16822+ let ok = Command::new("ffmpeg")
16823+ .args(["-v", "error", "-y", "-f", "lavfi"])
16824+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
16825+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
16826+ .arg(&clip)
16827+ .status()
16828+ .expect("ffmpeg failed to run")
16829+ .success();
16830+ assert!(ok, "ffmpeg could not write the synthetic clip");
16831+ let (width, height) = (1280usize, 768usize);
16832+ let pictures =
16833+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
16834+ let mut unforced = (0usize, 0usize);
16835+ for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
16836+ force_b128_rect(force);
16837+ let _ = take_b128_horz_hits();
16838+ let _ = take_b128_vert_hits();
16839+ let _ = crate::tile::take_sb128_horz_hits();
16840+ let _ = crate::tile::take_sb128_vert_hits();
16841+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
16842+ let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
16843+ let (coded_h, coded_v) = (
16844+ crate::tile::take_sb128_horz_hits(),
16845+ crate::tile::take_sb128_vert_hits(),
16846+ );
16847+ eprintln!(
16848+ "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
16849+ {coded_h} 128x64 + {coded_v} 64x128 halves"
16850+ );
16851+ match force {
16852+ 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
16853+ 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
16854+ // The unforced count is REPORTED, not asserted: it is the
16855+ // number the gate is read against, and a zero here would be
16856+ // an RD result, not a defect (the forced passes already prove
16857+ // the writer and the reader agree on the shape).
16858+ _ => unforced = (won_h, won_v),
16859+ }
16860+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16861+ assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
16862+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
16863+ for (plane, got, want) in [
16864+ ("luma", &dec.y, &frame.reconstruction.y),
16865+ ("U", &dec.u, &frame.reconstruction.u),
16866+ ("V", &dec.v, &frame.reconstruction.v),
16867+ ] {
16868+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
16869+ assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
16870+ }
16871+ }
16872+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
16873+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
16874+ assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
16875+ assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
16876+ assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
16877+ }
16878+ }
16879+ force_b128_rect(0);
16880+ eprintln!(
16881+ "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
16882+ unforced.0, unforced.1
16883+ );
16884+ }
16885+
16472 #[test]16886 #[test]
16473 #[ignore = "sets the process-global superblock size: run it alone"]16887 #[ignore = "sets the process-global superblock size: run it alone"]
16474 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {16888 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
crates/ec-av1/src/mvstack.rsmodified+43 -0
@@ -372,6 +372,49 @@ impl MiGrid {
372 }372 }
373 }373 }
374 374
375+ /// lane-b128hv: the raw cells and skip flags of one rect region, and the
376+ /// write-back that undoes a trial that published into it -- the 128
377+ /// root's HORZ/VERT search stamps its FIRST half so that the second
378+ /// half's mv stack is the one the writer will rebuild, then puts the grid
379+ /// back for the four-superblock arm it is weighed against.
380+ pub fn snapshot_rect(
381+ &self,
382+ row: usize,
383+ col: usize,
384+ h: usize,
385+ w: usize,
386+ ) -> (Vec<Option<MiInfo>>, Vec<bool>) {
387+ let mut cells = Vec::with_capacity(h * w);
388+ let mut skips = Vec::with_capacity(h * w);
389+ for r in row..(row + h).min(self.rows) {
390+ let c1 = (col + w).min(self.cols);
391+ cells.extend_from_slice(&self.cells[r * self.cols + col..r * self.cols + c1]);
392+ skips.extend_from_slice(&self.skips[r * self.cols + col..r * self.cols + c1]);
393+ }
394+ (cells, skips)
395+ }
396+
397+ /// Puts a [`Self::snapshot_rect`] back.
398+ pub fn restore_rect(
399+ &mut self,
400+ row: usize,
401+ col: usize,
402+ h: usize,
403+ w: usize,
404+ snap: &(Vec<Option<MiInfo>>, Vec<bool>),
405+ ) {
406+ let mut i = 0;
407+ for r in row..(row + h).min(self.rows) {
408+ let c1 = (col + w).min(self.cols);
409+ let n = c1 - col;
410+ self.cells[r * self.cols + col..r * self.cols + c1]
411+ .copy_from_slice(&snap.0[i..i + n]);
412+ self.skips[r * self.cols + col..r * self.cols + c1]
413+ .copy_from_slice(&snap.1[i..i + n]);
414+ i += n;
415+ }
416+ }
417+
375 /// The unit at `(row, col)`, or `None` when it is outside the grid, hasn't418 /// The unit at `(row, col)`, or `None` when it is outside the grid, hasn't
376 /// been coded, or sits outside the current tile's own bounds ([`Self::set_tile_bounds`]).419 /// been coded, or sits outside the current tile's own bounds ([`Self::set_tile_bounds`]).
377 pub fn get(&self, row: usize, col: usize) -> Option<MiInfo> {420 pub fn get(&self, row: usize, col: usize) -> Option<MiInfo> {