diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index ec187f2c..bfe61c92 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -410,6 +410,28 @@ fn b64_root() -> bool { ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT)) } +/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the +/// winner's prediction through one TX_64X64 luma transform and two TX_32X32 +/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root +/// lane-b64 shipped, so the two can be measured against each other on the +/// same build. +fn b64_residual() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0") + }); + ENV.unwrap_or(true) && b64_root() +} + +/// How many 64x64 roots came out cheaper with a residual than skipped, since +/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate +/// rather than assuming one (class `gate-blind-to-feature`). +static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The non-skip 64x64-root count since the last call, and zero it. +pub fn take_b64_residual_hits() -> usize { + B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// Whether the encoder searches loop restoration at all (spec 7.17): one /// Wiener filter per 64x64 luma restoration unit, picked from /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a @@ -1829,8 +1851,20 @@ impl Plane<'_> { bits: 0.0, }; } - let mut residual = [0i32; BLOCK * BLOCK]; - let residual = &mut residual[..side * side]; + // A 64x64 root's residual is four times the scratch every other + // block coder here sizes for [`BLOCK`]; only that one case pays for + // a heap buffer, so the 4x4..32x32 path keeps its stack array. + let mut small = [0i32; BLOCK * BLOCK]; + let mut big = if side > BLOCK { + vec![0i32; side * side] + } else { + Vec::new() + }; + let residual: &mut [i32] = if side > BLOCK { + &mut big + } else { + &mut small[..side * side] + }; for row in 0..side { for col in 0..side { residual[row * side + col] = @@ -1864,6 +1898,16 @@ impl Plane<'_> { .collect() }; let sse = self.block_sse(x, y, side, &reconstruction); + // A 64-point transform codes only its top-left 32x32 corner (spec + // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the + // key frame writer takes a 32x32 level grid for one). The inverse + // above reads the whole 64x64 array, but the price below and the + // levels the writer takes are that corner. + let levels = if side > BLOCK { + coded_corner(&levels, side, BLOCK) + } else { + levels + }; #[cfg(test)] let t = stage_start(); let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { @@ -5657,6 +5701,17 @@ struct Trial { bits: f64, } +/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part +/// of a 64-point transform that is actually coded (everything outside it is +/// zeroed by [`crate::transform::quantize`] already, so this only reshapes). +fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec { + let mut out = vec![0i32; to * to]; + for row in 0..to { + out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]); + } + out +} + /// The non-zero levels of a block, as the tile writer takes them. fn coeffs(levels: &[i32], side: usize) -> Vec { levels @@ -7282,7 +7337,7 @@ fn search_skip_64( } } - let mut best: Option<(f64, InterInfo, [Trial; 3])> = None; + let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None; for (bits, info) in cands { let trials = [ (0usize, x, y, side, true), @@ -7326,18 +7381,66 @@ fn search_skip_64( + trials[2].sse + search.lambda * (fixed + bits); if best.as_ref().is_none_or(|b| cost < b.0) { - best = Some((cost, info, trials)); + best = Some((cost, bits, info, trials)); } } - let (cost, info, trials) = best?; + let (skip_cost, bits, info, skip_trials) = best?; + + // The winner's prediction coded with a REAL residual (lane-tx64): one + // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the + // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per + // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv + // the skip arm already chose is re-coded: the prediction with the lowest + // SSE is also the cheapest residual to code, and a second 64x64 motion + // search per superblock is the wall this root was taken to SAVE. + // + // Priced against the skip arm through the same `symbol_bits` path, so the + // two numbers are comparable: `fixed` charged `skip` coded 1, and this + // arm charges 0 instead and adds its three planes' coefficient bits. + let mut chosen = (skip_cost, true, skip_trials); + if b64_residual() { + let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; + let residual_trials = [0usize, 1, 2].map(|plane| { + let (target, px, py, s) = if plane == 0 { + (&*luma, x, y, side) + } else { + (&chroma[plane - 1], x / 2, y / 2, side / 2) + }; + target.code_from_prediction( + px, + py, + s, + &chosen.2[plane].reconstruction, + false, + search.base_q_idx, + search.deadzone, + sets[plane], + ) + }); + let unskip = symbol_bits(&cdf::SKIP[0], 0) - symbol_bits(&cdf::SKIP[0], 1); + let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum(); + let cost = residual_trials.iter().map(|t| t.sse).sum::() + + search.lambda * (fixed + bits + unskip + coeff_bits); + if cost < skip_cost { + B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + chosen = (cost, false, residual_trials); + } + } + + let (cost, skip, trials) = chosen; luma.commit(x, y, side, &trials[0]); chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]); chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]); Some(( cost, BlockCoeffs { - skip: true, + skip, inter: Some(info), + // Both grids are 32-sided: the luma one is the 64-point + // transform's coded corner, the chroma ones are whole TX_32X32. + luma: if skip { Vec::new() } else { coeffs(&trials[0].levels, BLOCK) }, + u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) }, + v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) }, ..BlockCoeffs::default() }, )) diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index a63cae93..5810d86f 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -2281,6 +2281,75 @@ mod tests { } } + /// The same clip with a DC step between frames (lane-tx64): the 64x64 + /// root still predicts the whole superblock from the last frame, but the + /// prediction is uniformly off, so the root's NON-skip arm -- one + /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below + /// its skip arm and a 64x64 residual is really written. The counter is + /// the gate (class `gate-blind-to-feature`; the static clip above cannot + /// reach this arm at all because its prediction is exact), and both + /// decoders have to reconstruct those coefficients sample-exact -- a + /// writer that names the wrong coefficient set or the wrong `txfm_split` + /// desyncs the whole tile here. + #[test] + fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (256usize, 128usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..3) + .map(|t| { + let mut p = still.clone(); + let step = (t * 6) as u16; + for v in &mut p.y { + *v = (*v + step).min(255); + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_residual_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let residuals = crate::encode::take_b64_residual_hits(); + assert!( + residuals > 0, + "a DC-stepped clip coded no 64x64 root with a residual at all" + ); + eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half: no ffmpeg"); + return; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } + } + } + #[test] fn every_tile_layout_decodes_sample_exact_through_both_decoders() { let (width, height) = (640usize, 384usize); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 00fe1130..6b322a49 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -5558,6 +5558,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( // derived from luma's, not coded, so it never differs between the two. let intra_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16]; let inter_planes = [TxbSet::Luma32Inter, TxbSet::Chroma16, TxbSet::Chroma16]; + // A 64x64 root's planes (lane-tx64): TX_64X64 luma -- DCT-only at this + // size for an inter block too (spec `av1_get_ext_tx_set_type` returns + // `TX_SET_DCTONLY` for `tx_size_sqr_up == TX_64X64`), so `Luma64` carries + // no `tx_type` symbol and there is no `Luma64Inter` to write -- and one + // TX_32X32 per chroma plane. + let sb64_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; let scan32 = default_scan(TX32); let scan16 = default_scan(TX16); let scan8 = default_scan(TX8); @@ -5611,11 +5617,10 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( let info = block.inter.ok_or_else(|| { Error::unsupported("AV1 tile", "a 64x64 root block is coded inter") })?; - if !block.skip || info.ref1.is_some() { + if info.ref1.is_some() { return Err(Error::unsupported( "AV1 tile", - "a 64x64 root block is coded skip and single-reference \ - (a 64x64 residual needs a forward TX_64X64)", + "a 64x64 root block is coded single-reference", )); } enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[sb_ctx]); @@ -5624,8 +5629,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( let has_left = neighbours.has_left(mi_c); let skip_ctx = usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]); - enc.symbol(1, &mut cdfs.skip[skip_ctx]); - write_cdef_idx(&mut enc, (mi_r, mi_c), true); + enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); + write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip); let ii_ctx = intra_inter_ctx( has_above, has_left, @@ -5694,8 +5699,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( )?; if tx_select { // A skipped inter block writes no `txfm_split` at all -- - // this only publishes the max transform size the reader - // infers for it (`write_tx_syntax_inter`). + // that call only publishes the max transform size the + // reader infers for it; an unskipped one writes the + // `txfm_split` flag, 0 here because a 64x64 root's luma + // is one whole TX_64X64 (depth 1 is lane-tx64's deferred + // var-tx arm). write_tx_syntax_inter( &mut enc, &mut cdfs, @@ -5703,12 +5711,37 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( (mi_r, mi_c), SB, true, - true, + block.skip, 0, ); } - neighbours.record(sb_at, SB, 0, &zero_grids); - neighbours.record_inter(sb_at, SB, true, true, block_ref(block)); + if block.skip { + neighbours.record(sb_at, SB, 0, &zero_grids); + } else { + // lane-tx64: the 64x64 root's real residual. Luma is one + // TX_64X64 whose coded quarter is a 32x32 level grid + // (`TxbSet::Luma64`, `TX32`'s own scan -- the same pair + // `sb_coeff_key_frame_tile`'s `Superblock::Whole` writes), + // chroma one whole TX_32X32 per plane, and `split` is + // false because the luma transform covers the block. + let grids = [ + level_grid(&block.luma, TX32)?, + level_grid(&block.u, TX32)?, + level_grid(&block.v, TX32)?, + ]; + write_block_planes( + &mut enc, + &mut cdfs, + &sb64_planes, + &grids, + &[&scan32, &scan32, &scan32], + &neighbours.around(sb_at, SB), + 0, + false, + ); + neighbours.record_planes(sb_at, SB, 0, &grids, true); + } + neighbours.record_inter(sb_at, SB, block.skip, true, block_ref(block)); continue; } match (has_cols, has_rows) {