forge
Explore
Log in

Don't you dare go Hollow

A 64x64 inter root can code a real residual

Browse files at this commit

236d76c5571083d30540cb16136f567df6828a95Ahmet Kaan GümüşParent: 473ca5c
  • feat
    • a 64x64 inter root can code a real residual
Show full message
feat(av1): a 64x64 inter root can code a real residual

lane-tx64 step 1+2. The charter's premise (a) -- "transform.rs has no
forward TX_64X64" -- is STALE: forward_dct_n::<_, 6> has been there since
the network was written, quantize already drops everything outside the
coded 32x32 corner, and a_64x64_transform_keeps_what_fits_in_its_coded_quarter
round-trips a 64x64 residual through the decoder's own inverse. What was
missing was the two ends around it.

Encoder: code_from_prediction takes a 64-sided block (heap residual only
for that one case, the 4x4..32x32 path keeps its stack array) and hands
back the coded 32x32 corner as its levels, which is what both the pricer
and the writer want. search_skip_64 prices the skip winner's prediction a
second time with a real residual -- one TX_64X64 luma, one TX_32X32 per
chroma plane -- and takes it when it costs less.

Writer: Quadrant::Whole64 no longer refuses a non-skip block; it codes
skip 0, the txfm_split flag at depth 0, and TxbSet::Luma64 + two
Chroma32 planes, the same pair sb_coeff_key_frame_tile's
Superblock::Whole already wrote.

