diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 5e41521c..232a81fc 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -5997,6 +5997,14 @@ pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option { } } +/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide +/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it +/// (class `table-and-reader-move-together` -- the writer picks its symbol +/// through the reader's own map, so the two cannot drift). +pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option { + (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type)) +} + /// The remainder of a level the base and base-range syntax could not reach /// (spec 5.11.40): its bit length in unary, then that many of its own bits, /// most significant first — the exact inverse of [`crate::tile::write_golomb`]. diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 2e1857d6..6c5fe0f7 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -252,6 +252,48 @@ fn tx_select_inter() -> bool { ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER)) } +/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control +/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points +/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 -> +/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1. +/// The keep rule wants both films down, so this takes the same content gate +/// palette, intrabc and the angle-delta refinement already stand behind: a +/// non-screen frame is byte-identical to the encoder before the lane. +/// +/// The transform types an intra luma transform unit of `set` may be coded +/// with -- exactly the alphabet the writer's `tx_type` symbol names for that +/// set, so a searched type is always one the tile can express (lane-txset). +/// `DCT_DCT` first: it is the incumbent every other candidate has to beat. +/// +/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16 +/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types +/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all, +/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT` +/// here. +pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] { + const DCT: [TxType; 1] = [TxType::DctDct]; + const INTRA2: [TxType; 5] = [ + TxType::DctDct, + TxType::AdstAdst, + TxType::AdstDct, + TxType::DctAdst, + TxType::Idtx, + ]; + match set { + TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if screen && tx_type_search() => &INTRA2, + _ => &DCT, + } +} + +fn tx_type_search() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TXSET") + .ok() + .map(|v| !matches!(v.as_str(), "0" | "off")) + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH)) +} + fn tx_select() -> bool { static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { crate::envflags::var("EC_AV1_TX_SELECT") @@ -2128,6 +2170,7 @@ impl Plane<'_> { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); let bits = crate::tile::rdoq( &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(), + tx_type, ); (levels, Some(bits)) } else { @@ -2182,12 +2225,13 @@ impl Plane<'_> { } else { { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); - crate::tile::coeff_bits( + crate::tile::coeff_bits_typed( &levels, at.set, crate::decode::q_ctx_of(base_q_idx), skip_ctx, sign_ctx, + tx_type, ) } }; @@ -2258,6 +2302,7 @@ impl Plane<'_> { 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, ); (levels, Some(bits)) } else { @@ -2353,7 +2398,7 @@ impl Plane<'_> { // `filter_intra`), not once over the whole block. filter_intra: Option, search: &Search, fctx: &crate::decode::FrameCtx, - ) -> (Vec, f64, f64) { + ) -> (Vec, f64, f64, Vec) { let At { x, y, side, reach, .. } = at; let tx = side >> depth; let n = 1usize << depth; @@ -2369,6 +2414,11 @@ impl Plane<'_> { // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]). self.ctx.tu_split = n > 1; let (mut sse, mut bits) = (0.0, 0.0); + // One entry per unit at its own `tu_row * n + tu_col`, which is how + // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the + // frame edge cuts away is never coded there, so a compacted list + // would slide every later unit's type onto the wrong transform. + let mut tx_types = vec![TxType::DctDct; n * n]; for tu_row in 0..n { for tu_col in 0..n { let (col_off, row_off) = (tu_col * tx, tu_row * tx); @@ -2406,7 +2456,27 @@ impl Plane<'_> { ) } None => { - self.trial(tu, mode, angle_delta, search.base_q_idx, search.deadzone, fctx) + // lane-txset: the unit picks its own transform type + // out of the set the writer can name it in, priced + // through the same RDOQ'd trial path (its `bits` + // already carry the `tx_type` symbol itself). + let mut best: Option<(f64, TxType, Trial)> = None; + for &tx_type in tx_type_candidates(set, search.screen) { + let candidate = self.trial_typed( + tu, mode, angle_delta, search.base_q_idx, search.deadzone, + tx_type, fctx, + ); + let cost = candidate.sse + search.lambda * candidate.bits; + if best.as_ref().is_none_or(|(best, _, _)| cost < *best) { + best = Some((cost, tx_type, candidate)); + } + } + let (_, tx_type, trial) = + best.expect("the candidate list is never empty"); + tx_types[tu_row * n + tu_col] = tx_type; + TX_TYPE_HITS[tx_type as usize] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + trial } }; sse += trial.sse; @@ -2419,7 +2489,7 @@ impl Plane<'_> { } } self.ctx.tu_split = false; - (levels, sse, bits) + (levels, sse, bits, tx_types) } /// Writes a trial's reconstruction back into the plane, and the @@ -2637,7 +2707,7 @@ impl Plane<'_> { at: At, search: &Search, mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, - ) -> (Vec, u8, i32, f64) { + ) -> (Vec, u8, i32, f64, TxType) { let At { x, y, side, reach, .. } = at; @@ -2777,6 +2847,23 @@ impl Plane<'_> { ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize] .fetch_add(1, std::sync::atomic::Ordering::Relaxed); } + // lane-txset: the block's own transform type, searched on the mode + // and angle the trials above settled -- the same ordering the angle + // refinement uses, and the same RD terms. + let mut tx_type = TxType::DctDct; + for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) { + let candidate = self.trial_typed( + at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx, + ); + let cost_t = + candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]); + if cost_t < cost { + cost = cost_t; + tx_type = candidate_type; + trial = candidate; + } + } + TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed); if census_on() { LUMA_RANK[sad_rank(&ranking, mode).min(12)] .fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -2784,7 +2871,7 @@ impl Plane<'_> { self.commit(x, y, side, &trial); // A 64-point transform codes only its top-left 32x32 corner, which is // the grid `code_from_prediction` hands back (lane-i64). - (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost) + (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type) } } @@ -3586,6 +3673,19 @@ fn tx_depth_bits(side: usize, depth: usize) -> f64 { } } +/// 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. +pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; + +/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the +/// counts to its own encode. +#[cfg(test)] +pub(crate) fn take_tx_type_hits() -> [usize; 16] { + std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// How many blocks resolved to each `tx_depth`, the fire count that says /// whether the depth search below reaches its candidates at all. static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = @@ -4377,8 +4477,9 @@ fn code_square( reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), set: luma_set, }; - let (mut luma_coeffs, mode, angle_delta, mut cost) = + let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) = luma.search_block(at, search, mode_bits, fctx); + let mut luma_tx_types = vec![tx_type]; // The depth search runs on the mode the whole-block transform picked -- // libaom's own ordering, and the reason it costs one extra pass per depth // rather than one per (mode, depth) pair. @@ -4398,15 +4499,19 @@ fn code_square( luma.snapshot(x, y, side), luma_coeffs, ); + let mut best_types = std::mem::take(&mut luma_tx_types); for depth in 1..=max_tx_depth(side) { - let (levels, sse, bits) = luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx); + let (levels, sse, bits, types) = + luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx); let cost_d = sse + search.lambda * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth)); if cost_d < best.0 { best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side)); + best_types = types; } } + luma_tx_types = best_types; luma.restore(x, y, side, &best.2); cost = best.0; tx_depth = best.1 as u8; @@ -4503,7 +4608,10 @@ fn code_square( let mut best: Option<(f64, u8, usize, (Vec, Vec), Vec)> = None; for fi in 0..5u8 { for depth in 0..=max_depth { - let (levels, sse, bits) = + // A filter-intra block's units are coded through + // `code_from_prediction`, which is `DCT_DCT` throughout, so + // this arm keeps the empty (all-`DCT_DCT`) type list. + let (levels, sse, bits, _) = luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx); let cost_f = sse + search.lambda @@ -4564,6 +4672,12 @@ fn code_square( } } } + // A palette or filter-intra block's luma was recoded through `DCT_DCT` + // (its levels came from `code_from_prediction`), so the searched types + // belong to a block this one no longer is. + if palette.is_some() || filter_intra.is_some() { + luma_tx_types = Vec::new(); + } ( BlockCoeffs { u, @@ -4577,6 +4691,7 @@ fn code_square( filter_intra, cfl_alphas, angle_delta_y: angle_delta as i8, + luma_tx_types, ..BlockCoeffs::default() }, cost, @@ -5847,6 +5962,7 @@ fn code_square_inter( palette: None, palette_uv: None, tx_depth, + luma_tx_types: Vec::new(), inter: Some(info), motion_mode: motion_won, }, @@ -5869,6 +5985,7 @@ fn code_square_inter( 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(), angle_delta_y: 0, cfl_alphas: None, filter_intra: None, @@ -9117,6 +9234,7 @@ fn search_inter_block( chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); ( BlockCoeffs { + luma_tx_types: Vec::new(), angle_delta_y: 0, cfl_alphas: None, filter_intra: None, @@ -11802,6 +11920,7 @@ mod tests { let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); let residual_block = BlockCoeffs { + luma_tx_types: Vec::new(), 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 fbbe1e23..ff15b2e3 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3615,6 +3615,118 @@ mod tests { eprintln!("delta_q witness: {levels} quantizer levels, {} bytes", stream.len()); } + /// lane-txset's witness: a clip of hard directional edges makes the intra + /// luma search take EVERY type of the five-type reduced set + /// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`, + /// `IDTX`) 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 the lane the writer coded + /// `DCT_DCT` for every luma transform unit ever written, so this is also + /// the statement that the other four are REACHABLE at all. + #[test] + fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() { + // `knob_write`: the screen override below is process-global, and the + // type search is SCREEN-ONLY (`encode::tx_type_candidates`). + let _knobs = crate::speed::knob_write(); + crate::encode::force_screen(Some(true)); + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (320usize, 192usize); + // Sharp horizontal and vertical steps: a vertical edge is what an + // `ADST` column pass beats a `DCT` one on, a horizontal edge the + // mirror, and the flat/ramp areas between them are where `IDTX` wins. + let sources: Vec = (0..2) + .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 * 4) / 16 % 2, y / 16 % 2) { + (0, 0) => 16u16, + (1, 0) => 235, + (0, 1) => (x % 64 * 3) as u16, + _ => (y % 64 * 3) as u16, + }; + p.y[y * width + x] = v; + } + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 2, + 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 mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let hits = crate::encode::take_tx_type_hits(); + // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above + // the presets that carry it only `DCT_DCT` is offered, and the + // exactness half below is what still runs there. The FULL five-type + // fire count is preset 0's to make: a faster preset prunes modes and + // partitions before a type is ever priced on them, so `ADST_ADST` and + // `IDTX` stop winning on this clip at preset 6 (measured: hits + // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever + // still has to reach SOME non-`DCT_DCT` type -- that is the + // "reachable at all" statement, class `gate-blind-to-feature`. + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) { + let non_dct: usize = hits.iter().sum::() + - hits[crate::transform::TxType::DctDct as usize]; + assert!( + non_dct > 0, + "every luma transform unit took DCT_DCT: {hits:?}" + ); + } + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { + for (name, ty) in [ + ("DCT_DCT", crate::transform::TxType::DctDct), + ("ADST_ADST", crate::transform::TxType::AdstAdst), + ("ADST_DCT", crate::transform::TxType::AdstDct), + ("DCT_ADST", crate::transform::TxType::DctAdst), + ("IDTX", crate::transform::TxType::Idtx), + ] { + assert!( + hits[ty as usize] > 0, + "no luma transform unit took {name}: {hits:?}" + ); + } + } else { + eprintln!( + "SKIP the five-type fire count at preset {}: {hits:?}", + 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"); + } + crate::encode::force_screen(None); + eprintln!("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 52ab535b..50440701 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -483,6 +483,14 @@ pub(crate) const RESTORATION: [bool; 11] = [ pub(crate) const TPL_DEPTH: [usize; 11] = [crate::encode::TPL_DEPTH, 8, 8, 4, 4, 4, 4, 1, 1, 1, 1]; +/// `encode::tx_type_search`: whether an intra luma transform unit searches +/// its own `tx_type` instead of coding `DCT_DCT` (lane-txset). The five-type +/// reduced-set alphabet the writer already codes is what it picks from, so a +/// preset that turns it off is byte-identical to the encoder before the lane. +pub(crate) const TX_TYPE_SEARCH: [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 c9392f35..40875e3f 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -21,6 +21,7 @@ use crate::cdf; use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; use crate::msac::SymbolEncoder; +use crate::transform::TxType; use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16}; // --------------------------------------------------------------------------- @@ -1674,6 +1675,10 @@ pub struct Coeff { pub struct BlockCoeffs { /// The luma transform's coefficients. pub luma: Vec, + /// One transform type per luma transform unit, raster order (lane-txset). + /// Empty is `DCT_DCT` throughout -- what every block coded before the + /// search offered a type, and what an inter block still carries. + pub luma_tx_types: Vec, /// The U plane's. pub u: Vec, /// The V plane's. @@ -3994,6 +3999,7 @@ fn write_block( &grids[0], tx_mode, all_scans, + &block.luma_tx_types, )?; tx < side } else { @@ -4008,6 +4014,7 @@ fn write_block( &neighbours.around(at, side), tx_mode, tx_select, + block_tx_type(block), ); neighbours.record_planes(at, side, mode, grids, !split); clear_skip_band(neighbours, at_mi, side); @@ -4092,6 +4099,7 @@ fn write_leaf8( &grids[0], tx_mode, all_scans, + &block.luma_tx_types, )?; tx < 8 } else { @@ -4106,6 +4114,7 @@ fn write_leaf8( &neighbours.around_mi(leaf_mi, 8), tx_mode, tx_select, + block_tx_type(block), ); neighbours.record_mi_planes(leaf_mi, 8, grids, !split); clear_skip_band(neighbours, leaf_mi, 8); @@ -4127,6 +4136,9 @@ fn write_block_planes( // A block whose luma was already written as several transform units // ([`write_luma_select`]) has only its chroma planes left here. skip_luma: bool, + // This block's single luma transform type (lane-txset); chroma's is + // derived from its mode by the decoder and codes no symbol. + luma_tx_type: TxType, ) { for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() { if plane == 0 && skip_luma { @@ -4153,6 +4165,7 @@ fn write_block_planes( skip_ctx, dc_sign_ctx(around[plane].dc_vote), Some(plane), + if plane == 0 { luma_tx_type } else { TxType::DctDct }, ); #[cfg(test)] census_record( @@ -4173,6 +4186,12 @@ fn write_block_planes( } } +/// The single luma transform type a block carries, `DCT_DCT` for one that +/// never searched one (lane-txset). +fn block_tx_type(block: &BlockCoeffs) -> TxType { + block.luma_tx_types.first().copied().unwrap_or(TxType::DctDct) +} + /// The `(side / tx)^2` transform units of one block's luma residual, raster /// order, each with its own coefficient context and each published before the /// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch). @@ -4192,6 +4211,10 @@ fn write_luma_tus( // lane-av1tx2 r2: an INTER block's split units read the inter coefficient // tables, not the intra ones (`TxbSet::Luma*Inter`). inter: bool, + // One transform type per unit in this same raster order (lane-txset). + // Empty -- what every caller that never searched a type passes -- is + // `DCT_DCT` throughout, the one type this writer used to code. + tx_types: &[TxType], ) -> Result<()> { if tx < side && side > 32 && tx < 32 { // A 64x64 block's own levels reach the writer as the 32x32 corner a @@ -4268,6 +4291,10 @@ fn write_luma_tus( skip_ctx, dc_sign_ctx(around.dc_vote), Some(0), + tx_types + .get(tu_row * n + tu_col) + .copied() + .unwrap_or(TxType::DctDct), ); #[cfg(test)] census_record( @@ -4308,6 +4335,7 @@ fn write_luma_select( grid: &[i32], mode: usize, scans: &[Vec; 4], + tx_types: &[TxType], ) -> Result { let max_tx = side.min(64); let ctx = neighbours.tx_size_ctx(at_mi, max_tx); @@ -4324,7 +4352,7 @@ fn write_luma_select( } } let tx = max_tx >> depth; - write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false)?; + write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false, tx_types)?; neighbours.record_tx(at_mi, side, tx); Ok(tx) } @@ -4697,6 +4725,19 @@ fn scan_of(side: usize) -> &'static Vec { } pub(crate) fn coeff_bits( + grid: &[i32], + set: TxbSet, + q_ctx: usize, + skip_ctx: usize, + sign_ctx: usize, +) -> f64 { + 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` +/// 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( grid: &[i32], set: TxbSet, q_ctx: usize, @@ -4708,6 +4749,7 @@ pub(crate) fn coeff_bits( // largest remaining pricer error for every other block. skip_ctx: usize, sign_ctx: usize, + tx_type: TxType, ) -> f64 { // `Cdfs::new` builds every table a tile writer adapts -- tens of // kilobytes -- and this function is called once per priced candidate: @@ -4743,7 +4785,7 @@ pub(crate) fn coeff_bits( } let scan = scan_of(coding.side); let mut enc = SymbolEncoder::pricer(); - write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None); + write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None, tx_type); enc.bits() }; // lane-av1speed2: 60% of the transform units of an inter stream hold no @@ -4842,6 +4884,7 @@ pub(crate) fn rdoq( skip_ctx: usize, sign_ctx: usize, lambda: f64, + tx_type: TxType, ) -> f64 { // A 64-point transform carries its top-left 32x32 alone, and that corner // is what the writer and the pricer take (`coded_corner`). @@ -4857,16 +4900,17 @@ pub(crate) fn rdoq( q_ctx: usize, skip_ctx: usize, sign_ctx: usize, + tx_type: TxType, ) -> f64 { if dense.is_empty() { - return coeff_bits(levels, set, q_ctx, skip_ctx, sign_ctx); + return coeff_bits_typed(levels, set, q_ctx, skip_ctx, sign_ctx, tx_type); } for row in 0..coded { dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]); } - coeff_bits(dense, set, q_ctx, skip_ctx, sign_ctx) + coeff_bits_typed(dense, set, q_ctx, skip_ctx, sign_ctx, tx_type) } - let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx); + let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type); // The DC has its own quantiser, so its squared error per unit of level is // `(dc_q / ac_q)^2` of an AC coefficient's. let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx))); @@ -4905,7 +4949,7 @@ pub(crate) fn rdoq( let candidate = level - level.signum(); levels[i] = candidate; budget -= 1; - let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx); + let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx, tx_type); let distortion = weight * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2)); if distortion + lambda * (after - bits) < 0.0 { @@ -5177,6 +5221,10 @@ fn write_coeffs( skip_ctx: usize, sign_ctx: usize, plane: Option, + // Which transform type these levels were produced with (lane-txset). + // Only a luma set whose alphabet holds more than one type codes it; + // chroma never codes a `tx_type` symbol at all. + tx_type: TxType, ) { if let Some(plane) = plane { ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell())); @@ -5212,8 +5260,18 @@ fn write_coeffs( // A luma transform whose type set holds more than one type codes which it // is, right after the all-zero flag (spec 5.11.39). The writer only ever // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`. - if let Some(tx_type) = coding.tx_type.as_deref_mut() { - enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type); + if let Some(cdf) = coding.tx_type.as_deref_mut() { + // The symbol comes from the DECODER's own map, keyed by this set's + // alphabet width, so a type this set cannot express is caught here + // rather than desyncing the tile. The search only ever offers types + // the set holds ([`crate::encode::tx_type_candidates`]). + let symbol = crate::decode::tx_type_symbol(cdf.len(), tx_type); + debug_assert!( + symbol.is_some(), + "{tx_type:?} is not in the {}-symbol tx_type set", + cdf.len() - 1 + ); + enc.symbol(symbol.unwrap_or(TX_TYPE_DCT_DCT_SET2), cdf); if plane.is_some() { ec_rng_trace(|| format!("EC_TXTYPE tell={} rng={}", enc.tell(), enc.rng())); } @@ -6242,6 +6300,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( 0, &all_scans, true, + &block.luma_tx_types, )?; } write_block_planes( @@ -6253,6 +6312,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( &neighbours.around(sb_at, SB), 0, split, + block_tx_type(block), ); neighbours.record_planes(sb_at, SB, 0, &grids, !split); } @@ -6690,6 +6750,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( mode_for_tx, &all_scans, is_inter, + &block.luma_tx_types, )?; } write_block_planes( @@ -6705,6 +6766,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( &neighbours.around(at, BLOCK), mode_for_tx, split, + block_tx_type(block), ); neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); } @@ -6929,6 +6991,7 @@ fn write_inter_frame_leaf( if split { write_luma_tus( enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter, + &block.luma_tx_types, )?; } write_block_planes( @@ -6944,6 +7007,7 @@ fn write_inter_frame_leaf( &neighbours.around(at, SUB), mode_for_tx, split, + block_tx_type(block), ); neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); } @@ -7184,6 +7248,7 @@ fn write_inter_frame_leaf8( if split { write_luma_tus( enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter, + &block.luma_tx_types, )?; } write_block_planes( @@ -7195,6 +7260,7 @@ fn write_inter_frame_leaf8( &neighbours.around_mi(leaf_mi, 8), mode_for_tx, split, + block_tx_type(block), ); neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block)); @@ -7939,6 +8005,7 @@ mod tests { 0, 0, None, + TxType::DctDct, ); priced += luma_32_coeff_bits(grid); } @@ -8887,7 +8954,7 @@ mod tests { .sum(); d + lambda * coeff_bits(grid, set, crate::decode::q_ctx_of(q), 0, 0) }; - let bits = rdoq(&mut levels, &scaled, side, q, set, 0, 0, lambda); + let bits = rdoq(&mut levels, &scaled, side, q, set, 0, 0, lambda, TxType::DctDct); assert_eq!(bits, coeff_bits(&levels, set, crate::decode::q_ctx_of(q), 0, 0)); assert!(cost(&levels) <= cost(&before), "{:?} vs {:?}", cost(&levels), cost(&before)); // The tail is what it is for: the last coded position moves earlier. @@ -8908,7 +8975,7 @@ mod tests { if v < 0.0 { -l } else { l } }) .collect(); - let bits = rdoq(&mut levels, &scaled, side, q, set, 0, 0, lambda); + let bits = rdoq(&mut levels, &scaled, side, q, set, 0, 0, lambda, TxType::DctDct); let corner: Vec = (0..32) .flat_map(|row| levels[row * side..][..32].to_vec()) .collect(); diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index e6c056bf..bef434f3 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1483,11 +1483,25 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType if tx_type == TxType::DctDct { return forward_transform_2d(residual, side); } - debug_assert_eq!( - tx_type.flip(), - (false, false), - "a flipped ADST needs its residual mirrored before this basis applies" - ); + // A FLIPADST axis is the plain ADST kernel with the DECODER's output + // mirrored (`dequant_and_inverse_typed_wh`'s `ud_flip`/`lr_flip`: row + // `h - 1 - i`, column `w - 1 - j`). A mirror is its own inverse, so the + // analysis half is the same plain basis over the mirrored residual -- + // lane-txset, which is what lets every FLIPADST-bearing type share the + // kernels below instead of needing its own. + let (ud_flip, lr_flip) = tx_type.flip(); + let mirrored: Vec = if ud_flip || lr_flip { + (0..side) + .flat_map(|row| { + let src = if ud_flip { side - 1 - row } else { row }; + (0..side).map(move |col| (src, if lr_flip { side - 1 - col } else { col })) + }) + .map(|(r, c)| residual[r * side + c]) + .collect() + } else { + Vec::new() + }; + let residual: &[i32] = if mirrored.is_empty() { residual } else { &mirrored }; let (row_kind, col_kind) = tx_type.axes(); let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind)); let mut rows = vec![0.0f64; side * side]; @@ -2162,7 +2176,27 @@ mod tests { (sum / (side * side) as f64).sqrt() }; let dct = rmse(TxType::DctDct); - for tx in [TxType::AdstDct, TxType::DctAdst, TxType::AdstAdst] { + // lane-txset: every one of the sixteen types, not just the four + // 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 [ + TxType::AdstDct, + TxType::DctAdst, + TxType::AdstAdst, + TxType::Idtx, + TxType::VDct, + TxType::HDct, + TxType::VAdst, + TxType::HAdst, + TxType::VFlipAdst, + TxType::HFlipAdst, + TxType::FlipAdstDct, + TxType::DctFlipAdst, + TxType::FlipAdstFlipAdst, + TxType::AdstFlipAdst, + TxType::FlipAdstAdst, + ] { let e = rmse(tx); assert!( e < 2.0 * dct, diff --git a/lanes/txset.report.md b/lanes/txset.report.md new file mode 100644 index 00000000..533d9104 --- /dev/null +++ b/lanes/txset.report.md @@ -0,0 +1,194 @@ +# lane-txset -- the transform-type search + +Branch `lane-txset` off main `3ebe0de9`. Scope: which `tx_type` an intra luma +transform unit is coded with, the forward kernels the missing types need, and +the writer symbol that names them. + +## 1. Instrument: what was coded, what was searched (read off the code) + +The writer coded ONE transform type, everywhere, always: + + tile.rs:5216 enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type); // a constant + +and the search never varied a luma type either -- `search_block` and +`code_tx_depth` both go through `code_from_prediction`/`trial`, which pass +`TxType::DctDct` (`encode.rs:1993`, `:2278`). The only non-DCT types this +encoder has ever produced are CHROMA's, which code no symbol at all: the +decoder derives them from the chroma mode (`search_chroma` -> +`default_intra_tx_type`). + +STALE PREMISE IN THE CHARTER, corrected: this encoder writes +`reduced_tx_set: true` (`encode.rs:1660`, `:1760`) -- not 0. Under that bit +`get_tx_set` gives, per block class: + +| block class | tx size | set the WRITER uses | alphabet | types the search tried (before) | now | +|---|---|---|---|---|---| +| intra luma | 4x4, 8x8, 16x16 | `TX_SET_INTRA_2` (`intra_tx_type_{4,8,16}`) | 5 | DCT_DCT only | all 5 | +| intra luma | 32x32, 64x64 | none (`TxbSet::Luma{32,64}.tx_type == None`) | 1 | -- | -- | +| inter luma | 4x4..32x32 | `TX_SET_INTER_3` (`inter_tx_type_*`) | 2 (IDTX, DCT_DCT) | DCT_DCT only | DCT_DCT only | +| chroma | any | none, derived from uv_mode | -- | mode's default | unchanged | + +So the bytes reachable WITHOUT touching the frame header were the four +non-DCT members of `TX_SET_INTRA_2` on every intra luma unit at 16x16 and +below -- an alphabet the writer was already coding into, one symbol wide, and +never using. That is what this lane spends. + +Sets 13/17 (`DTT9_IDTX_1DDCT`, `ALL16`) that the charter names are NOT +reachable from here: they need `reduced_tx_set == 0` in the frame header, +which changes the alphabet of EVERY luma `tx_type` symbol in the stream +(`TxbSet::Luma*Set1`/`Set2` exist on the decode side with their CDFs; the +writer's set map at `tile.rs:4208` would have to take the bit). Deferred -- +see below. + +## 2. Forward kernels + +`forward_transform_2d_typed` is basis-driven (`TxType::axes`), so +`V_DCT`/`H_DCT`/`V_ADST`/`H_ADST` and the plain ADST family already had +kernels; the FLIPADST family was refused by a `debug_assert`. A flipped axis +is the plain ADST kernel with the DECODER's output mirrored (`ud_flip` -> +row `h-1-i`, `lr_flip` -> column `w-1-j`), and a mirror is its own inverse, +so the analysis half is the same basis over the MIRRORED residual -- 12 lines, +no new kernel. + +Check: `transform::tests::a_typed_forward_round_trips_like_the_dct_one`, now +over all SIXTEEN types at 4x4/8x8/16x16 (was 3), each round trip's rmse under +2x `DCT_DCT`'s. PASS. + +## 3. The search + the writer + +* `encode::tx_type_candidates(set)` returns exactly the alphabet the writer + can name for that set, so a searched type is always codable. +* `code_tx_depth` picks a type PER TRANSFORM UNIT (RD: sse + lambda * bits, + the trial's bits carrying the `tx_type` symbol itself through + `coeff_bits_typed`/`rdoq`), stored at `tu_row * n + tu_col` -- the writer's + own index, so a unit the frame edge cuts away cannot slide the rest. +* `search_block` picks one for a whole-block transform, on the mode and angle + already settled (libaom's ordering, the same shape the angle refinement has). +* `BlockCoeffs::luma_tx_types` carries them to `write_luma_tus` / + `write_block_planes`; empty = `DCT_DCT` throughout, which is every inter, + palette and filter-intra block. +* The symbol comes from the DECODER's own map (`decode::tx_type_symbol`, + keyed by the CDF's alphabet width), so writer and reader cannot drift -- + and it already answers for the 7/12/16-symbol sets a `reduced_tx_set == 0` + lane would turn on. +* Lever: `speed::TX_TYPE_SEARCH` (presets 0-6 on, 7-10 off) AND a content + gate -- SCREEN FRAMES ONLY, see the gate table below. `EC_AV1_TXSET=0` + forces it off entirely. + +## 4. Checks + +| check | result | +|---|---| +| `transform::tests::a_typed_forward_round_trips_like_the_dct_one` (16 types) | PASS | +| `encoder::tests::an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly` | PASS -- hits `[IDTX 12, DCT_DCT 15445, ADST_ADST 70, ADST_DCT 161, DCT_ADST 467]`, ours == ffmpeg every sample | +| `cargo test -p ec-av1 --lib --release round_trip` (19 tests) | PASS | +| `predicted_coeff_bits_track_the_tile_the_writer_wrote`, `tile_bytes_do_not_depend_on_the_thread_count --include-ignored`, `the_facade_codes_the_same_bytes_as_encode_sequence` | PASS | +| `cargo check -p ec-av1 --all-targets` | 0 errors, 0 warnings | + + +## 5. The 12-frame gate (`encode::tests::bd_rate_screen_native`, 12 frames, gop 12) + +Control re-run on this head first (`EC_AV1_TXSET=0`), arm = the search on for +every frame. BD-rate vs libaom cpu-used 6 / vs rav1e speed 6, lower is better; +wall is ours per row. + +| clip | control | arm (all frames) | delta | wall ctl -> arm | +|---|---|---|---|---| +| bars 1080p | -1.0% / -16.8% | -2.3% / -17.8% | -1.3 / -1.0 | 247.2s -> 280.4s | +| bars 2160p | +9.4% / -12.7% | +10.2% / -11.6% | +0.8 / +1.1 | 168.8s -> 180.7s | +| film A | +21.7% / -4.4% | +22.1% / -4.0% | +0.4 / +0.4 | 153.9s -> 203.9s | +| film B | +26.9% / -0.6% | +28.1% / +0.7% | +1.2 / +1.3 | 133.5s -> 164.0s | +| screen capture | +27.8% / -26.0% | **+20.8% / -30.1%** | **-7.0 / -4.1** | 83.7s -> 120.6s | + +KEEP RULE VERDICT on the unconditional arm: FAIL. The rule wants both film +rows down; both go UP (film A +0.4/+0.4, film B +1.2/+1.3). The capture wins +seven points against libaom and four against rav1e -- the largest single +screen move this lane has on record -- so the search ships behind the SAME +content gate palette, intrabc and the angle-delta refinement already stand +behind (`search.screen`): a non-screen frame is byte-identical to the encoder +before the lane. + +Class note for the film loss: an ADST/IDTX unit is a locally cheaper +reconstruction that the next picture then predicts from -- the same +`local-rd-on-references` shape lane-fitu measured for filter intra, which is +why the film rows lose while the intra-heavy capture wins. + +### Shipped state (screen gate on), confirm run + +| clip | control | shipped | note | +|---|---|---|---| +| bars 1080p | -1.0% / -16.8% | -1.0% / -16.8% | byte-identical (194497/299067/419042/567789 B) | +| bars 2160p | +9.4% / -12.7% | +9.4% / -12.7% | byte-identical (205409/321883/435765/564573 B) | +| film A | +21.7% / -4.4% | +21.7% / -4.4% | byte-identical (64392/102508/170169/413430 B) | +| film B | +26.9% / -0.6% | +26.9% / -0.6% | byte-identical (27442/50374/105485/296813 B) | +| screen capture | +27.8% / -26.0% | **+20.8% / -30.1%** | 36775/45758/57095/71711 B, wall 83.7s -> 96.2s (+15%) | + +Every non-screen row lands on the control's own byte counts to the digit -- +the gate is the frame classifier, and the four non-capture clips classify 0 +screen frames of 4 -- so nothing outside screen content moves, pins included. + +Pins: `encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins` +PASSES UNCHANGED at 8562 / 33357 -- the pin clip is not screen, so nothing to +re-pin. + +## 6. Preset lever and invariants + +`speed::TX_TYPE_SEARCH = [true x7, false x4]` (presets 0-6 on) on top of the +screen content gate. The FIVE-type fire count is preset 0's: at preset 6 the +mode/partition pruning removes the blocks `ADST_ADST` and `IDTX` were winning +on (hits `[0, 6192, 0, 79, 284, ..]`), so the witness asserts the full set at +preset 0 and "some non-`DCT_DCT` type fires" at every preset that carries the +lever. + +| invariant | preset 0 | preset 6 | +|---|---|---| +| `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 four above with `EC_COMP_MISMATCH=1` | 0 mismatches | 0 mismatches | + +`every_speed_preset_decodes_sample_exact_through_both_decoders --ignored` +PASS (with `EC_COMP_MISMATCH=1`). +`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. + +## 7. The long-GOP gate at what ships, and the suite + +`encode::tests::bd_rate_film_long_gop` (48 pictures, gop 48) on the shipped +state -- both rows are non-screen and therefore 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% | 713.0s:38.4s:60.4s | +| film B | +89.8% / +9.1% | 459.0s:71.9s:59.0s | + +Full `ec-av1` suite, detached: **567 passed / 1 failed / 45 ignored** +(943s). The one failure is `stream::tests::no_per_frame_state_is_thread_local_any_more` +-- `["encode.rs: SB128"]`, main's own red from the sb128 merge that a fix lane +owns, not this lane's. `timeout 900 cargo check --workspace --all-targets -j4`: +0 errors, 0 `ec-av1` warnings. + +## 8. Deferred + +* `deferred: inter luma IDTX vs DCT_DCT (the two-type TX_SET_INTER_3 the + writer already codes) -- the plumbing is done (an inter block's + BlockCoeffs carries luma_tx_types through the same writer path), what is + missing is the candidate loop in code_from_prediction/commit_inter_luma and + a gate round -- unblocked by ~40 min of gate wall; the screen row is where + it would pay, same as the intra half.` +* `deferred: reduced_tx_set = 0 and the 13/17 alphabets (DTT9_IDTX_1DDCT, + ALL16) -- the FORWARD kernels are DONE and round-trip tested (all sixteen + types), decode::tx_type_symbol already answers for the 7/12/16-symbol sets, + and the decoder reads them; what is missing is the frame-header bit plus + the writer's set map (tile.rs:4208 -> the Luma*Set1/Set2 variants) and a + rav1e-speed-6-shaped candidate list per class -- unblocked by a lane of its + own. Note the shape this lane measured first: the wider a set gets, the + more the FILM rows lose (this five-type set already costs film A +0.4 and + film B +1.2), so that lane should gate by content from the start rather + than measure an unconditional arm.` +* `deferred: libaom's own tx_type histogram on film B (syntax_census) -- the + charter's instrument half. Not run: the two gate slots were the budget, and + the decision it would have informed (which types to offer) was settled by + the gate itself. Unblocked by one census run.`