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 {
410 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))410 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
411 }411 }
412 412
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+
413 /// Whether the encoder searches loop restoration at all (spec 7.17): one435 /// Whether the encoder searches loop restoration at all (spec 7.17): one
414 /// Wiener filter per 64x64 luma restoration unit, picked from436 /// Wiener filter per 64x64 luma restoration unit, picked from
415 /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a437 /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
@@ -1829,8 +1851,20 @@ impl Plane<'_> {
1829 bits: 0.0,1851 bits: 0.0,
1830 };1852 };
1831 }1853 }
1832- let mut residual = [0i32; BLOCK * BLOCK];1854+ // A 64x64 root's residual is four times the scratch every other
1833- let residual = &mut residual[..side * side];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+ };
1834 for row in 0..side {1868 for row in 0..side {
1835 for col in 0..side {1869 for col in 0..side {
1836 residual[row * side + col] =1870 residual[row * side + col] =
@@ -1864,6 +1898,16 @@ impl Plane<'_> {
1864 .collect()1898 .collect()
1865 };1899 };
1866 let sse = self.block_sse(x, y, side, &reconstruction);1900 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+ };
1867 #[cfg(test)]1911 #[cfg(test)]
1868 let t = stage_start();1912 let t = stage_start();
1869 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {1913 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
@@ -5657,6 +5701,17 @@ struct Trial {
5657 bits: f64,5701 bits: f64,
5658 }5702 }
5659 5703
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+
5660 /// The non-zero levels of a block, as the tile writer takes them.5715 /// The non-zero levels of a block, as the tile writer takes them.
5661 fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {5716 fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
5662 levels5717 levels
@@ -7282,7 +7337,7 @@ fn search_skip_64(
7282 }7337 }
7283 }7338 }
7284 7339
7285- let mut best: Option<(f64, InterInfo, [Trial; 3])> = None;7340+ let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None;
7286 for (bits, info) in cands {7341 for (bits, info) in cands {
7287 let trials = [7342 let trials = [
7288 (0usize, x, y, side, true),7343 (0usize, x, y, side, true),
@@ -7326,18 +7381,66 @@ fn search_skip_64(
7326 + trials[2].sse7381 + trials[2].sse
7327 + search.lambda * (fixed + bits);7382 + search.lambda * (fixed + bits);
7328 if best.as_ref().is_none_or(|b| cost < b.0) {7383 if best.as_ref().is_none_or(|b| cost < b.0) {
7329- best = Some((cost, info, trials));7384+ best = Some((cost, bits, info, trials));
7330 }7385 }
7331 }7386 }
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;
7333 luma.commit(x, y, side, &trials[0]);7431 luma.commit(x, y, side, &trials[0]);
7334 chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]);7432 chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]);
7335 chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]);7433 chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]);
7336 Some((7434 Some((
7337 cost,7435 cost,
7338 BlockCoeffs {7436 BlockCoeffs {
7339- skip: true,7437+ skip,
7340 inter: Some(info),7438 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) },
7341 ..BlockCoeffs::default()7444 ..BlockCoeffs::default()
7342 },7445 },
7343 ))7446 ))
crates/ec-av1/src/encoder.rsmodified+69 -0
@@ -2281,6 +2281,75 @@ mod tests {
2281 }2281 }
2282 }2282 }
2283 2283
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+
2284 #[test]2353 #[test]
2285 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {2354 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
2286 let (width, height) = (640usize, 384usize);2355 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(
5558 // derived from luma's, not coded, so it never differs between the two.5558 // derived from luma's, not coded, so it never differs between the two.
5559 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];5559 let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
5560 let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16];5560 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];
5561 let scan32 = default_scan(TX32);5567 let scan32 = default_scan(TX32);
5562 let scan16 = default_scan(TX16);5568 let scan16 = default_scan(TX16);
5563 let scan8 = default_scan(TX8);5569 let scan8 = default_scan(TX8);
@@ -5611,11 +5617,10 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
5611 let info = block.inter.ok_or_else(|| {5617 let info = block.inter.ok_or_else(|| {
5612 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")5618 Error::unsupported("AV1 tile", "a 64x64 root block is coded inter")
5613 })?;5619 })?;
5614- if !block.skip || info.ref1.is_some() {5620+ if info.ref1.is_some() {
5615 return Err(Error::unsupported(5621 return Err(Error::unsupported(
5616 "AV1 tile",5622 "AV1 tile",
5617- "a 64x64 root block is coded skip and single-reference \5623+ "a 64x64 root block is coded single-reference",
5618- (a 64x64 residual needs a forward TX_64X64)",
5619 ));5624 ));
5620 }5625 }
5621 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);5626 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]);
@@ -5624,8 +5629,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
5624 let has_left = neighbours.has_left(mi_c);5629 let has_left = neighbours.has_left(mi_c);
5625 let skip_ctx = usize::from(neighbours.above_skip[mi_c])5630 let skip_ctx = usize::from(neighbours.above_skip[mi_c])
5626 + usize::from(neighbours.left_skip[mi_r]);5631 + usize::from(neighbours.left_skip[mi_r]);
5627- enc.symbol(1, &mut cdfs.skip[skip_ctx]);5632+ enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
5628- write_cdef_idx(&mut enc, (mi_r, mi_c), true);5633+ write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
5629 let ii_ctx = intra_inter_ctx(5634 let ii_ctx = intra_inter_ctx(
5630 has_above,5635 has_above,
5631 has_left,5636 has_left,
@@ -5694,8 +5699,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
5694 )?;5699 )?;
5695 if tx_select {5700 if tx_select {
5696 // A skipped inter block writes no `txfm_split` at all --5701 // A skipped inter block writes no `txfm_split` at all --
5697- // this only publishes the max transform size the reader5702+ // that call only publishes the max transform size the
5698- // infers for it (`write_tx_syntax_inter`).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).
5699 write_tx_syntax_inter(5707 write_tx_syntax_inter(
5700 &mut enc,5708 &mut enc,
5701 &mut cdfs,5709 &mut cdfs,
@@ -5703,12 +5711,37 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
5703 (mi_r, mi_c),5711 (mi_r, mi_c),
5704 SB,5712 SB,
5705 true,5713 true,
5706- true,5714+ block.skip,
5707 0,5715 0,
5708 );5716 );
5709 }5717 }
5710- neighbours.record(sb_at, SB, 0, &zero_grids);5718+ if block.skip {
5711- neighbours.record_inter(sb_at, SB, true, true, block_ref(block));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));
5712 continue;5745 continue;
5713 }5746 }
5714 match (has_cols, has_rows) {5747 match (has_cols, has_rows) {