diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 244f42f2..a6081b24 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -318,11 +318,48 @@ impl TxbSet { | Self::ChromaRect32x16 ) } + + /// lane-txi: this set's `reduced_tx_set == 0` counterpart -- the WIDER + /// `tx_type` alphabet the same coefficient tables are read with when the + /// frame header's bit is off. Every pair here is the one + /// `decode::txbset_for`/`txbset_for_inter`/`inter_txbset_for` resolve off + /// that bit, transcribed from the DECODER's own map so writer and reader + /// cannot drift (class `table-and-reader-move-together`); a set with no + /// counterpart -- intra 16x16 and 32x32, inter 32x32, 64x64, every + /// chroma set -- is its own, and widening an already-wide set is the + /// identity. + pub(crate) fn wide(self) -> Self { + match self { + Self::Luma8 => Self::Luma8Set1, + Self::Luma4 => Self::Luma4Set1, + Self::Luma16Inter => Self::Luma16InterSet1, + Self::Luma8Inter => Self::Luma8InterSet1, + Self::Luma4Inter => Self::Luma4InterSet1, + Self::LumaRect16x8 => Self::LumaRect16x8Set1, + Self::LumaRect4x8 => Self::LumaRect4x8Set1, + Self::LumaRect16x4 => Self::LumaRect16x4Set1, + Self::LumaRect16x8Inter => Self::LumaRect16x8InterSet1, + Self::LumaRect8x4Inter => Self::LumaRect8x4InterSet1, + Self::LumaRect16x4Inter => Self::LumaRect16x4Inter1, + other => other, + } + } } /// Every table a key frame's tile writer adapts. #[derive(Clone)] pub(crate) struct Cdfs { + /// lane-txi: this FRAME's `reduced_tx_set` header bit (spec 5.9.2). + /// `true` -- the default, and what every stream this encoder wrote + /// before the lane carries -- leaves [`Self::txb`]'s luma set exactly as + /// its caller named it. `false` widens it to the `Set1` counterpart + /// ([`TxbSet::wide`]), which is the ONE place the writer and its pricer + /// read the bit from, so a site that forgets it cannot code the right + /// value against the wrong CDF (class `wrong-alphabet-same-value`). + /// The DECODER never sets this: it names the widened set itself off the + /// header (`decode::txbset_for`), and widening an already-wide set is the + /// identity. + pub reduced_tx_set: bool, /// The coefficient q-context these tables were built for (spec 8.3.2's /// `Get_Qctx`), so a writer can price a block against the same tables the /// search did (`tile::coeff_bits`). @@ -996,6 +1033,7 @@ impl Cdfs { /// quantizer, so they are the same for every `q_ctx`. pub fn new(q_ctx: usize) -> Cdfs { Cdfs { + reduced_tx_set: true, q_ctx, partition_w128: cdf::PARTITION_W128, partition_w64: cdf::PARTITION_W64, @@ -1602,6 +1640,7 @@ impl Cdfs { /// The tables one table set is coded with, borrowed out of the state. pub fn txb(&mut self, set: TxbSet, mode: usize) -> TxbTables<'_> { + let set = if self.reduced_tx_set { set } else { set.wide() }; match set { TxbSet::Luma32 => TxbTables { side: 32, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 70738bdf..31d62b41 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -24891,6 +24891,12 @@ impl<'p> RefPix<'p> { /// (lane-defer8). fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> { refpix.dims(ref_frame).ok_or_else(|| { + if crate::envflags::env_flag!("EC_AV1_REFPROBE") { + eprintln!( + "EC_REFPROBE missing ref {ref_frame}\n{}", + std::backtrace::Backtrace::force_capture() + ); + } unsupported( "a reference frame selected with no picture at this frame's own \ ref_frame_idx slot for it", @@ -34220,6 +34226,9 @@ pub(crate) fn decode_inter_frame_tile_lr( interp_fixed, enable_dual_filter, reference_select, + // lane-txi: this wrapper's callers are the decoder's own tests, which + // all code the reduced sets. + true, tx_select, lr, initial_cdfs, @@ -34252,6 +34261,12 @@ pub(crate) fn decode_inter_frame_tiles_lr( interp_fixed: Option, enable_dual_filter: bool, reference_select: bool, + // lane-txi: this frame header's own `reduced_tx_set` bit. It used to be + // hardcoded `true` at the call below -- the encoder's own trial decode of + // the tile it just wrote then read every luma `tx_type` out of the + // reduced alphabet whatever the header said (class: a header bit a raw + // tile decode cannot guess, the same one `tx_select` carries). + reduced_tx_set: bool, tx_select: bool, lr: &LoopRestorationParams, initial_cdfs: Option, @@ -34314,7 +34329,7 @@ pub(crate) fn decode_inter_frame_tiles_lr( false, false, [0; 2], - true, + reduced_tx_set, tx_select, switchable_motion_mode, allow_warped_motion, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 2b89985a..1f7912e1 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -273,6 +273,15 @@ fn tx_select_inter() -> bool { /// here. pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] { const DCT: [TxType; 1] = [TxType::DctDct]; + const INTRA1: [TxType; 7] = [ + TxType::DctDct, + TxType::AdstAdst, + TxType::AdstDct, + TxType::DctAdst, + TxType::Idtx, + TxType::VDct, + TxType::HDct, + ]; const INTRA2: [TxType; 5] = [ TxType::DctDct, TxType::AdstAdst, @@ -281,7 +290,21 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] TxType::Idtx, ]; match set { - TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if screen && tx_type_search() => &INTRA2, + TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 + if intra_tx_search_on(screen) => + { + &INTRA2 + } + // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the + // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`; + // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two + // 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 intra_tx_search_on(screen) => + { + &INTRA1 + } _ => &DCT, } } @@ -308,6 +331,15 @@ pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] 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]; + const INTER_WIDE: [TxType; 7] = [ + TxType::DctDct, + TxType::AdstAdst, + TxType::AdstDct, + TxType::DctAdst, + TxType::Idtx, + TxType::VDct, + TxType::HDct, + ]; let mode = inter_tx_type_search(); let on = match mode { InterTxSearch::Off => false, @@ -317,10 +349,78 @@ pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [T match set { TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3, TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3, + // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the + // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32 + // stays the two-type `DCT_IDTX`). The seven offered here are the + // members those two alphabets SHARE with the intra set -- the four + // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the + // candidate list rav1e's speed 6 prunes to; the FLIPADST family and + // the 1-D ADSTs are codable and left unoffered (deferred). + TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => { + &INTER_WIDE + } _ => &DCT, } } +/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e. +/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below? +/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything +/// 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, + "screen" => InterTxSearch::Screen, + _ => InterTxSearch::All, + }) + }); + match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) { + InterTxSearch::Screen + } else { + InterTxSearch::Off + }) { + InterTxSearch::Off => false, + InterTxSearch::Screen => screen, + _ => true, + } +} + +/// 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 +/// the same alphabet or the two disagree on what a `tx_type` symbol costs. +pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet { + if wide_tx_set(screen) { + set.wide() + } else { + set + } +} + #[derive(Clone, Copy, PartialEq)] pub(crate) enum InterTxSearch { Off, @@ -372,6 +472,17 @@ 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). +/// 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, @@ -391,6 +502,45 @@ 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 +/// the gate (`0`/`off` still switches the search off entirely). +fn intra_tx_all_frames() -> bool { + static ENV: std::sync::LazyLock = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all") + }); + *ENV +} + fn tx_select() -> bool { static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { crate::envflags::var("EC_AV1_TX_SELECT") @@ -2546,12 +2696,15 @@ impl Plane<'_> { let At { x, y, side, reach, .. } = at; let tx = side >> depth; let n = 1usize << depth; - let set = match tx { - 32 => TxbSet::Luma32, - 16 => TxbSet::Luma16, - 8 => TxbSet::Luma8, - _ => TxbSet::Luma4, - }; + let set = luma_set_for( + match tx { + 32 => TxbSet::Luma32, + 16 => TxbSet::Luma16, + 8 => TxbSet::Luma8, + _ => TxbSet::Luma4, + }, + search.screen, + ); let mut levels = vec![0i32; side * side]; census_add(4, n * n); // A unit smaller than its block reads the neighbour magnitude table @@ -2610,7 +2763,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)); } @@ -3001,7 +3165,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; @@ -3864,6 +4031,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 @@ -4840,7 +5021,7 @@ fn code_square( y, side, reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), - set: luma_set, + set: luma_set_for(luma_set, search.screen), }; let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) = luma.search_block(at, search, mode_bits, fctx); @@ -7128,6 +7309,9 @@ pub(crate) fn encode_key_frame_inner( IBC_SHARE.with(|c| c.set(ibc_share)); let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; header.allow_screen_content_tools = screen; + // lane-txi: the wider `tx_type` alphabets, gated by the same content + // rule the type search itself stands behind ([`wide_tx_set`]). + header.reduced_tx_set = !wide_tx_set(screen); header.allow_intrabc = allow_intrabc; header.render_width = render.0 as u32; header.render_height = render.1 as u32; @@ -7582,7 +7766,10 @@ pub(crate) fn encode_key_frame_inner( // defaults again (spec 7.20's `started_from` arm) -- the first inter // frame after it therefore starts from the defaults too. let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); - let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); + let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); + // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set` + // from -- `Cdfs::txb` widens every luma set under it. + cdfs.reduced_tx_set = header.reduced_tx_set; let start_cdfs = CdfSnapshot(cdfs); // The luma restoration-unit grid this frame's `lr_params` implies // (`av1_lr_count_units` rounds to nearest, so a short last unit is @@ -10474,6 +10661,9 @@ pub(crate) fn encode_inter_frame( let screen = seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height); header.allow_screen_content_tools = screen; + // lane-txi, as on the key frame: the header bit the writer's own + // `Cdfs` then reads for every luma `tx_type` symbol. + header.reduced_tx_set = !wide_tx_set(screen); // The search prices coefficients against the tables this frame's writer // starts from, not against the defaults (lane-av1txbits) -- but only on a // frame the screen detector said no to (lane-av1price2): armed HERE, after @@ -11298,9 +11488,13 @@ pub(crate) fn encode_inter_frame( // next frame's writer starts from them -- exactly what // `crate::stream::stored_cdfs_for` hands the decoder. let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); - let cdfs = start_cdfs + let mut cdfs = start_cdfs .cloned() .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); + // lane-txi: set per frame, never inherited from the snapshot the + // previous frame stored -- the content gate can flip the bit between + // frames (class `per-tile-state-not-reset`). + cdfs.reduced_tx_set = header.reduced_tx_set; let start_cdfs = CdfSnapshot(cdfs); let reference_select_bit = header.reference_select; let switchable_motion_mode = header.is_motion_mode_switchable; @@ -11489,6 +11683,9 @@ pub(crate) fn encode_inter_frame( Some(mc::InterpFilterKind::Regular), seq.enable_dual_filter, h.reference_select, + // lane-txi: this frame's own bit, not the hardcoded `true` + // the wrapper used to pass. + h.reduced_tx_set, tx_select, lr, // The trial decode re-reads the tile the writer just wrote, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 60a678f7..b3962a8a 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3811,6 +3811,124 @@ 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] + #[ignore = "reduced_tx_set = 0 desyncs the encoder's own trial decode when the \ + seven-type intra search is on -- bisected in lanes/txi.report.md; \ + the lever is off at every preset until that is closed"] + 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:?}" + ); + // The INTER units of this same frame are coded into the + // twelve/sixteen-symbol alphabets too (the header bit widens + // every luma set at once), but their SEARCH still offers the + // two-type list -- see `encode::inter_luma_set`'s note on the + // reference-slot refusal the wider inter candidates trip. So the + // statement here is that those units still decode sample-exact + // out of the wider alphabet, which the two decoders below make. + assert!( + inter.iter().sum::() > 0, + "the clip coded no inter luma transform unit at all: {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 diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs index e5590910..e925d637 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -512,6 +512,15 @@ pub(crate) const TX_TYPE_SEARCH_INTER: [bool; 11] = [ true, true, true, true, true, true, true, false, false, false, false, ]; +/// `encode::wide_tx_set`: whether a frame codes `reduced_tx_set = 0`, the +/// wider `tx_type` alphabets (intra 8x8/4x4 seven types, inter 16x16 twelve, +/// inter 8x8/4x4 sixteen) instead of the reduced sets every stream this +/// encoder wrote before lane-txi carries. OFF at every preset until the gate +/// says otherwise; `EC_AV1_TXSET_WIDE` overrides. +pub(crate) const WIDE_TX_SET: [bool; 11] = [ + false, false, false, false, false, false, false, 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/lanes/txi.report.md b/lanes/txi.report.md new file mode 100644 index 00000000..4f5b1e51 --- /dev/null +++ b/lanes/txi.report.md @@ -0,0 +1,174 @@ +# lane-txi -- the intra type search's film loss, and `reduced_tx_set = 0` + +Branch `lane-txi` off main `f6c67770`. Predecessors: `lanes/txset.report.md` +(intra five-type set, screen-gated), `lanes/txset2.report.md` (inter +`DCT_IDTX`, screen-gated), `lanes/txrd.report.md` (the inter chroma-inherit +fix). + +## 1. The instrument: WHERE the intra unconditional arm loses (12-frame gate) + +`EC_AV1_TXSET=all` is new here -- it lifts the intra search's screen gate +without touching the preset lever -- and the gate already prints per-frame AND +per-plane PSNR under `EC_AV1_FRAME_PSNR=1` (lane-txrd's instrument). + +Control and arm both REPRODUCE the charter's numbers to the digit: bars 1080p +-1.0/-16.8 -> -2.3/-17.8, film A **+21.7/-4.4 -> +22.1/-4.0**. + +film A, per plane, per frame (frame 0 is the key frame; q=60 shown, q=150 +identical in shape): + +| plane | control | arm (`EC_AV1_TXSET=all`) | +|---|---|---| +| Y | 51.72 46.53 47.40 46.51 47.10 47.09 46.50 ... | **51.73 46.55 47.42 46.52 47.13 47.12 46.52 ...** | +| U | 52.52 49.39 49.75 49.44 49.65 49.87 49.60 ... | **52.52 49.41 49.77 49.49 49.68 49.90 49.62 ...** | +| V | 52.39 49.26 49.79 49.25 49.65 49.45 49.08 ... | **52.39 49.27 49.81 49.28 49.67 49.44 49.10 ...** | + +READING, and it refutes the charter's premise: the arm is EQUAL OR BETTER on +every frame, every plane and both quantizers shown -- the key frame included, +the leaves included. There is no plane collapse (lane-txrd's chroma class) and +no propagation shape (the leaves do not decay relative to the key frame), so +**a reference-aware `lambda` term has no signal to act on and was not built**. + +What the arm actually spends is BYTES: 64392 -> 65201, 102508 -> 103781, +170169 -> 172167, 413430 -> 419156, i.e. +1.2..1.4% of rate for +0.02..0.06 dB. +That is a rate term the type decision under-charges (class +`rd-rate-term-calibration`), not a distortion it mis-measures. + +DEVIATION FROM THE CHARTER, stated: instead of the reference-aware term, this +lane builds the term the instrument points at -- `encode::non_dct_surcharge`, +`(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits` charged to a non-`DCT_DCT` +candidate only (the incumbent is always `DCT_DCT`, so the block's returned +cost stays its true one). The intra decision now reads the same +`EC_AV1_TXRD_LAMBDA` the inter one already did. Sweep below. + +## 2. `reduced_tx_set = 0`: the writer half, and the defect that blocks it + +Commit `95b4bee9`. The bit is read in ONE place on the writer side: + +* `Cdfs::reduced_tx_set` (default `true`) + `TxbSet::wide()` -- every luma + set's `Set1` counterpart, transcribed from `decode::txbset_for` / + `txbset_for_inter` / `inter_txbset_for`, applied at the top of `Cdfs::txb`. + The `Set1` tables differ from their narrow twins in the `tx_type` field + ONLY, so this is the whole writer-side map; the writer's symbol already + comes from `decode::tx_type_symbol(cdf.len(), ..)`, so the wider alphabets + need no writer change at all. The decoder never sets the field (it names the + wide set itself; widening a wide set is the identity). +* `encode::wide_tx_set(screen)` (`EC_AV1_TXSET_WIDE` = `0`/`screen`/`1`, + `speed::WIDE_TX_SET` false at every preset) drives `header.reduced_tx_set` + on both header sites, and the frame's `Cdfs` reads the header bit. +* `encode::luma_set_for` gives the SEARCH and its pricer the same widened set, + so the two agree on what a `tx_type` symbol costs. +* Candidates: intra 8x8/4x4 get the seven-type `TX_SET_INTRA_1`; the twelve- + and sixteen-type inter lists are written (the seven types both alphabets + share) but NOT offered -- see below. + +BLOCKER, bisected: with the bit off, the encoder's own trial decode of the +tile it just wrote (`filter_search::pick_filters` -> `decode_inter_frame_ +tiles_lr`) desyncs and reads `BWDREF` on a frame that holds no such picture -- +"a reference frame selected with no picture at this frame's own ref_frame_idx +slot for it", refused out of `decode::ref_dims` (new probe: +`EC_AV1_REFPROBE=1` prints the missing reference and the backtrace). Bisection: + +| arm | result | +|---|---| +| wide bit + both type searches OFF | PASS (witness + ffmpeg exact) | +| wide bit + INTER search on, intra off | PASS | +| wide bit + INTRA search on (7-type set) | **FAIL, the refusal above** | +| wide bit off, `EC_AV1_TXRD_LAMBDA` 0/0.5/4 (cost perturbation alone) | PASS | + +So it is not RD noise and not the inter half: something in the SEVEN-type +intra path writes a symbol the reader resolves differently. One real defect was +found and fixed on the way (`decode_inter_frame_tiles_lr` hardcoded +`reduced_tx_set = true` for the encoder's own trial decode -- the class its +neighbours' doc comments name, a header bit a raw tile decode cannot guess); +it is not the whole story, the desync survives it. + +`speed::WIDE_TX_SET` is therefore false at every preset and +`EC_AV1_TXSET_WIDE` unset is byte-identical to main. + +## 3. The surcharge sweep (12-frame gate, `EC_AV1_TXSET=all`, film rows) + +BD-rate vs libaom `cpu-used 6` / rav1e `speed 6`, lower is better. Every arm is +the UNCONDITIONAL intra search (the shipped default is screen-gated and +byte-identical to the control on these rows). + +| clip | control | 1x (the plain arm) | 2x (`EC_AV1_TXRD_LAMBDA=2`) | 0.5x | +|---|---|---|---|---| +| bars 1080p | -1.0% / -16.8% | -2.3% / -17.8% | -1.2% / -16.9% | -0.8% / -16.5% | +| film A | +21.7% / -4.4% | +22.1% / -4.0% | **+21.7% / -4.3%** | +22.3% / -3.9% | + +film A bytes: control 64392/102508/170169/413430, 1x 65201/103781/172167/419156 +(+1.2..1.4%), 2x 64518/102989/170564/414763 (+0.2..0.3%), 0.5x +64731/103742/171929/418934. The sweep is MONOTONE in the weight on both rows: +0.5x spends more and loses more (film A +22.3/-3.9), 2x spends least and loses +least. + +READING: the surcharge does exactly what the instrument predicted -- it buys +the rate back (the arm's +1.3% of bytes collapses to +0.2%) and the film A row +walks from +22.1/-4.0 to +21.7/-4.3, i.e. onto the control against libaom and +0.1 SHORT of it against rav1e. It neutralises the loss; it does not turn it +into a win, because what the search wins on film (0.02-0.06 dB) is smaller +than what its symbols cost however they are priced. The same surcharge costs +the bars row a point of its own gain (-2.3 -> -1.2), which is the sign that a +single flat weight cannot serve both content classes. + +KEEP RULE: FAIL for the unconditional arm at every weight measured -- the rule +wants both film rows DOWN, and the best weight lands film A ON the control. +DECISION: the intra search stays SCREEN-GATED, the surcharge ships at its +default weight of 1.0 (`non_dct_surcharge` returns 0, so every default stream +is byte-identical to main), and `EC_AV1_TXRD_LAMBDA` stays the swept lever. + +## 4. Invariants, pins, suite + +Default state = every lever of this lane OFF (`WIDE_TX_SET` false at all +presets, surcharge weight 1.0, the intra/inter searches on their own screen +gates), so the shipped encoder is byte-identical to main -- which the pins +make below. + +| invariant | preset 0 | preset 6 | +|---|---|---| +| `an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly` | PASS | PASS | +| `an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly` | PASS | PASS | +| `the_facade_codes_the_same_bytes_as_encode_sequence` | PASS | PASS | +| `predicted_coeff_bits_track_the_tile_the_writer_wrote` | PASS | PASS | +| `tile_bytes_do_not_depend_on_the_thread_count --include-ignored` | PASS | PASS | +| the three above under `EC_COMP_MISMATCH=1` (preset 0) | 0 mismatches | -- | + +`the_encoders_own_streams_are_byte_identical_to_their_pins`: PASS at the +UNCHANGED 8562 / 33357, and again under `EC_AV1_TXSET=0 EC_AV1_TXSET_INTER=0`. +`timeout 890 cargo check --workspace --all-targets -j4`: 0 errors, 0 `ec-av1` +warnings (the 22 the workspace prints are `ec-opus`/`ec-vorbis`, untouched). + +`a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly` is +`#[ignore]`d with the blocker in its reason string -- it is the witness that +closes section 2 the moment the desync is found. + +LONG-GOP: not re-run, and it does not need to be -- what ships changes no +byte (pins unchanged, every lever off by default), so +`bd_rate_film_long_gop` stands at the head's own +26.4/-6.6 (film A) and ++89.8/+9.1 (film B). + +## 5. Deferred + +* `deferred: reduced_tx_set = 0 -- the writer half is BUILT and off by default; + what blocks it is a desync between the seven-type intra path's writer and the + encoder's own trial decode (section 2's bisection table), which shows up as a + refused reference slot. What unblocks it: the first symbol where the trial + decode's range diverges from the writer's (class equal-range-means-unread / + compare-range-not-tell), on the two-frame witness that already reproduces it + in 2 seconds -- one lane slot, no gate wall.` +* `deferred: the twelve/sixteen-type INTER candidate lists -- written + (encode::inter_tx_type_candidates' INTER_WIDE) but never offered, since the + header bit they need is the blocked one above. Unblocked by the same fix.` +* `deferred: the reference-aware type cost the charter asked for -- NOT BUILT, + and deliberately: the per-plane per-frame instrument (section 1) shows the + arm equal-or-better on the key frame AND every leaf, so there is no + propagation signal for such a term to price. What would revive it: a content + class whose leaves DO decay under the arm.` +* `deferred: the surcharge as a per-content lever (screen 1.0, film 2.0) -- + measured on film A only; film B and the capture were not swept. Unblocked by + two more gate slots. As a flat default it is a wash, which is why it ships + at 1.0.` +* `deferred: EC_AV1_REFPROBE=1 is a new decoder-side probe (the missing + reference slot plus a backtrace); it is env-gated and costs a branch on an + error path only.`