forge
Explore
Log in

Don't you dare go Hollow

A real 128x128 PARTITION_NONE root under EC_AV1_SB128

Browse files at this commit

c26b4448e2421b9a4f4ad932d3343eef6c1a34d9Ahmet Kaan GümüşParent: 7d2ddc2
  • feat
    • a real 128x128 PARTITION_NONE root under EC_AV1_SB128
Show full message
feat(av1): a real 128x128 PARTITION_NONE root under EC_AV1_SB128

The 128 superblock root wrote PARTITION_SPLIT by construction, so turning
the sequence bit on bought the extra partition symbols and the forced
loop-restoration unit with no block-count saving at all. The root now
carries a real candidate: one 128x128 inter block, skip-only, single
reference, searched through the same machinery the 64 root uses
(search_skip_64 parameterised by side) and weighed against what its four
superblocks really cost.

The search also walks the roots in the WRITER's own order under a 128
superblock (TL/TR/BL/BR inside each root) instead of plain raster, so
every mv stack and neighbour context is built off blocks the writer has
already coded.

Witness (--ignored, process-global superblock size): 406 128x128 blocks
on an 8-frame 1280x768 pan, sample-exact through our own decoder and
ffmpeg.

Task 0: the NEWMV/NEARMV pricer's drl offer set is enumerated against
the writer's clamp rule (tile::signalled_drl_idx); it was already
clamp-free on its own stack.
crates/ec-av1/src/encode.rsmodified+334 -3
@@ -722,6 +722,16 @@ pub fn take_b64_root_hits() -> usize {
722 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)722 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
723 }723 }
724 724
725+/// How many 128x128 `PARTITION_NONE` roots the search took since the last
726+/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
727+/// is only attributable once the fire count is known.
728+static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
729+
730+/// The 128x128-root count since the last call, and zero it.
731+pub fn take_b128_none_hits() -> usize {
732+ B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
733+}
734+
725 /// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).735 /// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
726 /// Preset-gated: it re-prices the block once per candidate level, so it buys736 /// Preset-gated: it re-prices the block once per candidate level, so it buys
727 /// bits with wall (see `crate::speed::RDOQ` for the per-preset table).737 /// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
@@ -9204,6 +9214,113 @@ fn predict_compound_u8(
9204 blended.iter().map(|&v| v as u8).collect()9214 blended.iter().map(|&v| v as u8).collect()
9205 }9215 }
9206 9216
9217+/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
9218+/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
9219+/// one motion vector where the four 64x64 roots below spend four of each.
9220+///
9221+/// SKIP only (`residual: false`): a 128x128 block's residual is four
9222+/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
9223+/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
9224+/// path for -- offering one here would price a block
9225+/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
9226+/// the same reason: the compound arm at this size is untested against the
9227+/// writer's own `write_compound_block` window.
9228+///
9229+/// Only a root whose whole 128x128 lies inside the true frame AND inside
9230+/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
9231+/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
9232+/// block would have to be ranked over its inside part alone.
9233+///
9234+/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
9235+/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
9236+/// against the four superblocks plus the SPLIT symbol.
9237+#[allow(clippy::too_many_arguments)]
9238+fn search_root_128(
9239+ luma: &mut Plane,
9240+ chroma: &mut [Plane; 2],
9241+ grid: &crate::mvstack::MiGrid,
9242+ (root_r, root_c): (usize, usize),
9243+ // The 32x32-block grid this tile's `blocks` vector is indexed on.
9244+ (rows, cols): (usize, usize),
9245+ // The frame's own mode-info grid, which bounds the root.
9246+ (mi_cols, mi_rows): (u32, u32),
9247+ search: Search<'_>,
9248+ tpl_factors: &Option<Vec<f64>>,
9249+ sb_q: Option<&Vec<u8>>,
9250+ sb_cols: usize,
9251+ tpl_cells_x: usize,
9252+ base_q_idx: u8,
9253+ reference: &Picture,
9254+ fctx: &crate::decode::FrameCtx,
9255+) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9256+ const SIDE: usize = SUPERBLOCK * 2;
9257+ const SIDE_MI: usize = SIDE / 4;
9258+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9259+ let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9260+ if root_r * 2 + 3 >= rows
9261+ || root_c * 2 + 3 >= cols
9262+ || (mi_row + SIDE_MI) as u32 > mi_rows
9263+ || (mi_col + SIDE_MI) as u32 > mi_cols
9264+ || x128 + SIDE > luma.true_width
9265+ || y128 + SIDE > luma.true_height
9266+ {
9267+ return None;
9268+ }
9269+ // One lambda for the whole root, the mean of what its four superblocks
9270+ // would each be searched at -- the 128-vs-four comparison weighs one cost
9271+ // against four, so both sides have to be priced at the same lambda (the
9272+ // same rule the 64 root's own mean-of-sixteen tpl cells follows).
9273+ let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9274+ (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9275+ (None, Some(f)) => {
9276+ let mean = (0..16)
9277+ .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9278+ .sum::<f64>()
9279+ / 16.0;
9280+ search.lambda * mean
9281+ }
9282+ (None, None) => search.lambda,
9283+ };
9284+ let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9285+ .iter()
9286+ .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9287+ .sum::<f64>()
9288+ / 4.0;
9289+ let root_search = Search { lambda, ..search };
9290+ let stack = find_mv_stack(
9291+ grid,
9292+ mi_row,
9293+ mi_col,
9294+ SIDE_MI,
9295+ SIDE_MI,
9296+ LAST_FRAME,
9297+ mi_cols as usize,
9298+ mi_rows as usize,
9299+ );
9300+ let base = snapshot(luma, chroma, (x128, y128), SIDE);
9301+ let found = search_skip_64(
9302+ luma,
9303+ chroma,
9304+ (x128, y128),
9305+ SIDE,
9306+ &root_search,
9307+ false,
9308+ reference,
9309+ &stack,
9310+ &[],
9311+ fctx,
9312+ );
9313+ let (cost, block) = found?;
9314+ let after = snapshot(luma, chroma, (x128, y128), SIDE);
9315+ restore(luma, chroma, (x128, y128), SIDE, &base);
9316+ Some((
9317+ cost + lambda * crate::tile::partition_bits(SIDE, false),
9318+ lambda,
9319+ block,
9320+ after,
9321+ ))
9322+}
9323+
9207 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):9324 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
9208 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded9325 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
9209 /// SKIP, priced through the same `symbol_bits` path every other candidate9326 /// SKIP, priced through the same `symbol_bits` path every other candidate
@@ -9218,6 +9335,12 @@ fn search_skip_64(
9218 luma: &mut Plane,9335 luma: &mut Plane,
9219 chroma: &mut [Plane; 2],9336 chroma: &mut [Plane; 2],
9220 (x, y): (usize, usize),9337 (x, y): (usize, usize),
9338+ // The root's side in samples: [`SUPERBLOCK`] at a 64 root, twice that at
9339+ // the 128 one [`search_root_128`] drives (lane-b128). Every trial below
9340+ // is a square of this side and its half in chroma, and the residual arm
9341+ // is only ever asked for at 64 -- a 128 block's residual is four
9342+ // TX_64X64 units the writer has no path for.
9343+ side: usize,
9221 search: &Search,9344 search: &Search,
9222 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on9345 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
9223 // screen content -- see that function's doc).9346 // screen content -- see that function's doc).
@@ -9230,7 +9353,7 @@ fn search_skip_64(
9230 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],9353 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9231 fctx: &crate::decode::FrameCtx,9354 fctx: &crate::decode::FrameCtx,
9232 ) -> Option<(f64, BlockCoeffs)> {9355 ) -> Option<(f64, BlockCoeffs)> {
9233- let side = SUPERBLOCK;9356+ debug_assert!(side == SUPERBLOCK || !residual, "a 128 root has no residual arm");
9234 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);9357 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
9235 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);9358 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
9236 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);9359 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
@@ -11459,8 +11582,63 @@ pub(crate) fn encode_inter_frame(
11459 rect.mi_col1 as usize,11582 rect.mi_col1 as usize,
11460 );11583 );
11461 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();11584 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
11462- for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {11585+ // lane-b128: under a 128x128 superblock the search walks the roots the
11463- for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {11586+ // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
11587+ // not plain raster -- a search that visits BL before TR builds every mv
11588+ // stack and neighbour context off blocks the writer has not coded yet,
11589+ // which is what made the write-time drl clamp fire at all (lane-sb128b).
11590+ // At a 64 superblock the two orders are identical and this is the same
11591+ // raster loop as before.
11592+ let sb128_search = sb128_on();
11593+ let root_step = if sb128_search { 2 } else { 1 };
11594+ let mut roots: Vec<(usize, usize)> = Vec::new();
11595+ {
11596+ let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
11597+ let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
11598+ let mut r = r0;
11599+ while r < r1 {
11600+ let mut c = c0;
11601+ while c < c1 {
11602+ roots.push((r, c));
11603+ c += root_step;
11604+ }
11605+ r += root_step;
11606+ }
11607+ }
11608+ for (root_r, root_c) in roots {
11609+ // The 64x64 cells of this root, in the writer's own order.
11610+ let cells: Vec<(usize, usize)> = if sb128_search {
11611+ [(0, 0), (0, 1), (1, 0), (1, 1)]
11612+ .into_iter()
11613+ .map(|(dr, dc)| (root_r + dr, root_c + dc))
11614+ .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
11615+ .collect()
11616+ } else {
11617+ vec![(root_r, root_c)]
11618+ };
11619+ // What the four cells below really cost, against which the whole
11620+ // 128x128 candidate is weighed.
11621+ let mark128 = blocks.len();
11622+ let mut root_cost = 0.0f64;
11623+ let root128 = sb128_search
11624+ .then(|| search_root_128(
11625+ &mut luma,
11626+ &mut chroma,
11627+ &grid,
11628+ (root_r, root_c),
11629+ (rows, cols),
11630+ (header.mi_cols, header.mi_rows),
11631+ search,
11632+ &tpl_factors,
11633+ sb_q.as_ref(),
11634+ sb_cols,
11635+ tpl_cells_x,
11636+ base_q_idx,
11637+ reference,
11638+ fctx,
11639+ ))
11640+ .flatten();
11641+ for (sb_r, sb_c) in cells {
11464 // lane-b64: the whole superblock as ONE 64x64 block, tried before11642 // lane-b64: the whole superblock as ONE 64x64 block, tried before
11465 // its quadrants are (`search_skip_64`) and compared against the11643 // its quadrants are (`search_skip_64`) and compared against the
11466 // four of them below. Only a superblock wholly inside the true11644 // four of them below. Only a superblock wholly inside the true
@@ -11559,6 +11737,7 @@ pub(crate) fn encode_inter_frame(
11559 &mut luma,11737 &mut luma,
11560 &mut chroma,11738 &mut chroma,
11561 (x64, y64),11739 (x64, y64),
11740+ SUPERBLOCK,
11562 &sb_search,11741 &sb_search,
11563 b64_residual() && !screen,11742 b64_residual() && !screen,
11564 reference,11743 reference,
@@ -12028,6 +12207,27 @@ pub(crate) fn encode_inter_frame(
12028 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);12207 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
12029 blocks.push((r32 * cols + c32, Quadrant::Covered));12208 blocks.push((r32 * cols + c32, Quadrant::Covered));
12030 }12209 }
12210+ root_cost += cost64;
12211+ } else {
12212+ root_cost += sb_cost;
12213+ }
12214+ }
12215+ // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
12216+ // `partition_w128` symbol) against what its four superblocks really
12217+ // cost, the same weighing the 64 root does one size down. Both sides
12218+ // carry their own partition symbol, so the comparison is complete.
12219+ if let Some((cost128, lambda128, block, after)) = root128
12220+ && cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)
12221+ {
12222+ B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12223+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
12224+ blocks.truncate(mark128);
12225+ restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
12226+ record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
12227+ blocks.push(((root_r * 2) * cols + root_c * 2, Quadrant::Whole128(block)));
12228+ for q in 1..16 {
12229+ let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
12230+ blocks.push((r32 * cols + c32, Quadrant::Covered));
12031 }12231 }
12032 }12232 }
12033 }12233 }
@@ -12534,6 +12734,57 @@ mod tests {
12534 /// An [`crate::mvstack::MvStack`] with every context at zero and no12734 /// An [`crate::mvstack::MvStack`] with every context at zero and no
12535 /// neighbours, for the pricer tests below to fill the one band each of12735 /// neighbours, for the pricer tests below to fill the one band each of
12536 /// them is about.12736 /// them is about.
12737+ /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
12738+ /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
12739+ /// against the same stack -- an offer the writer clamps prices the
12740+ /// residual against a predictor the decoder never derives, which is the
12741+ /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
12742+ /// side, so the stream stays legal; here the pricer's own offer set is
12743+ /// enumerated, class `enumerate-table-domain`).
12744+ ///
12745+ /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
12746+ #[test]
12747+ fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
12748+ for n in 0..=4usize {
12749+ let mut stack = bare_stack();
12750+ for i in 0..n {
12751+ stack.entries.push(crate::mvstack::StackEntry {
12752+ mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
12753+ weight: 1,
12754+ });
12755+ stack.drl_ctx.push(0);
12756+ }
12757+ stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
12758+ stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
12759+ stack.pred_mv = stack.nearest_mv;
12760+ // Aim the vector at each entry in turn, so every index the offer
12761+ // set holds is the one that wins at least once.
12762+ for target in 0..n.max(1) {
12763+ let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
12764+ let (_, idx) = best_new_mv_syntax(&stack, mv)
12765+ .expect("a zero residual is always codable");
12766+ let idx = usize::from(idx);
12767+ assert_eq!(
12768+ crate::tile::signalled_drl_idx(n, 0, idx),
12769+ idx,
12770+ "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
12771+ );
12772+ }
12773+ // The NEARMV arm's own offer set (`search_inter_block`,
12774+ // `search_skip_64`): indices 1 and 2, offered only when the stack
12775+ // really holds that entry.
12776+ for idx in 1..=2usize {
12777+ if stack.entries.get(idx).is_some() {
12778+ assert_eq!(
12779+ crate::tile::signalled_drl_idx(n, 1, idx),
12780+ idx,
12781+ "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
12782+ );
12783+ }
12784+ }
12785+ }
12786+ }
12787+
12537 fn bare_stack() -> crate::mvstack::MvStack {12788 fn bare_stack() -> crate::mvstack::MvStack {
12538 crate::mvstack::MvStack {12789 crate::mvstack::MvStack {
12539 entries: Default::default(),12790 entries: Default::default(),
@@ -15147,6 +15398,86 @@ mod tests {
15147 ///15398 ///
15148 /// cargo test -p ec-av1 --release --lib -- --ignored \15399 /// cargo test -p ec-av1 --release --lib -- --ignored \
15149 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture15400 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
15401+ /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
15402+ /// and one motion vector where the four 64x64 roots below spend four of
15403+ /// each (cen3's L1). The counter is the gate on the fixture (class
15404+ /// `gate-blind-to-feature`): a green round trip on a clip that never
15405+ /// codes a 128x128 block proves nothing. RED before the search existed
15406+ /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
15407+ /// root by construction).
15408+ ///
15409+ /// Both readers: our own decoder sample-exact against the encoder's
15410+ /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
15411+ /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
15412+ ///
15413+ /// `#[ignore]`: [`force_sb128`] moves a process-global.
15414+ ///
15415+ /// cargo test -p ec-av1 --release --lib -- --ignored \
15416+ /// a_128_superblock_clip_whose_root_search --nocapture
15417+ #[test]
15418+ #[ignore = "sets the process-global superblock size: run it alone"]
15419+ fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
15420+ let _knobs = crate::speed::knob_write();
15421+ if !have_ffmpeg() {
15422+ eprintln!("SKIP: no ffmpeg");
15423+ return;
15424+ }
15425+ force_sb128(true);
15426+ let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
15427+ std::fs::create_dir_all(&dir).unwrap();
15428+ let clip = dir.join("smpte-1280x768.y4m");
15429+ // A slow horizontal pan over a still pattern: whole 128x128 regions
15430+ // share one motion vector, which is exactly what a 128 root can code
15431+ // as one block and four 64 roots cannot.
15432+ let ok = Command::new("ffmpeg")
15433+ .args(["-v", "error", "-y", "-f", "lavfi"])
15434+ .args(["-i", "smptebars=size=1600x768:rate=24"])
15435+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
15436+ .args(["-pix_fmt", "yuv420p"])
15437+ .arg(&clip)
15438+ .status()
15439+ .expect("ffmpeg failed to run")
15440+ .success();
15441+ assert!(ok, "ffmpeg could not write the synthetic clip");
15442+ let (width, height) = (1280usize, 768usize);
15443+ let pictures =
15444+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
15445+ let _ = take_b128_none_hits();
15446+ let _ = crate::tile::take_sb128_none_hits();
15447+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
15448+ let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
15449+ eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
15450+ assert!(
15451+ coded > 0,
15452+ "no 128x128 block was coded on this clip, so it cannot witness the root search",
15453+ );
15454+ assert_eq!(won, coded, "every 128x128 root the search took must be coded as one");
15455+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15456+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
15457+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
15458+ let recon = &frame.reconstruction;
15459+ for (plane, got, want) in [
15460+ ("luma", &dec.y, &recon.y),
15461+ ("U", &dec.u, &recon.u),
15462+ ("V", &dec.v, &recon.v),
15463+ ] {
15464+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
15465+ assert_eq!(
15466+ differ, 0,
15467+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
15468+ own reconstruction",
15469+ got.len()
15470+ );
15471+ }
15472+ }
15473+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
15474+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
15475+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
15476+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
15477+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
15478+ }
15479+ }
15480+
15150 #[test]15481 #[test]
15151 #[ignore = "sets the process-global superblock size: run it alone"]15482 #[ignore = "sets the process-global superblock size: run it alone"]
15152 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {15483 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
crates/ec-av1/src/tile.rsmodified+252 -6
@@ -175,6 +175,12 @@ fn write_sb128_root(
175 sb_c: u32,175 sb_c: u32,
176 mi_cols: u32,176 mi_cols: u32,
177 mi_rows: u32,177 mi_rows: u32,
178+ // lane-b128: the partition the root's own search chose --
179+ // `PARTITION_SPLIT` (the four 64x64 quadrants below, which is every root
180+ // this writer coded before) or `PARTITION_NONE` (one 128x128 block,
181+ // written by the caller right after this). Only offered at a root wholly
182+ // inside the frame, so the gathered edge arms below still code SPLIT.
183+ part: usize,
178 ) {184 ) {
179 SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);185 SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
180 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);186 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
@@ -186,7 +192,7 @@ fn write_sb128_root(
186 eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}");192 eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}");
187 }193 }
188 match (has_cols128, has_rows128) {194 match (has_cols128, has_rows128) {
189- (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w128[ctx128]),195+ (true, true) => enc.symbol(part, &mut cdfs.partition_w128[ctx128]),
190 // As at the 64 root: the gathered CDF is built for the read and196 // As at the 64 root: the gathered CDF is built for the read and
191 // thrown away, so nothing adapts here. Value 1 is SPLIT.197 // thrown away, so nothing adapts here. Value 1 is SPLIT.
192 (true, false) => enc.symbol_fixed(198 (true, false) => enc.symbol_fixed(
@@ -203,6 +209,160 @@ fn write_sb128_root(
203 }209 }
204 }210 }
205 211
212+/// lane-b128: one 128x128 inter block at a `PARTITION_NONE` 128 superblock
213+/// root -- the syntax `decode_inter_block` reads for `sb128_none` (decode.rs
214+/// ~35110): `skip`, `is_inter`, the reference/mode chain at the block's own
215+/// 32x32-mi window, the motion mode, and the transform syntax, with the mi
216+/// grid and every neighbour band published over all thirty-two mi cells.
217+///
218+/// SKIP only, and refused otherwise: a 128x128 block's residual is four
219+/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
220+/// chunk (the chroma units reading the offset-10 `txb_skip` rows), which
221+/// this writer has no path for. A skipped block writes no `cdef_idx` and no
222+/// `delta_q` either, exactly as the 64 root's skip arm does.
223+///
224+/// # Errors
225+/// A block that is intra, or carries a residual, at this size.
226+#[allow(clippy::too_many_arguments)]
227+fn write_inter_block_128(
228+ enc: &mut SymbolEncoder,
229+ cdfs: &mut Cdfs,
230+ neighbours: &mut Neighbours,
231+ grid: &mut MiGrid,
232+ // The root's top-left position in [`SUB`] (16x16) units.
233+ sb_at: (usize, usize),
234+ block: &BlockCoeffs,
235+ mi_cols: u32,
236+ mi_rows: u32,
237+ tx_select: bool,
238+) -> Result<()> {
239+ /// The block's side in samples and in 4x4 mode-info units.
240+ const SIDE: usize = 128;
241+ const SIDE_MI: usize = SIDE / MI;
242+ let info = block.inter.ok_or_else(|| {
243+ Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter")
244+ })?;
245+ if !block.skip {
246+ return Err(Error::unsupported(
247+ "AV1 tile",
248+ "a 128x128 superblock root block carries a residual",
249+ ));
250+ }
251+ let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
252+ let has_above = neighbours.has_above(mi_r);
253+ let has_left = neighbours.has_left(mi_c);
254+ let skip_ctx =
255+ usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
256+ enc.symbol(1, &mut cdfs.skip[skip_ctx]);
257+ write_cdef_idx(enc, (mi_r, mi_c), true);
258+ write_delta_q(enc, cdfs, (mi_r, mi_c), true, true);
259+ let ii_ctx = intra_inter_ctx(
260+ has_above,
261+ has_left,
262+ neighbours.above_inter[mi_c],
263+ neighbours.left_inter[mi_r],
264+ );
265+ enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
266+ write_comp_mode(
267+ enc,
268+ cdfs,
269+ neighbours,
270+ (mi_r, mi_c),
271+ (has_above, has_left),
272+ info.ref1.is_some(),
273+ );
274+ let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
275+ write_compound_block(
276+ enc,
277+ cdfs,
278+ neighbours,
279+ grid,
280+ (mi_r, mi_c),
281+ (SIDE_MI, SIDE_MI),
282+ (has_above, has_left),
283+ info,
284+ (mi_cols as usize, mi_rows as usize),
285+ )?
286+ } else {
287+ write_single_ref(
288+ enc,
289+ cdfs,
290+ info.ref_frame,
291+ neighbours.above_ref[mi_c],
292+ neighbours.above_ref1[mi_c],
293+ neighbours.left_ref[mi_r],
294+ neighbours.left_ref1[mi_r],
295+ );
296+ let stack = find_mv_stack(
297+ grid,
298+ mi_r,
299+ mi_c,
300+ SIDE_MI,
301+ SIDE_MI,
302+ info.ref_frame,
303+ mi_cols as usize,
304+ mi_rows as usize,
305+ );
306+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
307+ (mv, (0, 0), is_new_mv)
308+ };
309+ for dr in 0..SIDE_MI {
310+ for dc in 0..SIDE_MI {
311+ grid.set(
312+ mi_r + dr,
313+ mi_c + dc,
314+ MiInfo {
315+ is_inter: true,
316+ ref_frame: info.ref_frame,
317+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
318+ mv1: mv16(mv1),
319+ mv: mv16(mv),
320+ is_new_mv,
321+ size: SIDE_MI as u8,
322+ size_h: SIDE_MI as u8,
323+ is_global_mv0: false,
324+ is_global_mv1: false,
325+ },
326+ );
327+ }
328+ }
329+ if info.ref1.is_none() {
330+ write_motion_mode(
331+ enc,
332+ cdfs,
333+ grid,
334+ (mi_r, mi_c),
335+ (SIDE_MI, SIDE_MI),
336+ (SIDE, SIDE),
337+ (mi_cols as usize, mi_rows as usize),
338+ info.ref_frame,
339+ block.motion_mode,
340+ )?;
341+ }
342+ if tx_select {
343+ write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);
344+ }
345+ let zero_grids = [
346+ vec![0i32; TX32 * TX32],
347+ vec![0i32; TX32 * TX32],
348+ vec![0i32; TX32 * TX32],
349+ ];
350+ neighbours.record(sb_at, SIDE, 0, &zero_grids);
351+ neighbours.record_inter(sb_at, SIDE, true, true, block_ref(block));
352+ record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
353+ SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
354+ Ok(())
355+}
356+
357+/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
358+/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
359+static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
360+
361+/// The 128x128-block count since the last call, and zero it.
362+pub fn take_sb128_none_hits() -> usize {
363+ SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
364+}
365+
206 /// `read_lr`'s write side, called once at the top of every superblock,366 /// `read_lr`'s write side, called once at the top of every superblock,
207 /// before its partition symbol: writes the units this superblock's own367 /// before its partition symbol: writes the units this superblock's own
208 /// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the368 /// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
@@ -1995,6 +2155,15 @@ pub enum Quadrant {
1995 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma2155 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma
1996 /// plane (lane-tx64, `crate::encode::b64_residual`).2156 /// plane (lane-tx64, `crate::encode::b64_residual`).
1997 Whole64(BlockCoeffs),2157 Whole64(BlockCoeffs),
2158+ /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the
2159+ /// top-left of, coded as one block (`PARTITION_NONE` at the root's
2160+ /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the
2161+ /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered).
2162+ ///
2163+ /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units
2164+ /// interleaved with its chroma per 64x64 mu chunk, which this writer has
2165+ /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
2166+ Whole128(BlockCoeffs),
1998 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's2167 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
1999 /// top-left already coded; it carries no block of its own.2168 /// top-left already coded; it carries no block of its own.
2000 Covered,2169 Covered,
@@ -2004,7 +2173,9 @@ impl Quadrant {
2004 /// The blocks it carries, in the order they are coded.2173 /// The blocks it carries, in the order they are coded.
2005 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {2174 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
2006 match self {2175 match self {
2007- Quadrant::Whole(block) | Quadrant::Whole64(block) => std::slice::from_ref(block),2176+ Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
2177+ std::slice::from_ref(block)
2178+ }
2008 Quadrant::Split(blocks) => blocks.as_slice(),2179 Quadrant::Split(blocks) => blocks.as_slice(),
2009 Quadrant::Covered => &[],2180 Quadrant::Covered => &[],
2010 }2181 }
@@ -2884,7 +3055,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
2884 neighbours.start_row();3055 neighbours.start_row();
2885 }3056 }
2886 if sb128 && sb_start {3057 if sb128 && sb_start {
2887- write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows);3058+ write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows, PARTITION_SPLIT);
2888 }3059 }
2889 {3060 {
2890 if !sb128 {3061 if !sb128 {
@@ -3001,7 +3172,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
3001 match quadrant {3172 match quadrant {
3002 // A 64x64 root is an INTER-frame partition; a3173 // A 64x64 root is an INTER-frame partition; a
3003 // key frame codes one as `Superblock::Whole`.3174 // key frame codes one as `Superblock::Whole`.
3004- Quadrant::Whole64(_) | Quadrant::Covered => {3175+ Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => {
3005 return Err(Error::unsupported(3176 return Err(Error::unsupported(
3006 "AV1 tile",3177 "AV1 tile",
3007 "a key frame codes a 64x64 block as `Superblock::Whole`",3178 "a key frame codes a 64x64 block as `Superblock::Whole`",
@@ -4625,6 +4796,10 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
4625 .iter()4796 .iter()
4626 .map(|q| {4797 .map(|q| {
4627 let side = match q {4798 let side = match q {
4799+ // lane-b128: a 128x128 root is SKIP by construction (the
4800+ // writer refuses a residual at that size), so it names no
4801+ // coefficients on any plane.
4802+ Quadrant::Whole128(_) => return 0.0,
4628 Quadrant::Whole(_) => 32,4803 Quadrant::Whole(_) => 32,
4629 Quadrant::Split(_) => 16,4804 Quadrant::Split(_) => 16,
4630 // lane-tx64: a 64x64 root that codes a residual pays for one4805 // lane-tx64: a 64x64 root that codes a residual pays for one
@@ -5231,6 +5406,8 @@ pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
5231 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));5406 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
5232 let cdfs = &*CDFS;5407 let cdfs = &*CDFS;
5233 let cdf: &[u16] = match side {5408 let cdf: &[u16] = match side {
5409+ // lane-b128: the 128 superblock root's own eight-symbol alphabet.
5410+ 128 => &cdfs.partition_w128[0],
5234 SB => &cdfs.partition_w64[0],5411 SB => &cdfs.partition_w64[0],
5235 BLOCK => &cdfs.partition_w32[0],5412 BLOCK => &cdfs.partition_w32[0],
5236 TX8 => &cdfs.partition_w8[0],5413 TX8 => &cdfs.partition_w8[0],
@@ -5994,6 +6171,19 @@ pub(crate) fn take_drl_hits() -> [usize; 4] {
5994 /// signalled index 1 and priced the residual against `pred_mv`, and the6171 /// signalled index 1 and priced the residual against `pred_mv`, and the
5995 /// decoder's MV silently drifted a whole frame before the drl symbols6172 /// decoder's MV silently drifted a whole frame before the drl symbols
5996 /// desynced).6173 /// desynced).
6174+/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack
6175+/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and
6176+/// each one needs a further entry to advance into (spec 5.11.24's
6177+/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`).
6178+///
6179+/// A search that offers an index this clamps prices its residual against a
6180+/// predictor the decoder never derives (lane-sb128b's silent MV drift); the
6181+/// pricer's own offer set is enumerated against this rule by
6182+/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`.
6183+pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize {
6184+ target.min(start + 2).min(entries.saturating_sub(1)).max(start)
6185+}
6186+
5997 fn write_drl_idx(6187 fn write_drl_idx(
5998 enc: &mut SymbolEncoder,6188 enc: &mut SymbolEncoder,
5999 cdfs: &mut Cdfs,6189 cdfs: &mut Cdfs,
@@ -6001,6 +6191,17 @@ fn write_drl_idx(
6001 start: usize,6191 start: usize,
6002 target: usize,6192 target: usize,
6003 ) -> usize {6193 ) -> usize {
6194+ debug_assert_eq!(
6195+ signalled_drl_idx(stack.entries.len(), start, target),
6196+ {
6197+ let mut i = start;
6198+ while i < start + 2 && stack.entries.len() > i + 1 && i < target {
6199+ i += 1;
6200+ }
6201+ i
6202+ },
6203+ "the drl clamp rule and the writer's own walk disagree",
6204+ );
6004 let mut idx = start;6205 let mut idx = start;
6005 while idx < start + 2 && stack.entries.len() > idx + 1 {6206 while idx < start + 2 && stack.entries.len() > idx + 1 {
6006 let advance = idx < target;6207 let advance = idx < target;
@@ -6257,6 +6458,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6257 ];6458 ];
6258 6459
6259 let sb128 = sb128_armed();6460 let sb128 = sb128_armed();
6461+ // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was
6462+ // just written, so the root's remaining 64x64 cells code nothing.
6463+ let mut sb128_none = false;
6260 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are6464 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
6261 // written in libaom's own TL/TR/BL/BR order, the root's restoration units6465 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
6262 // and partition symbol first; at a 64 one this is plain raster and every6466 // and partition symbol first; at a 64 one this is plain raster and every
@@ -6271,8 +6475,50 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6271 if row_start {6475 if row_start {
6272 neighbours.start_row();6476 neighbours.start_row();
6273 }6477 }
6478+ if sb_start {
6479+ sb128_none = false;
6480+ }
6481+ // lane-b128: the remaining three 64x64 cells of a root the search
6482+ // left WHOLE carry no syntax at all -- the same skip the decoder's
6483+ // own `sb128_none` runs.
6484+ if sb128_none {
6485+ continue;
6486+ }
6274 if sb128 && sb_start {6487 if sb128 && sb_start {
6275- write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows);6488+ // The 128x128 block a `PARTITION_NONE` root carries, held by the
6489+ // top-left 32x32 entry of the root's sixteen.
6490+ let root_block = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
6491+ .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize])
6492+ .and_then(|q| match q {
6493+ Quadrant::Whole128(block) => Some(block),
6494+ _ => None,
6495+ });
6496+ write_sb128_root(
6497+ &mut enc,
6498+ &mut cdfs,
6499+ &neighbours,
6500+ sb_r,
6501+ sb_c,
6502+ mi_cols,
6503+ mi_rows,
6504+ if root_block.is_some() { PARTITION_NONE } else { PARTITION_SPLIT },
6505+ );
6506+ if let Some(block) = root_block {
6507+ let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
6508+ write_inter_block_128(
6509+ &mut enc,
6510+ &mut cdfs,
6511+ &mut neighbours,
6512+ &mut grid,
6513+ at128,
6514+ block,
6515+ mi_cols,
6516+ mi_rows,
6517+ tx_select,
6518+ )?;
6519+ sb128_none = true;
6520+ continue;
6521+ }
6276 }6522 }
6277 {6523 {
6278 if !sb128 {6524 if !sb128 {
@@ -6518,7 +6764,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
6518 let block = match site {6764 let block = match site {
6519 // Already coded by the `Whole64` above -- but only inside6765 // Already coded by the `Whole64` above -- but only inside
6520 // a superblock that really carried one.6766 // a superblock that really carried one.
6521- Quadrant::Whole64(_) | Quadrant::Covered => {6767+ Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => {
6522 return Err(Error::unsupported(6768 return Err(Error::unsupported(
6523 "AV1 tile",6769 "AV1 tile",
6524 "a `Whole64`/`Covered` quadrant needs its superblock's \6770 "a `Whole64`/`Covered` quadrant needs its superblock's \