From 7a1492f9a1c1b1b1abd266c57905f106add3744c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 04:01:35 +0300 Subject: [PATCH] feat(av1): the intra half of reduced_tx_set=0, and a rate surcharge on a non-DCT type The search names the widened luma set for INTRA units only: with the wider inter candidates priced some block's winner selects a DPB slot this encoder holds no picture in (the refs lane's bookkeeping), which bisection pins to the inter half alone. EC_AV1_TXRD_LAMBDA now also charges the intra type decision: the 12-frame instrument says the five-type search buys 0.04 dB for 1.2% more bytes on film A on every frame and every plane, key frame included, so the loss is the rate term and not propagation into the leaves. --- crates/ec-av1/src/encode.rs | 111 +++++++++++++++++++++++++++++++---- crates/ec-av1/src/encoder.rs | 111 +++++++++++++++++++++++++++++++++++ 2 files changed, 211 insertions(+), 11 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 587cff4c..7a5385c6 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -291,7 +291,7 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] ]; match set { TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 - if (screen || intra_tx_all_frames()) && tx_type_search() => + if intra_tx_search_on(screen) => { &INTRA2 } @@ -301,7 +301,7 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] // extra members are the 1-D DCTs, and the order is the reader's own // map (`decode::tx_type_from_symbol`, 8-wide CDF). TxbSet::Luma8Set1 | TxbSet::Luma4Set1 - if (screen || intra_tx_all_frames()) && tx_type_search() => + if intra_tx_search_on(screen) => { &INTRA1 } @@ -369,6 +369,11 @@ pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [T /// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated /// like both halves of the type search itself. pub(crate) fn wide_tx_set(screen: bool) -> bool { + match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return false, + 1 => return true, + _ => {} + } static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() { "0" | "off" => InterTxSearch::Off, @@ -387,6 +392,23 @@ pub(crate) fn wide_tx_set(screen: bool) -> bool { } } +/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the +/// environment and the preset (`u8::MAX` = unset), the shape +/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the +/// witness that has to see the wider alphabets turns it on through this while +/// holding [`crate::speed::knob_write`]. +static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); + +/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it. +#[allow(dead_code)] // set only from the `#[cfg(test)]` gates +pub(crate) fn set_wide_tx_set(on: Option) { + WIDE_TX_OVERRIDE.store( + on.map_or(u8::MAX, u8::from), + std::sync::atomic::Ordering::Relaxed, + ); +} + /// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes /// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own /// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read @@ -450,14 +472,25 @@ fn inter_tx_type_search() -> InterTxSearch { /// 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, screen: bool) -> Option { - Some(luma_set_for(match tx { +/// lane-txi: the INTER half of the widening is deliberately NOT applied +/// here. A `reduced_tx_set = 0` frame's writer still codes its inter luma +/// `tx_type` into the twelve/sixteen-symbol alphabet (the frame bit widens +/// every luma set at once, spec `get_tx_set`), but the SEARCH keeps offering +/// the two-type list: with the wider inter candidates priced, some block's +/// winner selects a reference slot this encoder holds no picture in +/// ("a reference frame selected with no picture at this frame's own +/// ref_frame_idx slot for it", refused out of the encoder's own MC), which is +/// the `refs` lane's DPB bookkeeping (`encoder.rs` maps LAST2/LAST3 onto +/// LAST's slot), not a transform defect -- measured by bisection: the intra +/// half alone passes every witness, the inter half alone refuses. +fn inter_luma_set(tx: usize) -> Option { + Some(match tx { 4 => TxbSet::Luma4Inter, 8 => TxbSet::Luma8Inter, 16 => TxbSet::Luma16Inter, 32 => TxbSet::Luma32Inter, _ => return None, - }, screen)) + }) } fn tx_type_search() -> bool { @@ -469,6 +502,34 @@ fn tx_type_search() -> bool { ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH)) } +/// Whether an intra luma unit of this frame searches its own type at all: +/// the preset lever ([`tx_type_search`]) under the screen content gate, which +/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global +/// [`set_intra_tx_search`] override wins over (the witness needs the search +/// on a frame the detector called non-screen). +fn intra_tx_search_on(screen: bool) -> bool { + match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return false, + 1 => return true, + _ => {} + } + (screen || intra_tx_all_frames()) && tx_type_search() +} + +/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the +/// shape [`set_inter_tx_search`] has. +static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); + +/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it. +#[allow(dead_code)] // set only from the `#[cfg(test)]` gates +pub(crate) fn set_intra_tx_search(on: Option) { + INTRA_TX_OVERRIDE.store( + on.map_or(u8::MAX, u8::from), + std::sync::atomic::Ordering::Relaxed, + ); +} + /// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY /// frame -- the unconditional arm the gate measures -- instead of the screen /// content gate [`tx_type_candidates`] ships behind. Any other value keeps @@ -2692,7 +2753,18 @@ impl Plane<'_> { tu, mode, angle_delta, search.base_q_idx, search.deadzone, tx_type, fctx, ); - let cost = candidate.sse + search.lambda * candidate.bits; + // lane-txi: a non-`DCT_DCT` type is charged its + // bits at `EC_AV1_TXRD_LAMBDA` times the mode + // search's weight (default 1 = unchanged). The + // film rows buy 0.04 dB for 1.2% more bytes at + // weight 1 on every frame and every PLANE, key + // frame included -- a rate term this decision + // under-charges (class + // `rd-rate-term-calibration`), not the + // propagation loss the leaves would have shown. + let cost = candidate.sse + + search.lambda * candidate.bits + + non_dct_surcharge(search.lambda, tx_type, candidate.bits); if best.as_ref().is_none_or(|(best, _, _)| cost < *best) { best = Some((cost, tx_type, candidate)); } @@ -3083,7 +3155,10 @@ impl Plane<'_> { ); let cost_t = candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]); - if cost_t < cost { + // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is + // `DCT_DCT` and pays none of it, so the returned `cost` stays the + // block's true one for the caller's own decision. + if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost { cost = cost_t; tx_type = candidate_type; trial = candidate; @@ -3946,6 +4021,20 @@ pub(crate) fn tx_type_lambda_mult() -> f64 { *M } +/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own +/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the +/// default weight of 1 and for `DCT_DCT` itself. The instrument the film +/// question needs: at weight 1 the five-type intra search spends 1.2% more +/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate +/// of the type it picks. +pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 { + if tx_type == TxType::DctDct { + 0.0 + } else { + lambda * (tx_type_lambda_mult() - 1.0) * bits + } +} + /// lane-txrd instrument: over the FLAT inter luma decision, the summed /// reconstruction error and priced bits of the type the search chose against /// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an @@ -4176,7 +4265,7 @@ fn commit_inter_luma( let mut flat_typed: Option = None; let mut flat_type = TxType::DctDct; if !skip { - if let Some(fset) = inter_luma_set(side, search.screen) { + if let Some(fset) = inter_luma_set(side) { let lambda = search.lambda * tx_type_lambda_mult(); let cost = |t: &Trial| t.sse + lambda * t.bits; for &tx_type in inter_tx_type_candidates(fset, search.screen) { @@ -4222,7 +4311,7 @@ fn commit_inter_luma( // differently-predicted baseline is what would let a candidate win on // both terms at once (class `local-rd-on-references` vs a real // pricing defect); re-predicting it here is the only way to tell. - if let Some(fset) = inter_luma_set(side, search.screen) { + if let Some(fset) = inter_luma_set(side) { let here = match second { Some((mv1, ref1)) => mc_trial_compound_typed( luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx, @@ -4267,14 +4356,14 @@ fn commit_inter_luma( return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]); } let tx = side / 2; - let set = luma_set_for(if tx >= 32 { + let set = if tx >= 32 { // lane-b64b: the 64x64 root's halved transform is TX_32X32. TxbSet::Luma32Inter } else if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter - }, search.screen); + }; let mut levels = vec![0i32; side * side]; let (mut sse, mut bits) = (0.0, 0.0); let mut units = Vec::with_capacity(4); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 60a678f7..b058e41f 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3811,6 +3811,117 @@ mod tests { eprintln!("inter tx_type witness: hits {hits:?}, {} bytes", stream.len()); } + /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER + /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra + /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below -- + /// and both decoders reconstruct every frame sample-exact from them. The + /// statement is that the types only those alphabets can NAME (`V_DCT`, + /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are + /// reachable at all, and that the header bit, the writer's set map and + /// the search's pricer agree on which alphabet a symbol was coded into + /// (class `wrong-alphabet-same-value`: a disagreement here changes no + /// symbol VALUE and desyncs the arithmetic coder anyway). + #[test] + fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() { + // Every lever below is process-global: 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_intra_tx_search(Some(true)); + crate::encode::set_inter_tx_search(Some(true)); + crate::encode::set_wide_tx_set(Some(true)); + let (width, height) = (320usize, 192usize); + // The same moving hard-edge card the two narrow-set witnesses use: + // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the + // ramps are `ADST`'s and the moving plateaus `IDTX`'s. + 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_tx_type_hits(); + 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 (intra, inter) = ( + crate::encode::take_tx_type_hits(), + crate::encode::take_inter_tx_type_hits(), + ); + crate::encode::set_wide_tx_set(None); + crate::encode::set_inter_tx_search(None); + crate::encode::set_intra_tx_search(None); + eprintln!("wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes", stream.len()); + // The fire count is preset 0's, for the reason the five-type witness + // spells out: a faster preset prunes the modes and partitions a type + // wins on before it is ever priced (class `gate-blind-to-feature`). + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { + use crate::transform::TxType; + let wide_only = |hits: &[usize; 16]| -> usize { + hits[TxType::VDct as usize] + hits[TxType::HDct as usize] + }; + assert!( + wide_only(&intra) > 0, + "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}" + ); + let inter_wide: usize = inter.iter().sum::() + - inter[TxType::DctDct as usize] + - inter[TxType::Idtx as usize]; + assert!( + inter_wide > 0, + "no inter luma unit took a type outside the two-type set: {inter:?}" + ); + } else { + eprintln!( + "SKIP the wide-alphabet fire count at preset {}", + crate::speed::speed() + ); + } + 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"); + } + } + /// 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