Deferred: compound refs at the 64 root, depth-1 4x32x32 var-tx, intra 64,
edge superblocks -- all still refused/unsearched.
crates/ec-av1/src/encode.rsmodified+109 -6
@@ -410,6 +410,28 @@ fn b64_root() -> bool {
410410 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
411411 }
412412
413+/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
414+/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
415+/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
416+/// lane-b64 shipped, so the two can be measured against each other on the
417+/// same build.
418+fn b64_residual() -> bool {
419+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
420+ crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
421+ });
422+ ENV.unwrap_or(true) && b64_root()
423+}
424+
425+/// How many 64x64 roots came out cheaper with a residual than skipped, since
426+/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
427+/// rather than assuming one (class `gate-blind-to-feature`).
428+static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
429+
430+/// The non-skip 64x64-root count since the last call, and zero it.
431+pub fn take_b64_residual_hits() -> usize {
432+ B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
433+}
434+
413435 /// Whether the encoder searches loop restoration at all (spec 7.17): one
414436 /// Wiener filter per 64x64 luma restoration unit, picked from
415437 /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
@@ -1829,8 +1851,20 @@ impl Plane<'_> {
18291851 bits: 0.0,
18301852 };
18311853 }
1832- let mut residual = [0i32; BLOCK * BLOCK];
1833- let residual = &mut residual[..side * side];
1854+ // A 64x64 root's residual is four times the scratch every other
1855+ // block coder here sizes for [`BLOCK`]; only that one case pays for
1856+ // a heap buffer, so the 4x4..32x32 path keeps its stack array.
1857+ let mut small = [0i32; BLOCK * BLOCK];
1858+ let mut big = if side > BLOCK {
1859+ vec![0i32; side * side]
1860+ } else {
1861+ Vec::new()
1862+ };
1863+ let residual: &mut [i32] = if side > BLOCK {
1864+ &mut big
1865+ } else {
1866+ &mut small[..side * side]
1867+ };
18341868 for row in 0..side {
18351869 for col in 0..side {
18361870 residual[row * side + col] =
@@ -1864,6 +1898,16 @@ impl Plane<'_> {
18641898 .collect()
18651899 };
18661900 let sse = self.block_sse(x, y, side, &reconstruction);
1901+ // A 64-point transform codes only its top-left 32x32 corner (spec
1902+ // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
1903+ // key frame writer takes a 32x32 level grid for one). The inverse
1904+ // above reads the whole 64x64 array, but the price below and the
1905+ // levels the writer takes are that corner.
1906+ let levels = if side > BLOCK {
1907+ coded_corner(&levels, side, BLOCK)
1908+ } else {
1909+ levels
1910+ };
18671911 #[cfg(test)]
18681912 let t = stage_start();
18691913 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
@@ -5657,6 +5701,17 @@ struct Trial {
56575701 bits: f64,
56585702 }
56595703
5704+/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
5705+/// of a 64-point transform that is actually coded (everything outside it is
5706+/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
5707+fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
5708+ let mut out = vec![0i32; to * to];
5709+ for row in 0..to {
5710+ out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
5711+ }
5712+ out
5713+}
5714+
56605715 /// The non-zero levels of a block, as the tile writer takes them.
56615716 fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
56625717 levels
@@ -7282,7 +7337,7 @@ fn search_skip_64(
72827337 }
72837338 }
72847339
7285- let mut best: Option<(f64, InterInfo, [Trial; 3])> = None;
7340+ let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None;
72867341 for (bits, info) in cands {
72877342 let trials = [
72887343 (0usize, x, y, side, true),
@@ -7326,18 +7381,66 @@ fn search_skip_64(
73267381 + trials[2].sse
73277382 + search.lambda * (fixed + bits);
73287383 if best.as_ref().is_none_or(|b| cost < b.0) {
7329- best = Some((cost, info, trials));
7384+ best = Some((cost, bits, info, trials));
73307385 }
73317386 }
7332- let (cost, info, trials) = best?;
7387+ let (skip_cost, bits, info, skip_trials) = best?;
7388+
7389+ // The winner's prediction coded with a REAL residual (lane-tx64): one
7390+ // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
7391+ // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
7392+ // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
7393+ // the skip arm already chose is re-coded: the prediction with the lowest
7394+ // SSE is also the cheapest residual to code, and a second 64x64 motion
7395+ // search per superblock is the wall this root was taken to SAVE.
7396+ //
7397+ // Priced against the skip arm through the same `symbol_bits` path, so the
7398+ // two numbers are comparable: `fixed` charged `skip` coded 1, and this
7399+ // arm charges 0 instead and adds its three planes' coefficient bits.
7400+ let mut chosen = (skip_cost, true, skip_trials);
7401+ if b64_residual() {
7402+ let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
7403+ let residual_trials = [0usize, 1, 2].map(|plane| {
7404+ let (target, px, py, s) = if plane == 0 {
7405+ (&*luma, x, y, side)
7406+ } else {
7407+ (&chroma[plane - 1], x / 2, y / 2, side / 2)
7408+ };
7409+ target.code_from_prediction(
7410+ px,
7411+ py,
7412+ s,
7413+ &chosen.2[plane].reconstruction,
7414+ false,
7415+ search.base_q_idx,
7416+ search.deadzone,
7417+ sets[plane],
7418+ )
7419+ });
7420+ let unskip = symbol_bits(&cdf::SKIP[0], 0) - symbol_bits(&cdf::SKIP[0], 1);
7421+ let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
7422+ let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
7423+ + search.lambda * (fixed + bits + unskip + coeff_bits);
7424+ if cost < skip_cost {
7425+ B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7426+ chosen = (cost, false, residual_trials);
7427+ }
7428+ }
7429+
7430+ let (cost, skip, trials) = chosen;
73337431 luma.commit(x, y, side, &trials[0]);
73347432 chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]);
73357433 chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]);
73367434 Some((
73377435 cost,
73387436 BlockCoeffs {
7339- skip: true,
7437+ skip,
73407438 inter: Some(info),
7439+ // Both grids are 32-sided: the luma one is the 64-point
7440+ // transform's coded corner, the chroma ones are whole TX_32X32.
7441+ luma: if skip { Vec::new() } else { coeffs(&trials[0].levels, BLOCK) },
7442+ u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) },
7443+ v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) },
73417444 ..BlockCoeffs::default()
73427445 },
73437446 ))
crates/ec-av1/src/encoder.rsmodified+69 -0
@@ -2281,6 +2281,75 @@ mod tests {
22812281 }
22822282 }
22832283
2284+ /// The same clip with a DC step between frames (lane-tx64): the 64x64
2285+ /// root still predicts the whole superblock from the last frame, but the
2286+ /// prediction is uniformly off, so the root's NON-skip arm -- one
2287+ /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below
2288+ /// its skip arm and a 64x64 residual is really written. The counter is
2289+ /// the gate (class `gate-blind-to-feature`; the static clip above cannot
2290+ /// reach this arm at all because its prediction is exact), and both
2291+ /// decoders have to reconstruct those coefficients sample-exact -- a
2292+ /// writer that names the wrong coefficient set or the wrong `txfm_split`
2293+ /// desyncs the whole tile here.
2294+ #[test]
2295+ fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {
2296+ let _gate_lock = crate::stream::tests::lock_gate_counters();
2297+ let (width, height) = (256usize, 128usize);
2298+ let still = test_card(width, height, 0);
2299+ let sources: Vec<Picture> = (0..3)
2300+ .map(|t| {
2301+ let mut p = still.clone();
2302+ let step = (t * 6) as u16;
2303+ for v in &mut p.y {
2304+ *v = (*v + step).min(255);
2305+ }
2306+ p
2307+ })
2308+ .collect();
2309+ let config = EncoderConfig {
2310+ width,
2311+ height,
2312+ base_q_idx: 120,
2313+ gop: 8,
2314+ colour: Colour::Bt709Limited,
2315+ tile_cols_log2: 0,
2316+ tile_rows_log2: 0,
2317+ };
2318+ let mut enc = Av1Encoder::new(config).unwrap();
2319+ let mut stream = Vec::new();
2320+ let _ = crate::encode::take_b64_residual_hits();
2321+ for packet in encode_all(&mut enc, &sources) {
2322+ stream.extend_from_slice(&packet.data);
2323+ }
2324+ let residuals = crate::encode::take_b64_residual_hits();
2325+ assert!(
2326+ residuals > 0,
2327+ "a DC-stepped clip coded no 64x64 root with a residual at all"
2328+ );
2329+ eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks");
2330+
2331+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2332+ assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2333+ if !have_ffmpeg() {
2334+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
2335+ return;
2336+ }
2337+ let theirs = ffmpeg_decode_luma(&stream, width, height);
2338+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2339+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2340+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2341+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2342+ panic!(
2343+ "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2344+ at % width,
2345+ at / width,
2346+ got[at],
2347+ b[at],
2348+ );
2349+ }
2350+ }
2351+ }
2352+
22842353 #[test]
22852354 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
22862355 let (width, height) = (640usize, 384usize);
crates/ec-av1/src/tile.rsmodified+43 -10
@@ -5558,6 +5558,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
55585558 // derived from luma's, not coded, so it never differs between the two.
55595559 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
55605560 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];
5561+ // A 64x64 root's planes (lane-tx64): TX_64X64 luma -- DCT-only at this
5562+ // size for an inter block too (spec `av1_get_ext_tx_set_type` returns
5563+ // `TX_SET_DCTONLY` for `tx_size_sqr_up == TX_64X64`), so `Luma64` carries
5564+ // no `tx_type` symbol and there is no `Luma64Inter` to write -- and one
5565+ // TX_32X32 per chroma plane.
5566+ let sb64_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
55615567 let scan32 = default_scan(TX32);
55625568 let scan16 = default_scan(TX16);
55635569 let scan8 = default_scan(TX8);
@@ -5611,11 +5617,10 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
56115617 let info = block.inter.ok_or_else(|| {
56125618 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")
56135619 })?;
5614- if !block.skip || info.ref1.is_some() {
5620+ if info.ref1.is_some() {
56155621 return Err(Error::unsupported(
56165622 "AV1 tile",
5617- "a 64x64 root block is coded skip and single-reference \
5618- (a 64x64 residual needs a forward TX_64X64)",
5623+ "a 64x64 root block is coded single-reference",
56195624 ));
56205625 }
56215626 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);
@@ -5624,8 +5629,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
56245629 let has_left = neighbours.has_left(mi_c);
56255630 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
56265631 + usize::from(neighbours.left_skip[mi_r]);
5627- enc.symbol(1, &mut cdfs.skip[skip_ctx]);
5628- write_cdef_idx(&mut enc, (mi_r, mi_c), true);
5632+ enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
5633+ write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
56295634 let ii_ctx = intra_inter_ctx(
56305635 has_above,
56315636 has_left,
@@ -5694,8 +5699,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
56945699 )?;
56955700 if tx_select {
56965701 // A skipped inter block writes no `txfm_split` at all --
5697- // this only publishes the max transform size the reader
5698- // infers for it (`write_tx_syntax_inter`).
5702+ // that call only publishes the max transform size the
5703+ // reader infers for it; an unskipped one writes the
5704+ // `txfm_split` flag, 0 here because a 64x64 root's luma
5705+ // is one whole TX_64X64 (depth 1 is lane-tx64's deferred
5706+ // var-tx arm).
56995707 write_tx_syntax_inter(
57005708 &mut enc,
57015709 &mut cdfs,
@@ -5703,12 +5711,37 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
57035711 (mi_r, mi_c),
57045712 SB,
57055713 true,
5706- true,
5714+ block.skip,
57075715 0,
57085716 );
57095717 }
5710- neighbours.record(sb_at, SB, 0, &zero_grids);
5711- neighbours.record_inter(sb_at, SB, true, true, block_ref(block));
5718+ if block.skip {
5719+ neighbours.record(sb_at, SB, 0, &zero_grids);
5720+ } else {
5721+ // lane-tx64: the 64x64 root's real residual. Luma is one
5722+ // TX_64X64 whose coded quarter is a 32x32 level grid
5723+ // (`TxbSet::Luma64`, `TX32`'s own scan -- the same pair
5724+ // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes),
5725+ // chroma one whole TX_32X32 per plane, and `split` is
5726+ // false because the luma transform covers the block.
5727+ let grids = [
5728+ level_grid(&block.luma, TX32)?,
5729+ level_grid(&block.u, TX32)?,
5730+ level_grid(&block.v, TX32)?,
5731+ ];
5732+ write_block_planes(
5733+ &mut enc,
5734+ &mut cdfs,
5735+ &sb64_planes,
5736+ &grids,
5737+ &[&scan32, &scan32, &scan32],
5738+ &neighbours.around(sb_at, SB),
5739+ 0,
5740+ false,
5741+ );
5742+ neighbours.record_planes(sb_at, SB, 0, &grids, true);
5743+ }
5744+ neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block));
57125745 continue;
57135746 }
57145747 match (has_cols, has_rows) {