forge
Explore
Log in

Don't you dare go Hollow

The 128 superblock root offers the four AB shapes

Browse files at this commit

62a90fb3d0824997c34c12d1c8a236eb0e3223a9Ahmet Kaan GümüşParent: b4cfa09
  • feat
    • the 128 superblock root offers the four AB shapes
Show full message
feat(av1): the 128 superblock root offers the four AB shapes
crates/ec-av1/src/encode.rsmodified+396 -11
@@ -826,6 +826,69 @@ pub(crate) fn force_b128_rect(which: u8) {
826 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);826 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
827 }827 }
828 828
829+/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
830+/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
831+/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
832+/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
833+/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
834+/// arms ship, at its own footprint ([`search_root_128_ab`],
835+/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
836+/// arm's attribution control.
837+fn b128_ab() -> bool {
838+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
839+ crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0")
840+ });
841+ ENV.unwrap_or(true) && b128_root()
842+}
843+
844+/// How many 128 roots the search left as each AB shape since the last take,
845+/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
846+/// `gate-blind-to-feature`).
847+static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
848+ [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
849+
850+/// The four per-shape AB-root counts since the last call, and zero them.
851+pub fn take_b128_ab_hits() -> [usize; 4] {
852+ std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
853+}
854+
855+/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
856+/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
857+/// content is where the shapes are cheapest to decode-check and the RD there
858+/// prefers one whole block).
859+static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
860+
861+/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
862+#[cfg(test)]
863+pub(crate) fn force_b128_ab(which: u8) {
864+ FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
865+}
866+
867+/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
868+/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
869+/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
870+/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
871+/// Each entry is the piece's own top-left in mode-info units and its
872+/// footprint in samples.
873+pub(crate) fn ab128_pieces(
874+ symbol: usize,
875+ (mi_row, mi_col): (usize, usize),
876+) -> [((usize, usize), (usize, usize)); 3] {
877+ const S: usize = SUPERBLOCK;
878+ let (r, c) = (mi_row, mi_col);
879+ let (r1, c1) = (mi_row + 16, mi_col + 16);
880+ match symbol {
881+ // PARTITION_HORZ_A
882+ 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
883+ // PARTITION_HORZ_B
884+ 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
885+ // PARTITION_VERT_A
886+ 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
887+ // PARTITION_VERT_B
888+ _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
889+ }
890+}
891+
829 /// Test-only: take the 128 root's residual arm whatever it costs, so a892 /// Test-only: take the 128 root's residual arm whatever it costs, so a
830 /// witness clip codes the shape rather than waiting for content on which the893 /// witness clip codes the shape rather than waiting for content on which the
831 /// RD picks it (the same role [`force_sb128`] plays for the superblock size).894 /// RD picks it (the same role [`force_sb128`] plays for the superblock size).
@@ -9891,6 +9954,156 @@ fn search_root_128_rect(
9891 ))9954 ))
9892 }9955 }
9893 9956
9957+/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
9958+/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
9959+/// decoder's own). Each piece is priced through the same `search_skip_64`
9960+/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
9961+/// into `grid` before the next is searched -- the writer publishes it too, so
9962+/// a later piece searched against a stale grid would be priced (and its mv
9963+/// predicted) off a stack the decoder never derives (class
9964+/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
9965+/// are put back before returning; the caller re-applies the winner.
9966+///
9967+/// SKIP only, for the reason [`search_root_128_rect`] gives: the 128 residual
9968+/// arm the pieces would share is itself parked behind `EC_AV1_B128RES`.
9969+///
9970+/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
9971+/// already carrying the root's own partition symbol so it ranks against the
9972+/// other root candidates and against the four superblocks below.
9973+#[allow(clippy::too_many_arguments)]
9974+fn search_root_128_ab(
9975+ luma: &mut Plane,
9976+ chroma: &mut [Plane; 2],
9977+ grid: &mut crate::mvstack::MiGrid,
9978+ (root_r, root_c): (usize, usize),
9979+ (rows, cols): (usize, usize),
9980+ (mi_cols, mi_rows): (u32, u32),
9981+ search: Search<'_>,
9982+ tpl_factors: &Option<Vec<f64>>,
9983+ sb_q: Option<&Vec<u8>>,
9984+ sb_cols: usize,
9985+ tpl_cells_x: usize,
9986+ base_q_idx: u8,
9987+ reference: &Picture,
9988+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9989+ // The partition symbol, 4..=7.
9990+ symbol: usize,
9991+ fctx: &crate::decode::FrameCtx,
9992+) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
9993+ const SIDE: usize = SUPERBLOCK * 2;
9994+ const SIDE_MI: usize = SIDE / 4;
9995+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9996+ let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9997+ if root_r * 2 + 3 >= rows
9998+ || root_c * 2 + 3 >= cols
9999+ || (mi_row + SIDE_MI) as u32 > mi_rows
10000+ || (mi_col + SIDE_MI) as u32 > mi_cols
10001+ || x128 + SIDE > luma.true_width
10002+ || y128 + SIDE > luma.true_height
10003+ {
10004+ return None;
10005+ }
10006+ // The root's own lambda, the mean of its four superblocks' -- the same one
10007+ // [`search_root_128`] prices with, so every root candidate and the
10008+ // four-superblock arm are comparable.
10009+ let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10010+ (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10011+ (None, Some(f)) => {
10012+ let mean = (0..16)
10013+ .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10014+ .sum::<f64>()
10015+ / 16.0;
10016+ search.lambda * mean
10017+ }
10018+ (None, None) => search.lambda,
10019+ };
10020+ let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10021+ .iter()
10022+ .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10023+ .sum::<f64>()
10024+ / 4.0;
10025+ let root_search = Search {
10026+ lambda,
10027+ ..match sb_q {
10028+ Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10029+ None => search,
10030+ }
10031+ };
10032+ let base = snapshot(luma, chroma, (x128, y128), SIDE);
10033+ let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10034+ let mut cost = 0.0f64;
10035+ let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
10036+ for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
10037+ let (w_mi, h_mi) = (w / 4, h / 4);
10038+ let stack = find_mv_stack(
10039+ grid,
10040+ mr,
10041+ mc,
10042+ w_mi,
10043+ h_mi,
10044+ LAST_FRAME,
10045+ mi_cols as usize,
10046+ mi_rows as usize,
10047+ );
10048+ let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10049+ .iter()
10050+ .map(|&(r, pic, _)| {
10051+ (
10052+ r,
10053+ pic,
10054+ crate::mvstack::find_mv_stack_compound(
10055+ grid,
10056+ mr,
10057+ mc,
10058+ w_mi,
10059+ h_mi,
10060+ (LAST_FRAME, r),
10061+ mi_cols as usize,
10062+ mi_rows as usize,
10063+ grid.sign_bias_table(),
10064+ &[(0, 0); 7],
10065+ None,
10066+ ),
10067+ )
10068+ })
10069+ .collect();
10070+ let found = search_skip_64(
10071+ luma,
10072+ chroma,
10073+ (mc * 4, mr * 4),
10074+ (w, h),
10075+ &root_search,
10076+ false,
10077+ reference,
10078+ &stack,
10079+ &piece_compound,
10080+ fctx,
10081+ );
10082+ match found {
10083+ Some((c, block)) => {
10084+ cost += c;
10085+ record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10086+ pieces.push(block);
10087+ }
10088+ None => {
10089+ restore(luma, chroma, (x128, y128), SIDE, &base);
10090+ grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10091+ return None;
10092+ }
10093+ }
10094+ }
10095+ let after = snapshot(luma, chroma, (x128, y128), SIDE);
10096+ restore(luma, chroma, (x128, y128), SIDE, &base);
10097+ grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10098+ let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
10099+ Some((
10100+ cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
10101+ lambda,
10102+ [b0, b1, b2],
10103+ after,
10104+ ))
10105+}
10106+
9894 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):10107 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
9895 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded10108 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
9896 /// SKIP, priced through the same `symbol_bits` path every other candidate10109 /// SKIP, priced through the same `symbol_bits` path every other candidate
@@ -12659,6 +12872,44 @@ pub(crate) fn encode_inter_frame(
12659 best12872 best
12660 })12873 })
12661 .flatten();12874 .flatten();
12875+ // lane-ab128: and the same root as one of the four AB shapes -- two
12876+ // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
12877+ // the cheapest joins the candidate list below.
12878+ let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
12879+ let root_ab = (sb128_search && b128_ab() && cells.len() == 4 && forced_rect == 0)
12880+ .then(|| {
12881+ let mut best: Option<(usize, _)> = None;
12882+ for symbol in 4..=7usize {
12883+ if forced_ab != 0 && usize::from(forced_ab) != symbol {
12884+ continue;
12885+ }
12886+ let Some(found) = search_root_128_ab(
12887+ &mut luma,
12888+ &mut chroma,
12889+ &mut grid,
12890+ (root_r, root_c),
12891+ (rows, cols),
12892+ (header.mi_cols, header.mi_rows),
12893+ search,
12894+ &tpl_factors,
12895+ sb_q.as_ref(),
12896+ sb_cols,
12897+ tpl_cells_x,
12898+ base_q_idx,
12899+ reference,
12900+ &root_compound,
12901+ symbol,
12902+ fctx,
12903+ ) else {
12904+ continue;
12905+ };
12906+ if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) {
12907+ best = Some((symbol, found));
12908+ }
12909+ }
12910+ best
12911+ })
12912+ .flatten();
12662 for (sb_r, sb_c) in cells {12913 for (sb_r, sb_c) in cells {
12663 // lane-b64: the whole superblock as ONE 64x64 block, tried before12914 // lane-b64: the whole superblock as ONE 64x64 block, tried before
12664 // its quadrants are (`search_skip_64`) and compared against the12915 // its quadrants are (`search_skip_64`) and compared against the
@@ -13237,18 +13488,26 @@ pub(crate) fn encode_inter_frame(
13237 // `partition_w128` symbol) against what its four superblocks really13488 // `partition_w128` symbol) against what its four superblocks really
13238 // cost, the same weighing the 64 root does one size down. Both sides13489 // cost, the same weighing the 64 root does one size down. Both sides
13239 // carry their own partition symbol, so the comparison is complete.13490 // carry their own partition symbol, so the comparison is complete.
13240- // lane-b128hv: `None` is the NONE arm, `Some(horz)` a rect cut.13491+ // The root candidates, each tagged with the PARTITION symbol its
13241- let mut cands: Vec<(f64, f64, Option<bool>, Vec<BlockCoeffs>, _)> = Vec::new();13492+ // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
13493+ // shapes (lane-ab128).
13494+ let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
13242 if let Some((c, l, b, a)) = root128 {13495 if let Some((c, l, b, a)) = root128 {
13243- cands.push((c, l, None, vec![b], a));13496+ cands.push((c, l, 0, vec![b], a));
13244 }13497 }
13245 if let Some((horz, (c, l, halves, a))) = root_rect {13498 if let Some((horz, (c, l, halves, a))) = root_rect {
13246- cands.push((c, l, Some(horz), halves.to_vec(), a));13499+ cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
13500+ }
13501+ if let Some((symbol, (c, l, pieces, a))) = root_ab {
13502+ cands.push((c, l, symbol, pieces.to_vec(), a));
13247 }13503 }
13248- // The rect witness knob drops the NONE arm outright: on synthetic13504+ // The witness knobs drop every other arm outright: on synthetic
13249 // content the whole block always wins its own comparison.13505 // content the whole block always wins its own comparison.
13250 if forced_rect != 0 {13506 if forced_rect != 0 {
13251- cands.retain(|c| c.2.is_some());13507+ cands.retain(|c| c.2 == 1 || c.2 == 2);
13508+ }
13509+ if forced_ab != 0 {
13510+ cands.retain(|c| c.2 == usize::from(forced_ab));
13252 }13511 }
13253 cands.sort_by(|a, b| a.0.total_cmp(&b.0));13512 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13254 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()13513 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
@@ -13256,20 +13515,40 @@ pub(crate) fn encode_inter_frame(
13256 // The witness knobs take the root whatever it costs, so the13515 // The witness knobs take the root whatever it costs, so the
13257 // forced block really reaches the writer.13516 // forced block really reaches the writer.
13258 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)13517 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
13259- || forced_rect != 0)13518+ || forced_rect != 0
13519+ || forced_ab != 0)
13260 {13520 {
13261 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);13521 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
13262 blocks.truncate(mark128);13522 blocks.truncate(mark128);
13263 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);13523 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
13264 let at = (root_r * 2) * cols + root_c * 2;13524 let at = (root_r * 2) * cols + root_c * 2;
13265 match shape {13525 match shape {
13266- None => {13526+ 0 => {
13267 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);13527 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13268 let block = halves.into_iter().next().expect("the NONE arm's block");13528 let block = halves.into_iter().next().expect("the NONE arm's block");
13269 record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);13529 record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
13270 blocks.push((at, Quadrant::Whole128(block)));13530 blocks.push((at, Quadrant::Whole128(block)));
13271 }13531 }
13272- Some(horz) => {13532+ // lane-ab128: three pieces, published at their own footprints
13533+ // in the writer's own order ([`ab128_pieces`]).
13534+ symbol @ 4..=7 => {
13535+ B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13536+ for (((mr, mc), (w, h)), piece) in
13537+ ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves)
13538+ {
13539+ record_mi_rect(
13540+ &mut grid,
13541+ *mr,
13542+ *mc,
13543+ (w / 4, h / 4),
13544+ piece.inter,
13545+ piece.skip,
13546+ );
13547+ }
13548+ blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
13549+ }
13550+ symbol => {
13551+ let horz = symbol == 1;
13273 if horz {13552 if horz {
13274 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);13553 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13275 } else {13554 } else {
@@ -13361,11 +13640,26 @@ pub(crate) fn encode_inter_frame(
13361 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))13640 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
13362 })13641 })
13363 .count();13642 .count();
13643+ // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
13644+ // .. _VERT_B order -- the per-shape fire count its gate rows are read
13645+ // against.
13646+ let ab: [usize; 4] = std::array::from_fn(|i| {
13647+ blocks
13648+ .iter()
13649+ .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
13650+ .count()
13651+ });
13364 eprintln!(13652 eprintln!(
13365 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \13653 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
13366 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \13654 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
13367- compound half), {roots} coded blocks ({:.1}% of the frame's area at 128)",13655+ compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
13368- 100.0 * ((whole + horz + vert) * 16) as f64 / blocks.len().max(1) as f64,13656+ {roots} coded blocks ({:.1}% of the frame's area at 128)",
13657+ ab[0],
13658+ ab[1],
13659+ ab[2],
13660+ ab[3],
13661+ 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
13662+ / blocks.len().max(1) as f64,
13369 );13663 );
13370 }13664 }
13371 let modes = blocks13665 let modes = blocks
@@ -16976,6 +17270,97 @@ mod tests {
16976 );17270 );
16977 }17271 }
16978 17272
17273+ /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
17274+ /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
17275+ /// Five passes over the same `testsrc2` clip
17276+ /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
17277+ /// uses: each shape forced at every root ([`force_b128_ab`]), so every
17278+ /// context and every visit order the shape reads is exercised rather than
17279+ /// the handful the RD would pick, and then an UNFORCED pass whose
17280+ /// per-shape count is REPORTED (it is the number the gate rows are read
17281+ /// against).
17282+ ///
17283+ /// Each pass is sample-exact against the encoder's own reconstruction
17284+ /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17285+ /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17286+ /// before this lane by construction: `write_sb128_root` could only name
17287+ /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
17288+ ///
17289+ /// cargo test -p ec-av1 --release --lib -- --ignored \
17290+ /// a_128_root_ab_shapes --nocapture
17291+ #[test]
17292+ #[ignore = "sets the process-global superblock size: run it alone"]
17293+ fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
17294+ let _knobs = crate::speed::knob_write();
17295+ if !have_ffmpeg() {
17296+ eprintln!("SKIP: no ffmpeg");
17297+ return;
17298+ }
17299+ force_sb128(true);
17300+ let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
17301+ std::fs::create_dir_all(&dir).unwrap();
17302+ let clip = dir.join("testsrc2-1280x768.y4m");
17303+ let ok = Command::new("ffmpeg")
17304+ .args(["-v", "error", "-y", "-f", "lavfi"])
17305+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
17306+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17307+ .arg(&clip)
17308+ .status()
17309+ .expect("ffmpeg failed to run")
17310+ .success();
17311+ assert!(ok, "ffmpeg could not write the synthetic clip");
17312+ let (width, height) = (1280usize, 768usize);
17313+ let pictures =
17314+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17315+ let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
17316+ let mut unforced = [0usize; 4];
17317+ for force in [4u8, 5, 6, 7, 0] {
17318+ force_b128_ab(force);
17319+ let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] };
17320+ let _ = take_b128_ab_hits();
17321+ let _ = crate::tile::take_sb128_ab_hits();
17322+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17323+ let won = take_b128_ab_hits();
17324+ let coded = crate::tile::take_sb128_ab_hits();
17325+ eprintln!(
17326+ "{label}: search won {won:?} AB roots, writer coded {coded:?} \
17327+ (HORZ_A/HORZ_B/VERT_A/VERT_B)"
17328+ );
17329+ if force == 0 {
17330+ // The unforced counts are REPORTED, not asserted: a zero here
17331+ // would be an RD result, not a defect (the four forced passes
17332+ // already prove the writer and the reader agree on the shape).
17333+ unforced = won;
17334+ } else {
17335+ let i = usize::from(force) - 4;
17336+ assert!(coded[i] > 0, "no {label} root was coded with {label} forced");
17337+ }
17338+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17339+ assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
17340+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17341+ for (plane, got, want) in [
17342+ ("luma", &dec.y, &frame.reconstruction.y),
17343+ ("U", &dec.u, &frame.reconstruction.u),
17344+ ("V", &dec.v, &frame.reconstruction.v),
17345+ ] {
17346+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17347+ assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
17348+ }
17349+ }
17350+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17351+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17352+ assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
17353+ assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
17354+ assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
17355+ }
17356+ }
17357+ force_b128_ab(0);
17358+ eprintln!(
17359+ "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
17360+ unforced[0], unforced[1], unforced[2], unforced[3],
17361+ );
17362+ }
17363+
16979 #[test]17364 #[test]
16980 #[ignore = "sets the process-global superblock size: run it alone"]17365 #[ignore = "sets the process-global superblock size: run it alone"]
16981 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {17366 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
crates/ec-av1/src/tile.rsmodified+77 -7
@@ -617,9 +617,12 @@ fn write_inter_block_128_rect(
617 if let Some(r1) = info.ref1 {617 if let Some(r1) = info.ref1 {
618 neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);618 neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
619 }619 }
620+ // lane-ab128: an AB shape codes its two 64x64 pieces through this same
621+ // function, and they are neither a 128x64 nor a 64x128 half -- the
622+ // witness reads these two counters for the HORZ/VERT shape alone.
620 if w > h {623 if w > h {
621 SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);624 SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
622- } else {625+ } else if h > w {
623 SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);626 SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
624 }627 }
625 Ok(())628 Ok(())
@@ -642,6 +645,17 @@ pub fn take_sb128_vert_hits() -> usize {
642 SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)645 SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
643 }646 }
644 647
648+/// lane-ab128: how many AB-shape roots the inter writer has coded since the
649+/// last [`take_sb128_ab_hits`], in `PARTITION_HORZ_A` .. `_VERT_B` order
650+/// (class `gate-blind-to-feature`).
651+static SB128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
652+ [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
653+
654+/// The four per-shape AB-root counts since the last call, and zero them.
655+pub fn take_sb128_ab_hits() -> [usize; 4] {
656+ std::array::from_fn(|i| SB128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
657+}
658+
645 /// lane-b128r: how many of those blocks carried a REAL residual (four659 /// lane-b128r: how many of those blocks carried a REAL residual (four
646 /// TX_64X64 luma units plus their per-chunk chroma pair) rather than being660 /// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
647 /// skipped, since the last [`take_sb128_residual_hits`].661 /// skipped, since the last [`take_sb128_residual_hits`].
@@ -2594,6 +2608,17 @@ pub enum Quadrant {
2594 /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a2608 /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a
2595 /// residual), single reference or compound.2609 /// residual), single reference or compound.
2596 Rect128(bool, Vec<BlockCoeffs>),2610 Rect128(bool, Vec<BlockCoeffs>),
2611+ /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
2612+ /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
2613+ /// the order the decoder reads them
2614+ /// ([`crate::encode::ab128_pieces`]). The `u8` is the partition symbol
2615+ /// itself (4 `PARTITION_HORZ_A` .. 7 `PARTITION_VERT_B`). Carried by the
2616+ /// top-left 32x32 entry of the root's sixteen, exactly as
2617+ /// [`Rect128`](Quadrant::Rect128) is.
2618+ ///
2619+ /// SKIP only, same writer ([`crate::tile::write_inter_block_128_rect`])
2620+ /// and same reason.
2621+ Ab128(u8, Vec<BlockCoeffs>),
2597 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's2622 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
2598 /// top-left already coded; it carries no block of its own.2623 /// top-left already coded; it carries no block of its own.
2599 Covered,2624 Covered,
@@ -2606,7 +2631,9 @@ impl Quadrant {
2606 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {2631 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
2607 std::slice::from_ref(block)2632 std::slice::from_ref(block)
2608 }2633 }
2609- Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) => blocks.as_slice(),2634+ Quadrant::Split(blocks)
2635+ | Quadrant::Rect128(_, blocks)
2636+ | Quadrant::Ab128(_, blocks) => blocks.as_slice(),
2610 Quadrant::Covered => &[],2637 Quadrant::Covered => &[],
2611 }2638 }
2612 }2639 }
@@ -3742,6 +3769,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
3742 Quadrant::Whole64(_)3769 Quadrant::Whole64(_)
3743 | Quadrant::Whole128(_)3770 | Quadrant::Whole128(_)
3744 | Quadrant::Rect128(..)3771 | Quadrant::Rect128(..)
3772+ | Quadrant::Ab128(..)
3745 | Quadrant::Covered => {3773 | Quadrant::Covered => {
3746 return Err(Error::unsupported(3774 return Err(Error::unsupported(
3747 "AV1 tile",3775 "AV1 tile",
@@ -5410,7 +5438,9 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
5410 // lane-b128: a 128x128 root is SKIP by construction (the5438 // lane-b128: a 128x128 root is SKIP by construction (the
5411 // writer refuses a residual at that size), so it names no5439 // writer refuses a residual at that size), so it names no
5412 // coefficients on any plane.5440 // coefficients on any plane.
5413- Quadrant::Whole128(_) | Quadrant::Rect128(..) => return 0.0,5441+ Quadrant::Whole128(_) | Quadrant::Rect128(..) | Quadrant::Ab128(..) => {
5442+ return 0.0;
5443+ }
5414 Quadrant::Whole(_) => 32,5444 Quadrant::Whole(_) => 32,
5415 Quadrant::Split(_) => 16,5445 Quadrant::Split(_) => 16,
5416 // lane-tx64: a 64x64 root that codes a residual pays for one5446 // lane-tx64: a 64x64 root that codes a residual pays for one
@@ -7141,6 +7171,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7141 Quadrant::Rect128(horz, halves) => Some((*horz, halves)),7171 Quadrant::Rect128(horz, halves) => Some((*horz, halves)),
7142 _ => None,7172 _ => None,
7143 });7173 });
7174+ // lane-ab128: the three pieces an AB-shape root carries, and the
7175+ // partition symbol it is coded under.
7176+ let root_ab = root_entry.and_then(|q| match q {
7177+ Quadrant::Ab128(symbol, pieces) => Some((*symbol as usize, pieces)),
7178+ _ => None,
7179+ });
7144 write_sb128_root(7180 write_sb128_root(
7145 &mut enc,7181 &mut enc,
7146 &mut cdfs,7182 &mut cdfs,
@@ -7149,10 +7185,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7149 sb_c,7185 sb_c,
7150 mi_cols,7186 mi_cols,
7151 mi_rows,7187 mi_rows,
7152- match (root_block.is_some(), root_rect) {7188+ match (root_block.is_some(), root_rect, root_ab) {
7153- (true, _) => PARTITION_NONE,7189+ (true, ..) => PARTITION_NONE,
7154- (_, Some((true, _))) => PARTITION_HORZ,7190+ (_, Some((true, _)), _) => PARTITION_HORZ,
7155- (_, Some((false, _))) => PARTITION_VERT,7191+ (_, Some((false, _)), _) => PARTITION_VERT,
7192+ (_, _, Some((symbol, _))) => symbol,
7156 _ => PARTITION_SPLIT,7193 _ => PARTITION_SPLIT,
7157 },7194 },
7158 );7195 );
@@ -7201,6 +7238,38 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7201 sb128_none = true;7238 sb128_none = true;
7202 continue;7239 continue;
7203 }7240 }
7241+ if let Some((symbol, pieces)) = root_ab {
7242+ // libaom `decode_partition` at BLOCK_128X128, AB arm: two
7243+ // 64x64 blocks and one 128x64 / 64x128 half, in the order
7244+ // decode.rs' `sb128_ab` reads them
7245+ // ([`crate::encode::ab128_pieces`]). An AB shape only comes
7246+ // from the full alphabet symbol (both halves in frame), so
7247+ // there is no edge break to mirror -- the search offers one
7248+ // only at a root wholly inside.
7249+ let base_mi = (
7250+ (sb_r & !1) as usize * SB_MI as usize,
7251+ (sb_c & !1) as usize * SB_MI as usize,
7252+ );
7253+ for (((mi_r, mi_c), (w, h)), piece) in
7254+ crate::encode::ab128_pieces(symbol, base_mi).iter().zip(pieces)
7255+ {
7256+ write_inter_block_128_rect(
7257+ &mut enc,
7258+ &mut cdfs,
7259+ &mut neighbours,
7260+ &mut grid,
7261+ (*mi_r, *mi_c),
7262+ (*w, *h),
7263+ piece,
7264+ mi_cols,
7265+ mi_rows,
7266+ tx_select,
7267+ )?;
7268+ }
7269+ SB128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7270+ sb128_none = true;
7271+ continue;
7272+ }
7204 }7273 }
7205 {7274 {
7206 if !sb128 {7275 if !sb128 {
@@ -7449,6 +7518,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
7449 Quadrant::Whole64(_)7518 Quadrant::Whole64(_)
7450 | Quadrant::Whole128(_)7519 | Quadrant::Whole128(_)
7451 | Quadrant::Rect128(..)7520 | Quadrant::Rect128(..)
7521+ | Quadrant::Ab128(..)
7452 | Quadrant::Covered => {7522 | Quadrant::Covered => {
7453 return Err(Error::unsupported(7523 return Err(Error::unsupported(
7454 "AV1 tile",7524 "AV1 tile",