diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 6c5fe0f7..0c655fef 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -41,10 +41,11 @@ use crate::tile::{ BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits, }; use crate::transform::{ - TxType, dequant_and_inverse_typed_wh, forward_and_quantize, - forward_and_quantize_scaled, forward_and_quantize_typed, + TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed, forward_and_quantize_typed_scaled, }; +#[cfg(test)] +use crate::transform::forward_and_quantize; /// The side of the larger of the two luma blocks this encoder codes, in /// samples. @@ -285,6 +286,102 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] } } +/// The transform types an INTER luma transform unit of `set` may be coded +/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every +/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3` +/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two +/// types, a symbol the writer already codes and never varied. 64x64 codes no +/// `tx_type` symbol at all, so it is not offered one. +/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the +/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars +/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 -> +/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its +/// loudest, and restricting the offer to 16x16 and below does not soften it +/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the +/// intra search, palette and intrabc stand behind: a non-screen frame is +/// byte-identical to the encoder before the lane. +/// +/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16` +/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT` +/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else +/// on for every frame at every size. +pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] { + const DCT: [TxType; 1] = [TxType::DctDct]; + const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx]; + let mode = inter_tx_type_search(); + let on = match mode { + InterTxSearch::Off => false, + InterTxSearch::Screen => screen, + InterTxSearch::All | InterTxSearch::Le16 => true, + }; + match set { + TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3, + TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3, + _ => &DCT, + } +} + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum InterTxSearch { + Off, + Screen, + /// 16x16 and below only. + Le16, + All, +} + +/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the +/// environment and the preset (`u8::MAX` = unset), the shape +/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness +/// that has to see a non-`DCT_DCT` inter unit turns it on through this while +/// holding [`crate::speed::knob_write`]. +static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); + +/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it. +#[allow(dead_code)] // set only from the `#[cfg(test)]` gates +pub(crate) fn set_inter_tx_search(on: Option) { + INTER_TX_OVERRIDE.store( + on.map_or(u8::MAX, u8::from), + std::sync::atomic::Ordering::Relaxed, + ); +} + +fn inter_tx_type_search() -> InterTxSearch { + match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return InterTxSearch::Off, + 1 => return InterTxSearch::All, + _ => {} + } + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() { + "0" | "off" => InterTxSearch::Off, + "screen" => InterTxSearch::Screen, + "le16" => InterTxSearch::Le16, + _ => InterTxSearch::All, + }) + }); + ENV.unwrap_or_else(|| { + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) { + InterTxSearch::Screen + } else { + InterTxSearch::Off + } + }) +} + +/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the +/// 64-point one (it codes no `tx_type` symbol). +fn inter_luma_set(tx: usize) -> Option { + Some(match tx { + 4 => TxbSet::Luma4Inter, + 8 => TxbSet::Luma8Inter, + 16 => TxbSet::Luma16Inter, + 32 => TxbSet::Luma32Inter, + _ => return None, + }) +} + fn tx_type_search() -> bool { static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { crate::envflags::var("EC_AV1_TXSET") @@ -2262,6 +2359,28 @@ impl Plane<'_> { base_q_idx: u8, deadzone: f64, set: TxbSet, + ) -> Trial { + self.code_from_prediction_typed( + x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct, + ) + } + + /// [`Self::code_from_prediction`] coding the residual with a NAMED + /// transform type (lane-txset2): the inter luma sets carry a two-type + /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes + /// a symbol for, and [`commit_inter_luma`] prices both through this. + #[allow(clippy::too_many_arguments)] + fn code_from_prediction_typed( + &self, + x: usize, + y: usize, + side: usize, + prediction: &[u8], + skip: bool, + base_q_idx: u8, + deadzone: f64, + set: TxbSet, + tx_type: TxType, ) -> Trial { if skip { let sse = self.block_sse(x, y, side, prediction); @@ -2298,16 +2417,20 @@ impl Plane<'_> { // lane-rdoq, as in [`Self::trial_typed`]. let (levels, rdoq_bits) = if rdoq_on() { let (mut levels, scaled) = - forward_and_quantize_scaled(residual, side, 8, i32::from(base_q_idx), deadzone); + forward_and_quantize_typed_scaled( + residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, + ); let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); let bits = crate::tile::rdoq( &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(), - TxType::DctDct, + tx_type, ); (levels, Some(bits)) } else { ( - forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone), + forward_and_quantize_typed( + residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, + ), None, ) }; @@ -2320,7 +2443,7 @@ impl Plane<'_> { i32::from(base_q_idx), 0, 0, - TxType::DctDct, + tx_type, ); #[cfg(test)] stage_since(2, t); @@ -2357,12 +2480,13 @@ impl Plane<'_> { } else { { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); - crate::tile::coeff_bits( + crate::tile::coeff_bits_typed( &levels, set, crate::decode::q_ctx_of(base_q_idx), skip_ctx, sign_ctx, + tx_type, ) } }; @@ -3673,6 +3797,17 @@ fn tx_depth_bits(side: usize, depth: usize) -> f64 { } } +/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so +/// the intra witness's fire count stays its own. +pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; + +/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it. +#[cfg(test)] +pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] { + std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// How many luma transform units resolved to each [`TxType`], indexed by the /// enum's own discriminant (lane-txset): the fire count a witness asserts on, /// and the instrument that says which types the search actually reaches. @@ -3821,7 +3956,52 @@ fn commit_inter_luma( // `comp_group_idx == 0` average). `None` is the single-reference block. second: Option<((i32, i32), (&[u16], usize, usize, usize))>, fctx: &crate::decode::FrameCtx, -) -> (Vec, u8, f64) { +) -> (Vec, u8, f64, Vec) { + // lane-txset2 step 1: the whole-block (depth 0) residual picks its own + // type out of the two-type inter set the writer already codes a symbol + // for, priced the same way the intra search is (sse + lambda * bits, the + // bits carrying the `tx_type` symbol itself through RDOQ). A skipped + // block codes no residual and the 64-point transform names no type. + let mut flat_typed: Option = None; + let mut flat_type = TxType::DctDct; + if !skip { + if let Some(fset) = inter_luma_set(side) { + let cost = |t: &Trial| t.sse + search.lambda * t.bits; + for &tx_type in inter_tx_type_candidates(fset, search.screen) { + if tx_type == TxType::DctDct { + continue; + } + let candidate = match second { + Some((mv1, ref1)) => mc_trial_compound_typed( + luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx, + search.deadzone, fset, tx_type, fctx, + ), + None => mc_trial_typed( + luma, x, y, side, mv, true, reference.0, reference.1, reference.2, + reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type, + fctx, + ), + }; + if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) { + flat_type = tx_type; + flat_typed = Some(candidate); + } + } + } + } + // Counted at the return points, so the census names the types the block + // really CODES -- a split unit's winner that the flat cost then beats was + // never written (class `counter from refused stream`). + let count = |types: &[TxType]| { + for &t in types { + INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + }; + let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat); + // What the caller's already-counted `flat` cost has to be corrected by + // when a non-`DCT_DCT` type won it, the same way the split delta below is. + let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits) + - (flat.sse + search.lambda * flat.bits); let eligible = tx_select() && tx_select_inter() && !skip @@ -3831,8 +4011,9 @@ fn commit_inter_luma( && x + side <= luma.true_width && y + side <= luma.true_height; if !eligible { - luma.commit(x, y, side, flat); - return (flat.levels.clone(), 0, 0.0); + luma.commit(x, y, side, flat_ref); + count(&[flat_type]); + return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]); } let tx = side / 2; let set = if tx >= 32 { @@ -3850,19 +4031,32 @@ fn commit_inter_luma( // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and // each unit's own commit publishes what the next one reads, coding order. luma.ctx.tu_split = true; + // One type per unit in the writer's own raster order (tile.rs + // `write_luma_tus`), all `DCT_DCT` when nothing else is offered. + let mut split_types = vec![TxType::DctDct; 4]; for tu_row in 0..2 { for tu_col in 0..2 { let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); - let trial = match second { - Some((mv1, ref1)) => mc_trial_compound( + let unit = |tx_type: TxType| match second { + Some((mv1, ref1)) => mc_trial_compound_typed( luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1, - search.base_q_idx, search.deadzone, set, fctx, + search.base_q_idx, search.deadzone, set, tx_type, fctx, ), - None => mc_trial( + None => mc_trial_typed( luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, - reference.3, false, search.base_q_idx, search.deadzone, set, fctx, + reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx, ), }; + let mut best: Option<(f64, TxType, Trial)> = None; + for &tx_type in inter_tx_type_candidates(set, search.screen) { + let candidate = unit(tx_type); + let cost = candidate.sse + search.lambda * candidate.bits; + if best.as_ref().is_none_or(|(b, _, _)| cost < *b) { + best = Some((cost, tx_type, candidate)); + } + } + let (_, tx_type, trial) = best.expect("the candidate list is never empty"); + split_types[tu_row * 2 + tu_col] = tx_type; sse += trial.sse; bits += trial.bits; for row in 0..tx { @@ -3874,7 +4068,7 @@ fn commit_inter_luma( } luma.ctx.tu_split = false; let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); - let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); + let flat_cost = flat_ref.sse + search.lambda * (flat_ref.bits + txfm_split_bits(side, 0)); let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2; // The depth census has a leaf row and a 32x32 row and no 64 one, so the // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing @@ -3887,13 +4081,15 @@ fn commit_inter_luma( if counted { INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - return (levels, 1, split_cost - flat_cost); + count(&split_types); + return (levels, 1, flat_gain + split_cost - flat_cost, split_types); } if counted { INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - luma.commit(x, y, side, flat); - (flat.levels.clone(), 0, 0.0) + luma.commit(x, y, side, flat_ref); + count(&[flat_type]); + (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]) } /// The largest distinct-colour count a block may hold and still be offered a @@ -5932,11 +6128,11 @@ fn code_square_inter( ) }) }); - let (levels, tx_depth, dcost) = if motion_won != 0 + let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0 || (info.ref1.is_some() && second.is_none()) { luma.commit(x, y, side, &luma_new); - (luma_new.levels.clone(), 0, 0.0) + (luma_new.levels.clone(), 0, 0.0, Vec::new()) } else { commit_inter_luma( luma, (x, y), side, info.mv, @@ -5962,7 +6158,7 @@ fn code_square_inter( palette: None, palette_uv: None, tx_depth, - luma_tx_types: Vec::new(), + luma_tx_types, inter: Some(info), motion_mode: motion_won, }, @@ -5979,13 +6175,13 @@ fn code_square_inter( census_add(9, 1); } if inter_cost < intra_cost { - let (levels, tx_depth, dcost) = commit_inter_luma( + let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma( luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx, ); chroma[0].commit(x / 2, y / 2, side / 2, &u); chroma[1].commit(x / 2, y / 2, side / 2, &v); (BlockCoeffs { - luma_tx_types: Vec::new(), + luma_tx_types, angle_delta_y: 0, cfl_alphas: None, filter_intra: None, @@ -7817,7 +8013,34 @@ fn mc_trial( skip: bool, base_q_idx: u8, deadzone: f64, - set: TxbSet, fctx: &crate::decode::FrameCtx, + set: TxbSet, + fctx: &crate::decode::FrameCtx, +) -> Trial { + mc_trial_typed( + plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx, + deadzone, set, TxType::DctDct, fctx, + ) +} + +/// [`mc_trial`] coding its residual with a named transform type (lane-txset2). +#[allow(clippy::too_many_arguments)] +fn mc_trial_typed( + plane: &Plane, + x: usize, + y: usize, + side: usize, + mv: (i32, i32), + luma: bool, + reference: &[u16], + stride: usize, + ref_width: usize, + ref_height: usize, + skip: bool, + base_q_idx: u8, + deadzone: f64, + set: TxbSet, + tx_type: TxType, + fctx: &crate::decode::FrameCtx, ) -> Trial { let x_q4 = mv_to_q4(x, mv.1, luma); let y_q4 = mv_to_q4(y, mv.0, luma); @@ -7846,7 +8069,9 @@ fn mc_trial( for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) { *dst = src as u8; } - plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set) + plane.code_from_prediction_typed( + x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type, + ) } /// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both @@ -7857,6 +8082,28 @@ fn mc_trial( /// block, so the encoder's reconstruction is the decoder's. #[allow(clippy::too_many_arguments)] fn mc_trial_compound( + plane: &Plane, + x: usize, + y: usize, + side: usize, + mvs: ((i32, i32), (i32, i32)), + luma: bool, + ref0: (&[u16], usize, usize, usize), + ref1: (&[u16], usize, usize, usize), + base_q_idx: u8, + deadzone: f64, + set: TxbSet, + fctx: &crate::decode::FrameCtx, +) -> Trial { + mc_trial_compound_typed( + plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx, + ) +} + +/// [`mc_trial_compound`] coding its residual with a named transform type +/// (lane-txset2). +#[allow(clippy::too_many_arguments)] +fn mc_trial_compound_typed( plane: &Plane, x: usize, y: usize, @@ -7867,7 +8114,9 @@ fn mc_trial_compound( ref1: (&[u16], usize, usize, usize), base_q_idx: u8, deadzone: f64, - set: TxbSet, fctx: &crate::decode::FrameCtx, + set: TxbSet, + tx_type: TxType, + fctx: &crate::decode::FrameCtx, ) -> Trial { let mut inter0 = [0i32; BLOCK * BLOCK]; let mut inter1 = [0i32; BLOCK * BLOCK]; @@ -7896,7 +8145,9 @@ fn mc_trial_compound( for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { *dst = src as u8; } - plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set) + plane.code_from_prediction_typed( + x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type, + ) } /// Codes one 32x32 block of an inter frame as whichever costs least of: each @@ -8262,7 +8513,7 @@ fn search_skip_64( // The residual arm's luma levels and the `txfm_split` depth the writer // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is // four TX_32X32 units in 64x64 ones. - let mut luma_levels: Option<(Vec, u8)> = None; + let mut luma_levels: Option<(Vec, u8, Vec)> = None; if residual { let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; let residual_trials = [0usize, 1, 2].map(|plane| { @@ -8288,7 +8539,7 @@ fn search_skip_64( // four TX_32X32 units of `txfm_split = 1`, taken by the same // `commit_inter_luma` every other inter block's is (it commits the // winner and hands back the cost it took off the flat arm). - let (levels, depth, gain) = if b64_var_tx() { + let (levels, depth, gain, tx_types) = if b64_var_tx() { let second = info.ref1.and_then(|r1| { compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| { ( @@ -8311,7 +8562,7 @@ fn search_skip_64( fctx, ) } else { - (residual_trials[0].levels.clone(), 0, 0.0) + (residual_trials[0].levels.clone(), 0, 0.0, Vec::new()) }; let cost = residual_trials.iter().map(|t| t.sse).sum::() + search.lambda * (syntax + unskip + coeff_bits) @@ -8321,7 +8572,7 @@ fn search_skip_64( if depth == 1 { B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - luma_levels = Some((levels, depth)); + luma_levels = Some((levels, depth, tx_types)); chosen = (cost, false, residual_trials); } } @@ -8342,11 +8593,15 @@ fn search_skip_64( // The chroma grids are whole TX_32X32; the luma one is the // 64-point transform's coded 32x32 corner at depth 0 and the // whole 64-sided block at depth 1 (lane-b64b). - tx_depth: luma_levels.as_ref().map_or(0, |&(_, d)| d), + tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d), + luma_tx_types: match (skip, &luma_levels) { + (false, Some((_, _, types))) => types.clone(), + _ => Vec::new(), + }, luma: match (skip, &luma_levels) { (true, _) => Vec::new(), - (false, Some((levels, 1))) => coeffs(levels, SUPERBLOCK), - (false, Some((levels, _))) => coeffs(levels, BLOCK), + (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK), + (false, Some((levels, _, _))) => coeffs(levels, BLOCK), (false, None) => coeffs(&trials[0].levels, BLOCK), }, u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) }, @@ -9200,7 +9455,7 @@ fn search_inter_block( // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp // winner still commits flat: `commit_inter_luma` re-predicts each unit by // plain translation, which is not the prediction it was priced from. - let (levels, tx_depth, dcost) = match best.inter.filter(|_| motion_won == 0) { + let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) { Some(info) => { let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height), @@ -9217,7 +9472,7 @@ fn search_inter_block( match info.ref1.is_some() && second.is_none() { true => { luma.commit(x, y, BLOCK, &best.luma); - (best.luma.levels.clone(), 0, 0.0) + (best.luma.levels.clone(), 0, 0.0, Vec::new()) } false => commit_inter_luma( luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second, @@ -9227,14 +9482,14 @@ fn search_inter_block( } None => { luma.commit(x, y, BLOCK, &best.luma); - (best.luma.levels.clone(), 0, 0.0) + (best.luma.levels.clone(), 0, 0.0, Vec::new()) } }; chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); ( BlockCoeffs { - luma_tx_types: Vec::new(), + luma_tx_types, angle_delta_y: 0, cfl_alphas: None, filter_intra: None, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index ff15b2e3..60a678f7 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3727,6 +3727,90 @@ mod tests { eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len()); } + /// lane-txset2's witness: an INTER frame's luma transform units take BOTH + /// types of the two-type inter set the writer already codes a symbol for + /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire + /// count, class `gate-blind-to-feature` -- and both decoders reconstruct + /// every frame sample-exact from the `tx_type` symbols that name them. + /// Before this lane every inter luma unit was coded `DCT_DCT`. + #[test] + fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() { + // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so + // this turns it on process-globally under the same exclusive lock the + // presets take. + let _knobs = crate::speed::knob_write(); + let _gate_lock = crate::stream::tests::lock_gate_counters(); + crate::encode::set_inter_tx_search(Some(true)); + let (width, height) = (320usize, 192usize); + // Sharp steps that MOVE: the motion-compensated residual along a + // moving edge is exactly where the identity transform beats a DCT, + // and the flat plateaus between them predict to nothing at all. + let sources: Vec = (0..4) + .map(|t| { + let mut p = test_card(width, height, t * 3); + for y in 0..height { + for x in 0..width { + let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { + (0, 0) => 16u16, + (1, 0) => 235, + (0, 1) => ((x + t) % 64 * 3) as u16, + _ => ((y + t) % 64 * 3) as u16, + }; + p.y[y * width + x] = v; + } + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::encode::take_inter_tx_type_hits(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let hits = crate::encode::take_inter_tx_type_hits(); + crate::encode::set_inter_tx_search(None); + for (name, ty) in [ + ("DCT_DCT", crate::transform::TxType::DctDct), + ("IDTX", crate::transform::TxType::Idtx), + ] { + assert!( + hits[ty as usize] > 0, + "no inter luma transform unit was CODED {name}: {hits:?}" + ); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + if have_ffmpeg() { + 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], + ); + } + } + } else { + eprintln!("SKIP the ffmpeg half: no ffmpeg"); + } + eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len()); + } + /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from /// its neighbour (a preset that changes no byte is a preset that buys no diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs index 50440701..0d169386 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -491,6 +491,18 @@ pub(crate) const TX_TYPE_SEARCH: [bool; 11] = [ true, true, true, true, true, true, true, false, false, false, false, ]; +/// `tx_type_candidates`: whether an INTER luma transform unit searches the +/// two-type `TX_SET_INTER_3` (`IDTX` vs `DCT_DCT`) the writer already codes a +/// symbol for, instead of always coding `DCT_DCT` (lane-txset2). On at the +/// presets that carry the intra search, and SCREEN CONTENT ONLY on top of it +/// (measured, 12-frame `bd_rate_screen_native`: the capture goes +/// +20.8/-30.1 -> +20.1/-30.4 while both synthetic bars rows lose twenty +/// points and film B 0.3 -- see `encode::inter_tx_type_candidates`). +/// `EC_AV1_TXSET_INTER` overrides. +pub(crate) const TX_TYPE_SEARCH_INTER: [bool; 11] = [ + true, true, true, true, true, true, true, false, false, false, false, +]; + /// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs. pub(crate) const DEBLOCK_REFINE: [bool; 11] = [ true, true, true, true, true, true, true, false, false, false, false, diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 40875e3f..e6d5f430 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -4724,6 +4724,9 @@ fn scan_of(side: usize) -> &'static Vec { } } +/// [`coeff_bits_typed`] at `DCT_DCT`, the only type the test-only pricers +/// ([`predicted_coeff_bits`]) model. +#[cfg(test)] pub(crate) fn coeff_bits( grid: &[i32], set: TxbSet, @@ -4734,7 +4737,7 @@ pub(crate) fn coeff_bits( coeff_bits_typed(grid, set, q_ctx, skip_ctx, sign_ctx, TxType::DctDct) } -/// [`coeff_bits`] for levels a named transform type produced: the `tx_type` +/// What levels a named transform type produced cost: the `tx_type` /// symbol is part of what the block spends, so a search comparing types has /// to see each one's own symbol priced (lane-txset). pub(crate) fn coeff_bits_typed( diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index bef434f3..1d40feb9 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -2160,7 +2160,10 @@ mod tests { /// and the mode search would read as a loss. #[test] fn a_typed_forward_round_trips_like_the_dct_one() { - for side in [4usize, 8, 16] { + // lane-txset2: 32 too -- the INTER search offers `IDTX` at 32x32 + // (`TxbSet::Luma32Inter`'s `EXT_TX_SET_DCT_IDTX`), a size the intra + // sets never name and this round trip never covered. + for side in [4usize, 8, 16, 32] { let residual: Vec = noise(side * side, 7 + side as u64) .iter() .map(|&v| v / 4) @@ -2180,7 +2183,10 @@ mod tests { // the reduced set names -- the FLIPADST and 1D-ADST/DCT families // reach the forward side through the mirrored residual, and a // mirror on the wrong axis reads exactly as a blown-up rmse here. - for tx in [ + // At 32x32 the only types any set names are `DCT_DCT` and + // `IDTX` (`EXT_TX_SET_DCT_IDTX`; ADST is undefined above 16), and + // the inter search offers exactly those. + let all = [ TxType::AdstDct, TxType::DctAdst, TxType::AdstAdst, @@ -2196,7 +2202,9 @@ mod tests { TxType::FlipAdstFlipAdst, TxType::AdstFlipAdst, TxType::FlipAdstAdst, - ] { + ]; + let types: &[TxType] = if side > 16 { &[TxType::Idtx] } else { &all }; + for &tx in types { let e = rmse(tx); assert!( e < 2.0 * dct, diff --git a/lanes/txset2.report.md b/lanes/txset2.report.md new file mode 100644 index 00000000..2900a951 --- /dev/null +++ b/lanes/txset2.report.md @@ -0,0 +1,198 @@ +# lane-txset2 -- the inter transform-type search, and reduced_tx_set=0 + +Branch `lane-txset2` off main `5e923074`. Predecessor: `lanes/txset.report.md` +(intra 5-type reduced set, screen-gated). + +## Step 1 -- inter luma IDTX vs DCT_DCT (`TX_SET_INTER_3`) + +The writer already codes a two-symbol `tx_type` for every inter luma unit at +32x32 and below (`TxbSet::Luma{4,8,16,32}Inter`) and always named `DCT_DCT`. + +* `encode::inter_tx_type_candidates(set, screen)` -- `[DCT_DCT, IDTX]` for + those four sets, `[DCT_DCT]` for the 64-point transform (no symbol) and for + chroma. +* `Plane::code_from_prediction_typed` / `mc_trial_typed` / + `mc_trial_compound_typed`: the untyped entries are now `DCT_DCT` wrappers, + so no call site outside the search moved. +* `commit_inter_luma` prices the candidates twice: once for the whole-block + (depth 0) residual, once per var-tx split unit, both by `sse + lambda * + bits` with the bits carrying the `tx_type` symbol through RDOQ -- the same + rule the intra search uses. The chosen types leave through the new fourth + element of its return and reach the writer as `BlockCoeffs::luma_tx_types` + (flat = one entry, split = four in the writer's raster order). +* Levers: `speed::TX_TYPE_SEARCH_INTER` (OFF at every preset until the gate + says otherwise), `EC_AV1_TXSET_INTER=0|screen|1`, plus a test-only + process-global override (`encode::set_inter_tx_search`). +* Census: `encode::INTER_TX_TYPE_HITS`, counted at the COMMIT points only, so + a split unit's winner the flat cost then beats is not counted. + +Witness: `encoder::tests::an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly` +-- PASS, hits `[DCT_DCT 154 .., IDTX 1368 ..]`, ours == ffmpeg every sample. + +Gate rows: see below (arms running). + +### The 12-frame gate (`encode::tests::bd_rate_screen_native`, 12 frames, gop 12) + +Control re-run on this head (`EC_AV1_TXSET_INTER=0`, which is also the +default): it REPRODUCES the charter's numbers to the digit, byte counts +included. + +| clip | control | arm: every frame, every size | delta | wall ctl -> arm | +|---|---|---|---|---| +| bars 1080p | -1.0% / -16.8% | **+23.1% / +3.3%** | +24.1 / +20.1 | 177.2s -> 182.0s | +| bars 2160p | +9.4% / -12.7% | **+31.2% / +3.7%** | +21.8 / +16.4 | 155.9s -> 160.7s | +| film A | +21.7% / -4.4% | +21.5% / -4.5% | -0.2 / -0.1 | 154.9s -> 167.7s | +| film B | +26.9% / -0.6% | +27.2% / -0.3% | +0.3 / +0.3 | 161.5s -> 167.6s | +| screen capture | +20.8% / -30.1% | +20.1% / -30.4% | -0.7 / -0.3 | 112.2s -> 109.5s | + +KEEP RULE on the unconditional arm: FAIL, and not marginally -- the two +synthetic bars rows lose TWENTY points (2 dB of luma PSNR at the same byte +count). Film A is 0.2/0.1 down, film B 0.3/0.3 up, the capture 0.7/0.3 down. + +The identity transform is not mis-scaled at 32x32: the typed round trip now +covers `side = 32` for the two types any set names there (`DCT_DCT`, `IDTX`; +ADST is undefined above 16) and `IDTX`'s rmse stays inside the DCT's 2x bound. +The bars collapse is the `local-rd-on-references` class again, at its loudest: +a flat synthetic frame is all 32x32 inter blocks whose residual `IDTX` prices +cheapest locally, and every later frame predicts from that reconstruction. + +## Step 3 -- what libaom actually picks (instrument, read off lane-libcen's census) + +`lanes/libcen.report.md`'s census files (`~/.cache/lc-libcen/cen-*.txt`, +`crates/ec-av1/examples/syntax_census.rs`) already carry the per-frame +`tx_type` histogram keyed by CDF row length, so no new run was needed. Film B, +libaom cpu-used 6 crf41 (48 pictures), row length -> set: 3 = the 2-symbol +inter `DCT_IDTX` (32x32), 6 = the 5-symbol `TX_SET_INTRA_2` (intra 16x16 and, +under `reduced_tx_set`, all intra), 8 = the 7-symbol `TX_SET_INTRA_1` (intra +8x8/4x4), 13 = the 12-symbol `TX_SET_INTER_2` (inter 16x16), 17 = ALL16 +(inter 8x8/4x4). + +| frame | set3 (inter 32) | set6 (intra 16) | set8 (intra 8/4) | set13 (inter 16) | set17 (inter <=8) | +|---|---|---|---|---|---| +| key (718 symbols) | -- | 85.3% | 14.7% | -- | -- | +| arf hint 30 (1058) | 27.5% | 6.8% | 4.5% | 51.7% | 9.7% | +| arf hint 15 (364) | 34.1% | 1.7% | 1.6% | 46.8% | 15.7% | +| arf hint 7 (61) | 67.2% | 1.6% | -- | 19.7% | 11.5% | +| arf hint 3 (41) | 78.0% | -- | -- | 9.7% | 12.3% | + +Two readings, both decisions: + +1. **libaom never codes `IDTX` at 32x32 on film B.** Every one of its set3 + symbols is symbol 1 (`DCT_DCT`); symbol 0 does not appear in any frame of + the stream. That is exactly the size our unconditional arm loses its twenty + points on -- hence the `le16` arm below. +2. **41% of its inter `tx_type` symbols are in sets 13/17**, i.e. the alphabets + `reduced_tx_set = 0` unlocks, and they are spread across nine or more + distinct types (set13 symbols 3..11 at 1.5-14% each). Our own stream codes + `set3/1` and `set6/1` only, 100% `DCT_DCT` in inter frames -- the gap step 2 + is aimed at. + +### Step 1, second round: `le16` (the census's own prune) and the screen gate + +| clip | control | `le16` (16x16 and below) | screen-gated (SHIPPED) | +|---|---|---|---| +| bars 1080p | -1.0% / -16.8% | +22.9% / +3.1% | -1.0% / -16.8% (byte-identical) | +| bars 2160p | +9.4% / -12.7% | +31.6% / +4.0% | +9.4% / -12.7% (byte-identical) | +| film A | +21.7% / -4.4% | +21.6% / -4.5% | +21.7% / -4.4% (byte-identical) | +| film B | +26.9% / -0.6% | +27.4% / -0.1% | +26.9% / -0.6% (byte-identical) | +| screen capture | +20.8% / -30.1% | +19.9% / -30.4% | **+20.1% / -30.4%** | + +`le16` does NOT recover the bars rows (+22.9/+31.6 against the unconditional +arm's +23.1/+31.2), so the size restriction the libaom census suggested is +refuted as a fix: the damage is in the 16x16-and-below inter units, not the +32x32 ones. It also drifts film B further up (+27.4/-0.1). + +DECISION: ship SCREEN-GATED, the same shape the intra half of lane-txset +ships behind. The four non-screen rows land on the control's own byte counts +to the digit (194497/299067/419042/567789, 205409/321883/435765/564573, +64392/102508/170169/413430, 27442/50374/105485/296813 -- the clips classify +0 screen frames of 4, the capture 48 of 48), so nothing outside screen +content moves, pins included. The capture is 0.7 down against libaom and 0.3 +against rav1e, at no wall cost (112.2s -> 109.4s, inside the noise). + +Levers as shipped: `speed::TX_TYPE_SEARCH_INTER` true at presets 0-6 (the row +the intra search carries), `inter_tx_type_search()` defaulting to +`Screen` on top of it. `EC_AV1_TXSET_INTER=1` is the unconditional arm, +`le16` the pruned one, `0` off. + +## Step 2 -- `reduced_tx_set = 0` and the 13/17 alphabets: NOT ATTEMPTED, scoped + +`deferred: reduced_tx_set = 0 (sets 13/17, and the 7-symbol intra set at +8x8/4x4) -- not started; the two gate slots and the budget went to step 1's +three arms. What it needs, from this lane's reading:` + +* The DECODER half is complete and needs nothing: `decode::txbset_for` / + `txbset_for_inter` already pick `Luma{8,4}Set1`, `Luma{16,8,4}InterSet1`, + `LumaRect16x8Set1`, `LumaRect{4x8,16x4}Set1`, `LumaRect8x4InterSet1` off the + frame's own bit, and `decode::tx_type_symbol` answers for the 7/12/16-symbol + alphabets. Note the spec shape the charter's table simplifies: intra 16x16 + stays the FIVE-type `TX_SET_INTRA_2` even with the bit off (there is no + `Luma16Set1` and none is needed), only intra 8x8/4x4 widen to seven; inter + 32x32 stays the two-type `DCT_IDTX`, inter 16x16 becomes the 12-symbol set + and inter 8x8/4x4 ALL16. +* The WRITER half is the cross-cutting part (class `tx-class-cross-cutting`): + the frame-header bit (`encode.rs:1660`, `:1760`) plus EVERY luma `TxbSet` + the writer and the pricer pick, which is `tile.rs` 2844, 4087, 4231-4238 + (`write_luma_tus`), 4611-4616, 6078, 7004/7006, 7217/7219 and `encode.rs` + `code_tx_depth` / `commit_inter_luma` / `inter_luma_set` / the trial set + arguments. A site that misses the bit codes the right value against the + wrong CDF -- the `wrong-alphabet-same-value` class -- so the bit belongs in + one accessor both sides read, not in nine `match` arms. +* The gate shape this lane measured says what to expect: a wider set is worth + BD only where the reference chain is short or intra-heavy. Both halves of + the search now measured (intra 5-type, inter 2-type) win on the capture and + lose on film, so a 13/17 lane should be armed screen-gated from the start + and spend its slots on the FILM question separately (the rate term, class + `rd-rate-term-calibration`, is the suspect: at equal bytes the bars rows + lose 2 dB of PSNR, which is a pricer that under-charges the cheap type, not + a decoder or kernel defect -- the typed round trip at 32 is inside its + bound). + +## Invariants, the long-GOP gate and the suite (at the shipped state) + +| invariant | preset 0 | preset 6 | +|---|---|---| +| `an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly` (new) | PASS | PASS | +| `an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly` | PASS | PASS | +| `tile_bytes_do_not_depend_on_the_thread_count --include-ignored` | PASS | PASS | +| `the_facade_codes_the_same_bytes_as_encode_sequence` | PASS | PASS | +| `predicted_coeff_bits_track_the_tile_the_writer_wrote` | PASS | PASS | +| all five above with `EC_COMP_MISMATCH=1` | 0 mismatches | 0 mismatches | + +`transform::tests::a_typed_forward_round_trips_like_the_dct_one` now covers +`side = 32` for `IDTX` (the size the inter search newly offers): PASS. +`every_speed_preset_decodes_sample_exact_through_both_decoders --ignored` +with `EC_COMP_MISMATCH=1`: PASS. +`the_encoders_own_streams_are_byte_identical_to_their_pins`: PASS at the +UNCHANGED 8562 / 33357 -- no re-pin, the pin clip is not screen content +(`EC_AV1_TXSET=0` therefore also restores them unchanged). + +`encode::tests::bd_rate_film_long_gop` at the shipped state (both rows are +non-screen, so byte-identical to the encoder before the lane, which the +12-frame confirm run proves clip by clip): + +| clip | shipped | wall ours:libaom:rav1e | +|---|---|---| +| film A | +26.4% / -6.6% | 726.9s:52.9s:73.5s | +| film B | +89.8% / +9.1% | 489.9s:78.8s:52.2s | + +Full `ec-av1` suite, detached: **569 passed / 0 failed / 45 ignored** +(1327.8s). `timeout 890 cargo check --workspace --all-targets -j4`: 0 errors, +0 `ec-av1` warnings (the 22 warnings the workspace prints are `ec-opus` / +`ec-vorbis`, untouched by this lane). + +## Deferred + +* `deferred: reduced_tx_set = 0 and the 13/17 alphabets -- see the scoped + section above; unblocked by a lane of its own with two gate slots. Arm it + screen-gated from the start.` +* `deferred: the FILM question behind both halves of this search -- at equal + bytes the bars rows lose 2 dB, i.e. the pricer under-charges the cheap type + rather than any kernel or decoder being wrong (round trip at 32 is inside + its bound, the witness decodes sample-exact through ffmpeg). The upgrade + path is the rate term / lambda the type search compares with (class + rd-rate-term-calibration), not a wider set -- unblocked by a sweep of that + term against the bars and film rows.` +* `deferred: offering the inter search on a warp/OBMC winner -- commit_inter_luma + is skipped entirely for those blocks (motion_won != 0), so they still code + DCT_DCT; unblocked by pricing the type on the motion-mode prediction.`