forge
Explore
Log in

Don't you dare go Hollow

The 128 rect root and the four-superblock arm pay for the delta_q group they code

Browse files at this commit

dc9d340c5817b42739073777144498ce3b61ace9Ahmet Kaan GümüşParent: b4cfa09
  • fix
    • the 128 rect root and the four-superblock arm pay for the delta_q group they code
Show full message
fix(av1): the 128 rect root and the four-superblock arm pay for the delta_q group they code

lane-rectdq. write_delta_q codes its symbol group for every shape but a
SKIPPED whole-superblock PARTITION_NONE root, so the 128 HORZ/VERT
candidate and the four 64 superblocks under a 128 grid were both priced
as if the group were free while only the NONE root really is.

delta_q_bits prices the writer's own three pieces through a pricing
coder (the escape literals are equiprobable symbols, not free bits), and
delta_q_bits_at_root charges it once per root, at the root's own sb_q
cell against the previous 128 root's target standing in for the writer's
CurrentQIndex. EC_AV1_RECTDQ=0 is the control.

A unit witness enumerates delta_q_abs steps -20..=20 against
write_delta_q's bit account; the two agree to 1e-9.
crates/ec-av1/src/encode.rsmodified+124 -3
@@ -798,6 +798,93 @@ fn b128_rect() -> bool {
798 ENV.unwrap_or(true) && b128_root()798 ENV.unwrap_or(true) && b128_root()
799 }799 }
800 800
801+/// lane-rectdq: whether the delta_q symbol group is priced on the root
802+/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
803+/// attribution control (the pre-lane pricing, where a 128 rect root and the
804+/// four-superblock arm were both priced as if the group were free).
805+fn rectdq() -> bool {
806+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
807+ crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0")
808+ });
809+ ENV.unwrap_or(true)
810+}
811+
812+/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
813+/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
814+/// `res` -- the same three pieces that writer codes, in its order: the
815+/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
816+/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
817+/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
818+/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
819+pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
820+ if res <= 0 {
821+ return 0.0;
822+ }
823+ /// spec `DELTA_Q_SMALL`, as in the writer.
824+ const DELTA_Q_SMALL: usize = 3;
825+ let reduced = (target - cur) / res;
826+ let abs = reduced.unsigned_abs() as usize;
827+ // A pricing coder, not a sum of table entries: the escape's literal bits
828+ // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
829+ // floor, so each really costs a little over one bit (class
830+ // `price-the-narrowing-not-the-table`). Read off the same
831+ // `SymbolEncoder::bits` account the writer's own coder keeps.
832+ let mut enc = crate::msac::SymbolEncoder::pricer();
833+ enc.reset_bits();
834+ enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
835+ if abs >= DELTA_Q_SMALL {
836+ let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
837+ enc.literal(rem_bits - 1, 3);
838+ enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
839+ }
840+ if abs != 0 {
841+ enc.literal(u32::from(reduced < 0), 1);
842+ }
843+ enc.bits()
844+}
845+
846+/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
847+/// superblock units): the group every root shape but a SKIPPED
848+/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
849+/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
850+/// superblock under a 128 grid is that.
851+///
852+/// The target is the root's own cell of the `sb_q` grid, exactly the entry
853+/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
854+/// the writer's `plan.cur` only advances at the roots that really code a
855+/// group, and which those are is decided by this very comparison -- so the
856+/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
857+/// `base_q_idx` at the first root of the frame, which is also the writer's
858+/// own per-tile reset). Wrong only where a neighbouring root came out a
859+/// skipped NONE block, and then only by the difference of two adjacent tpl
860+/// cells.
861+fn delta_q_bits_at_root(
862+ sb_q: Option<&Vec<u8>>,
863+ sb_cols: usize,
864+ base_q_idx: u8,
865+ res: i32,
866+ (root_r, root_c): (usize, usize),
867+) -> f64 {
868+ if !rectdq() || res <= 0 {
869+ return 0.0;
870+ }
871+ let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
872+ return 0.0;
873+ };
874+ let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
875+ let target = at(root_r, root_c);
876+ let cur = if root_c >= 2 {
877+ at(root_r, root_c - 2)
878+ } else if root_r >= 2 {
879+ // The last 128 root of the row above, i.e. the previous one in the
880+ // writer's raster walk.
881+ at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
882+ } else {
883+ i32::from(base_q_idx)
884+ };
885+ delta_q_bits(target, cur, res)
886+}
887+
801 /// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)888 /// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
802 /// halves since the last take (class `gate-blind-to-feature`).889 /// 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);890 static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -9567,6 +9654,9 @@ fn search_root_128(
9567 sb_cols: usize,9654 sb_cols: usize,
9568 tpl_cells_x: usize,9655 tpl_cells_x: usize,
9569 base_q_idx: u8,9656 base_q_idx: u8,
9657+ // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
9658+ // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
9659+ dq_res: i32,
9570 reference: &Picture,9660 reference: &Picture,
9571 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,9661 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
9572 // built by the caller off the same grid the tile writer rebuilds its9662 // built by the caller off the same grid the tile writer rebuilds its
@@ -9724,8 +9814,16 @@ fn search_root_128(
9724 }9814 }
9725 let after = snapshot(luma, chroma, (x128, y128), SIDE);9815 let after = snapshot(luma, chroma, (x128, y128), SIDE);
9726 restore(luma, chroma, (x128, y128), SIDE, &base);9816 restore(luma, chroma, (x128, y128), SIDE, &base);
9817+ // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
9818+ // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
9819+ // residual arm above codes it like every other block does.
9820+ let dq = if block.skip {
9821+ 0.0
9822+ } else {
9823+ delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
9824+ };
9727 Some((9825 Some((
9728- cost + lambda * crate::tile::partition_bits(SIDE, false),9826+ cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
9729 lambda,9827 lambda,
9730 block,9828 block,
9731 after,9829 after,
@@ -9762,6 +9860,8 @@ fn search_root_128_rect(
9762 sb_cols: usize,9860 sb_cols: usize,
9763 tpl_cells_x: usize,9861 tpl_cells_x: usize,
9764 base_q_idx: u8,9862 base_q_idx: u8,
9863+ // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
9864+ dq_res: i32,
9765 reference: &Picture,9865 reference: &Picture,
9766 // The `LAST` + extra-reference pairs offered at this root; only the9866 // The `LAST` + extra-reference pairs offered at this root; only the
9767 // reference and its picture are read here, since each HALF derives its9867 // reference and its picture are read here, since each HALF derives its
@@ -9883,8 +9983,13 @@ fn search_root_128_rect(
9883 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);9983 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
9884 let symbol = if horz { 1 } else { 2 };9984 let symbol = if horz { 1 } else { 2 };
9885 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;9985 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
9986+ // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
9987+ // codes the delta_q group whether it is skipped or not
9988+ // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
9989+ // half is at a non-origin mi and codes none.
9990+ let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
9886 Some((9991 Some((
9887- cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),9992+ cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
9888 lambda,9993 lambda,
9889 [b0, b1],9994 [b0, b1],
9890 after,9995 after,
@@ -12465,6 +12570,9 @@ pub(crate) fn encode_inter_frame(
12465 header.delta.q_present = true;12570 header.delta.q_present = true;
12466 header.delta.q_res = res.trailing_zeros() as u8;12571 header.delta.q_res = res.trailing_zeros() as u8;
12467 }12572 }
12573+ // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
12574+ // below, so the root search prices the group the writer really codes.
12575+ let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
12468 if let Some(g) = &sb_q {12576 if let Some(g) = &sb_q {
12469 let mut levels: Vec<u8> = g.clone();12577 let mut levels: Vec<u8> = g.clone();
12470 levels.sort_unstable();12578 levels.sort_unstable();
@@ -12616,6 +12724,7 @@ pub(crate) fn encode_inter_frame(
12616 sb_cols,12724 sb_cols,
12617 tpl_cells_x,12725 tpl_cells_x,
12618 base_q_idx,12726 base_q_idx,
12727+ dq_res,
12619 reference,12728 reference,
12620 &root_compound,12729 &root_compound,
12621 fctx,12730 fctx,
@@ -12645,6 +12754,7 @@ pub(crate) fn encode_inter_frame(
12645 sb_cols,12754 sb_cols,
12646 tpl_cells_x,12755 tpl_cells_x,
12647 base_q_idx,12756 base_q_idx,
12757+ dq_res,
12648 reference,12758 reference,
12649 &root_compound,12759 &root_compound,
12650 horz,12760 horz,
@@ -13251,8 +13361,19 @@ pub(crate) fn encode_inter_frame(
13251 cands.retain(|c| c.2.is_some());13361 cands.retain(|c| c.2.is_some());
13252 }13362 }
13253 cands.sort_by(|a, b| a.0.total_cmp(&b.0));13363 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13364+ // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
13365+ // superblock arm codes the delta_q group too -- the Whole64 writer
13366+ // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
13367+ // with `!sb128_armed()`) and every smaller shape below it pass
13368+ // `is_whole_sb = false` under a 128 grid, so the arm's first
13369+ // (root-origin) superblock codes the group even when skipped. Only the skipped 128
13370+ // NONE root escapes it, so the split side is charged here at the same
13371+ // root lambda the candidates are priced with.
13372+ let split_dq =
13373+ delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
13254 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()13374 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
13255- && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)13375+ && (cost128
13376+ < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
13256 // The witness knobs take the root whatever it costs, so the13377 // The witness knobs take the root whatever it costs, so the
13257 // forced block really reaches the writer.13378 // forced block really reaches the writer.
13258 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)13379 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
crates/ec-av1/src/tile.rsmodified+42 -0
@@ -10869,4 +10869,46 @@ mod tests {
10869 "KF_Y_MODE's different probabilities must decode a different mode"10869 "KF_Y_MODE's different probabilities must decode a different mode"
10870 );10870 );
10871 }10871 }
10872+
10873+ /// lane-rectdq witness: [`crate::encode::delta_q_bits`] prices exactly
10874+ /// what [`write_delta_q`] writes, over the whole `delta_q_abs` domain
10875+ /// (0..=20 steps, both signs -- the escape literal pair starts at 3 and
10876+ /// its `rem_bits` widens at 4, 5, 9 and 17). The writer is run into a
10877+ /// PRICING coder whose account (`SymbolEncoder::bits`) is the same
10878+ /// arithmetic-coder cost the pricer's `symbol_bits` sums, so the two
10879+ /// agree to floating-point noise, not to a tolerance band.
10880+ ///
10881+ /// Both sides read the DEFAULT `delta_q` row: the writer's `cdfs` is
10882+ /// rebuilt per case, exactly as every tile's is armed before its first
10883+ /// superblock.
10884+ #[test]
10885+ fn the_delta_q_pricer_matches_the_writer_over_the_whole_domain() {
10886+ const RES: i32 = 4;
10887+ const CUR: i32 = 128;
10888+ for steps in -20i32..=20 {
10889+ let target = CUR + steps * RES;
10890+ arm_delta_q(RES, 1, vec![u8::try_from(target).expect("in range")], 128);
10891+ let mut cdfs = Cdfs::new(2);
10892+ let mut enc = SymbolEncoder::pricer();
10893+ enc.reset_bits();
10894+ // `is_whole_sb = false`: the rect half / 64-superblock shape,
10895+ // the one whose pricer this witnesses.
10896+ write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
10897+ let written = enc.bits();
10898+ let priced = crate::encode::delta_q_bits(target, CUR, RES);
10899+ assert!(
10900+ (written - priced).abs() < 1e-9,
10901+ "steps {steps}: writer {written} bits, pricer {priced}"
10902+ );
10903+ }
10904+ // Disarmed plan: the writer codes nothing and the pricer charges
10905+ // nothing.
10906+ arm_delta_q(0, 1, Vec::new(), 128);
10907+ let mut cdfs = Cdfs::new(2);
10908+ let mut enc = SymbolEncoder::pricer();
10909+ enc.reset_bits();
10910+ write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
10911+ assert!(enc.bits().abs() < 1e-9, "a disarmed plan writes no symbol");
10912+ assert!((crate::encode::delta_q_bits(200, 128, 0)).abs() < 1e-9);
10913+ }
10872 }10914 }