diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a1532214..fe67d29f 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -8288,7 +8288,7 @@ impl Neighbours { /// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's /// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode /// instead (the defect commit 1a89ed9 fixed at the square sites). -fn fi_tx_row(mode: usize, filter_intra: Option) -> usize { +pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option) -> usize { const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED]; filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi]) } @@ -8296,7 +8296,7 @@ fn fi_tx_row(mode: usize, filter_intra: Option) -> usize { /// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`, /// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32 /// bound (spec `filter_intra_mode_info` never reads a symbol there). -fn filter_intra_size_class(side: usize) -> Option { +pub(crate) fn filter_intra_size_class(side: usize) -> Option { match side { 4 => Some(0), 8 => Some(1), @@ -33480,7 +33480,9 @@ pub(crate) fn decode_inter_frame_tile( loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, reference_select, tx_select, &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, - switchable_motion_mode, false, fctx, + // `enable_filter_intra`: as the `false`s beside it, this convenience + // entry names a stream written without the sequence bit (lane-fintra). + switchable_motion_mode, false, false, fctx, ) } @@ -33532,6 +33534,8 @@ pub(crate) fn decode_inter_frame_tile_lr( // `false` here desynced every stream this crate's encoder writes with the // warp knob on: the same stale-header class as the parameter above. allow_warped_motion: bool, + // lane-fintra: see [`decode_inter_frame_tiles_lr`]'s own parameter. + enable_filter_intra: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { @@ -33562,6 +33566,7 @@ pub(crate) fn decode_inter_frame_tile_lr( allow_screen_content_tools, switchable_motion_mode, allow_warped_motion, + enable_filter_intra, fctx, ) } @@ -33603,6 +33608,12 @@ pub(crate) fn decode_inter_frame_tiles_lr( // `false` here desynced every stream this crate's encoder writes with the // warp knob on: the same stale-header class as the parameter above. allow_warped_motion: bool, + // lane-fintra: this sequence header's own `enable_filter_intra` bit (spec + // 5.5.2). Hard-coded `false` here until this lane -- the same stale-header + // class as `switchable_motion_mode`/`allow_warped_motion` above: the + // encoder's own trial decode desyncs at the first intra-in-inter DC_PRED + // block the moment its sequence header sets the bit. + enable_filter_intra: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_with_cdfs( @@ -33641,10 +33652,7 @@ pub(crate) fn decode_inter_frame_tiles_lr( allow_warped_motion, allow_screen_content_tools, DeltaParams::default(), - // `enable_filter_intra`: this crate's own encoder never writes the - // sequence bit (`encode.rs`), so no intra-in-inter block of a stream - // reaching this entry point reads a `use_filter_intra` symbol. - false, + enable_filter_intra, None, fctx, ) @@ -37632,7 +37640,10 @@ mod tests { base_q_idx, w as u32, h as u32, - false, + // lane-fintra: the sequence bit the encoder wrote this tile under + // (stale-header class -- a hard-coded `false` here reads one symbol + // short at the first DC_PRED block once the search offers filter intra). + crate::encode::filter_intra_on(), &cdef, &loop_filter, tx_select, @@ -38002,7 +38013,10 @@ mod tests { encoded.base_q_idx, coded_w, coded_h, - false, + // lane-fintra: the sequence bit the encoder wrote this tile under + // (stale-header class -- a hard-coded `false` here reads one symbol + // short at the first DC_PRED block once the search offers filter intra). + crate::encode::filter_intra_on(), &encoded.cdef, &encoded.loop_filter, encoded.tx_select, @@ -38018,6 +38032,68 @@ mod tests { } } + /// lane-fintra: the encoder's own filter-intra blocks, read back by BOTH + /// decoders. Two claims in one gate: the stream really exercises the tool + /// (the decoder's own `use_filter_intra == 1` counter moves, class + /// `gate-blind-to-feature` -- a feature that never fires is not measured), + /// and every sample of the frame that carries them matches ffmpeg's + /// (class `fixture-proves-symbol-not-signal`: the symbol alone would not + /// prove the recursive predictor, the tx_type row or the syntax position + /// between the palette colours and the colour-index maps). + #[test] + fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { + let fctx = &crate::decode::FrameCtx::new(); + if !crate::encode::filter_intra_on() { + eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0"); + return; + } + if !have_ffmpeg() { + eprintln!("SKIP a_filter_intra_key_frame...: no ffmpeg"); + return; + } + let (width, height) = (128usize, 128usize); + // Smooth, slowly curving content: what the recursive filter modes are + // for, and what a plain directional prediction leaves residual on. + let mut picture = crate::encode::Picture::grey(width, height); + for row in 0..height { + for col in 0..width { + let v = 128.0 + + 60.0 * ((row as f64) / 9.0).sin() * ((col as f64) / 11.0).cos() + + 8.0 * ((row + col) as f64 / 3.0).sin(); + picture.y[row * width + col] = v.clamp(0.0, 255.0) as u16; + } + } + let encoded = crate::encode::encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + let (coded_w, coded_h) = ffprobe_size(&encoded.stream); + let before = filter_intra_hits(); + let ours = decode_key_frame_tile_lr( + &encoded.tile, + encoded.mi_cols, + encoded.mi_rows, + encoded.base_q_idx, + coded_w, + coded_h, + crate::encode::filter_intra_on(), + &encoded.cdef, + &encoded.loop_filter, + encoded.tx_select, + true, + encoded.screen, + encoded.allow_intrabc, + &encoded.loop_restoration, + fctx, + ) + .unwrap(); + let fired = filter_intra_hits() - before; + assert!(fired > 0, "no block took filter intra -- the gate is blind to the feature"); + eprintln!("a_filter_intra_key_frame: {fired} filter-intra blocks"); + let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize); + assert_eq!(ours.y, ffmpeg_decoded.y, "luma vs ffmpeg"); + assert_eq!(ours.u, ffmpeg_decoded.u, "U vs ffmpeg"); + assert_eq!(ours.v, ffmpeg_decoded.v, "V vs ffmpeg"); + assert_eq!(ours.y, encoded.reconstruction.y, "luma vs the encoder's own reconstruction"); + } + /// The key frame the encoder writes carries `tx_mode == TxMode::Select`, /// and that header bit is load-bearing for a decode of its tile: read as a /// `TxMode::Largest` frame the very first block misses its `tx_depth` @@ -38046,7 +38122,10 @@ mod tests { encoded.base_q_idx, width as u32, height as u32, - false, + // lane-fintra: the sequence bit the encoder wrote this tile under + // (stale-header class -- a hard-coded `false` here reads one symbol + // short at the first DC_PRED block once the search offers filter intra). + crate::encode::filter_intra_on(), &encoded.cdef, &encoded.loop_filter, tx_select, @@ -38131,7 +38210,10 @@ mod tests { key.base_q_idx, width as u32, height as u32, - false, + // lane-fintra: the sequence bit the encoder wrote this tile under + // (stale-header class -- a hard-coded `false` here reads one symbol + // short at the first DC_PRED block once the search offers filter intra). + crate::encode::filter_intra_on(), &key.cdef, &key.loop_filter, key.tx_select, @@ -38197,6 +38279,9 @@ mod tests { // the warp bit must be the one it wrote too (lane-av1obmc2); // the encoder only sets it under `EC_AV1_WARP`. crate::encode::warp_on(), + // lane-fintra: the sequence bit the encoder wrote this tile + // under -- same stale-header class as the warp bit above. + crate::encode::filter_intra_on(), fctx, ) .unwrap(); @@ -38480,7 +38565,10 @@ mod tests { key.base_q_idx, coded_w, coded_h, - false, + // lane-fintra: the sequence bit the encoder wrote this tile under + // (stale-header class -- a hard-coded `false` here reads one symbol + // short at the first DC_PRED block once the search offers filter intra). + crate::encode::filter_intra_on(), &key.cdef, &key.loop_filter, key.tx_select, @@ -38535,6 +38623,9 @@ mod tests { // the warp bit must be the one it wrote too (lane-av1obmc2); // the encoder only sets it under `EC_AV1_WARP`. crate::encode::warp_on(), + // lane-fintra: the sequence bit the encoder wrote this tile + // under -- same stale-header class as the warp bit above. + crate::encode::filter_intra_on(), fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0b957a5e..e9a2fe62 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -756,6 +756,46 @@ fn intra_predict_u8( } } +/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same +/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one +/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode. +fn filter_intra_predict_u8( + mode: usize, + above: Option<&[u8]>, + left: Option<&[u8]>, + corner: Option, + side: usize, + dst: &mut [u8], fctx: &crate::decode::FrameCtx, +) { + let mut above_buf = [0u16; 2 * BLOCK]; + let mut left_buf = [0u16; 2 * BLOCK]; + let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| { + for (d, &v) in buf[..src.len()].iter_mut().zip(src) { + *d = u16::from(v); + } + }; + if let Some(a) = above { + widen(a, &mut above_buf); + } + if let Some(l) = left { + widen(l, &mut left_buf); + } + let mut dst16 = [0u16; BLOCK * BLOCK]; + let n = side * side; + crate::intra::predict_filter_intra( + mode, + above.map(|a| &above_buf[..a.len()]), + left.map(|l| &left_buf[..l.len()]), + corner.map(u16::from), + side, + side, + &mut dst16[..n], fctx, + ); + for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) { + *d = v as u8; + } +} + /// Pads one plane to `(padded_width, padded_height)` by repeating its last /// row and column, so the block coder always sees a whole number of blocks. /// [`crop_plane`] undoes this on the way back out. @@ -982,6 +1022,20 @@ pub(crate) fn force_screen(value: Option) { SCREEN_FORCE.with(|c| c.set(value)); } +// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE +// ablation can measure the mode search alone. Setting it also clears the +// sequence header's own `enable_filter_intra` bit, so the stream the arm +// writes is exactly the one this encoder wrote before the lane. +#[cfg(test)] +thread_local! { + static FILTER_INTRA_FORCE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(crate) fn force_filter_intra(value: Option) { + FILTER_INTRA_FORCE.with(|c| c.set(value)); +} + pub(crate) fn arm_seq_screen(on: bool) { SEQ_SCREEN.with(|c| c.set(on)); } @@ -1183,7 +1237,11 @@ pub(crate) fn key_frame_headers_colour( max_frame_width: w, max_frame_height: h, use_128x128_superblock: false, - enable_filter_intra: false, + // lane-fintra: the encoder's intra search offers the five recursive + // filter-intra modes on eligible blocks, so the sequence bit is set + // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both + // off and restores the streams this encoder wrote before the lane). + enable_filter_intra: filter_intra_on(), enable_intra_edge_filter: false, enable_order_hint: true, order_hint_bits: 7, @@ -3860,6 +3918,81 @@ fn code_square( } } + // The five recursive filter-intra modes (spec 5.11.14), priced against + // whatever the mode, transform-depth and palette searches settled on -- + // the same "one candidate loop after the incumbent is known" shape the + // palette above uses. A block that takes one is `DC_PRED` with no palette + // by construction (`av1_filter_intra_allowed`), and its luma transform + // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`). + // + // corner-cut, ceiling named: the candidate is only ever priced at + // `tx_depth` 0 (one transform over the whole block), so a block whose + // ordinary intra winner wanted a SPLIT transform is compared against a + // handicapped filter-intra arm -- and only 19-44% of this encoder's intra + // blocks code depth 0. Upgrade path: predict per transform unit inside + // [`Plane::code_tx_depth`] (the decoder already reads `filter_intra` per + // unit, decode.rs:11835) and run the depth search under the winning + // filter mode. + let mut filter_intra: Option = None; + if filter_intra_on() + && palette.is_none() + && let Some(class) = crate::decode::filter_intra_size_class(side) + { + let row = &cdf::FILTER_INTRA[class]; + // With the sequence bit on, EVERY `DC_PRED` block without a luma + // palette carries the flag, so the incumbent pays its zero before the + // comparison -- otherwise the candidate is charged a bit the block + // spends either way (class `price-the-narrowing-not-the-table`). + if mode == DC_PRED { + cost += search.lambda * symbol_bits(row, 0); + } + let one_bits = symbol_bits(row, 1); + let kept = luma.snapshot(x, y, side); + let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); + let (above, left, corner) = + luma.edges_into(x, y, side, at.reach, &mut above_buf, &mut left_buf); + let mut prediction = vec![0u8; side * side]; + for fi in 0..5u8 { + filter_intra_predict_u8( + usize::from(fi), + above, + left, + corner, + side, + &mut prediction, fctx, + ); + let trial = luma.code_from_prediction( + x, + y, + side, + &prediction, + false, + search.base_q_idx, + search.deadzone, + luma_set, + ); + let cost_f = trial.sse + + search.lambda + * (trial.bits + + mode_bits[DC_PRED as usize] + + one_bits + + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi)) + + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); + if cost_f < cost { + cost = cost_f; + mode = DC_PRED; + angle_delta = 0; + tx_depth = 0; + luma_coeffs = coeffs(&trial.levels, side); + luma.commit(x, y, side, &trial); + filter_intra = Some(fi); + } + } + if filter_intra.is_none() { + luma.restore(x, y, side, &kept); + } + } + // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both // planes; what it costs still counts towards the partition decision. let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) = @@ -3898,6 +4031,7 @@ fn code_square( tx_depth, palette, palette_uv, + filter_intra, cfl_alphas, angle_delta_y: angle_delta as i8, ..BlockCoeffs::default() @@ -3975,6 +4109,20 @@ fn cfl_on() -> bool { *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0")) } +/// Whether the intra search offers the five recursive filter-intra modes at +/// all, and with them whether the sequence header sets `enable_filter_intra` +/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured +/// its own on/off pair -- and how every byte pin written before it still +/// reproduces). +pub(crate) fn filter_intra_on() -> bool { + #[cfg(test)] + if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) { + return forced; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("EC_AV1_FILTER_INTRA").as_deref() != Ok("0")) +} + /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts /// to its own encode. #[cfg(test)] @@ -5086,6 +5234,7 @@ fn code_square_inter( BlockCoeffs { angle_delta_y: 0, cfl_alphas: None, + filter_intra: None, luma: coeffs(&levels, side), u: coeffs(&u_new.levels, side / 2), v: coeffs(&v_new.levels, side / 2), @@ -5121,6 +5270,7 @@ fn code_square_inter( (BlockCoeffs { angle_delta_y: 0, cfl_alphas: None, + filter_intra: None, luma: coeffs(&levels, side), u: coeffs(&u.levels, side / 2), v: coeffs(&v.levels, side / 2), @@ -6223,6 +6373,7 @@ pub(crate) fn encode_key_frame_inner( crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); + crate::tile::arm_filter_intra(filter_intra_on()); crate::tile::arm_intrabc(allow_intrabc); crate::tile::arm_pricing_cdfs(None, false); let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( @@ -7829,6 +7980,7 @@ fn search_inter_block( BlockCoeffs { angle_delta_y: 0, cfl_alphas: None, + filter_intra: None, luma: coeffs(&levels, BLOCK), u: coeffs(&best.u.levels, BLOCK / 2), v: coeffs(&best.v.levels, BLOCK / 2), @@ -9079,6 +9231,7 @@ pub(crate) fn encode_inter_frame( crate::tile::arm_warped_motion(warped_motion); crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); crate::tile::arm_screen(screen); + crate::tile::arm_filter_intra(filter_intra_on()); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_pricing_cdfs(Some(&cdfs), screen); // Each tile's own MV grid: a candidate scan never reaches past @@ -9205,6 +9358,7 @@ pub(crate) fn encode_inter_frame( h.allow_screen_content_tools, switchable_motion_mode, h.allow_warped_motion, + seq.enable_filter_intra, fctx, ) }, @@ -10083,6 +10237,7 @@ mod tests { let residual_block = BlockCoeffs { angle_delta_y: 0, cfl_alphas: None, + filter_intra: None, luma: vec![Coeff { row: 0, col: 0, @@ -10882,6 +11037,11 @@ mod tests { eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); return; } + // A mode ablation measures the MODE search: a filter-intra block is + // coded `DC_PRED` whatever mode the arm forces, so it would fail the + // "the encoder coded something else" check for a reason that is not + // about the mode search at all. + force_filter_intra(Some(false)); // 128 wide is a whole number of superblocks and 160 is not: the last // superblock of a 160-wide row is half a one, whose blocks have no // above-right samples inside the frame at all. @@ -10992,6 +11152,10 @@ mod tests { // these synthetic two-colour pictures losslessly under every arm and // leave nothing to compare (see [`force_screen`]). force_screen(Some(false)); + // Same reason, for the filter-intra candidate: it wins blocks under + // BOTH arms of a mode ablation and so cancels the difference the + // ablation measures (class `gate-recipe-confound`). + force_filter_intra(Some(false)); let mut points: Vec<(f64, f64)> = [110u8, 90, 70] .iter() .map(|&q| { @@ -12840,8 +13004,14 @@ mod tests { // so every block taking either codes different syntax and different // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60. // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half. + // Re-taken on lane-fintra: the sequence header sets + // `enable_filter_intra`, so every DC_PRED intra block of at most + // 32x32 without a luma palette carries a `use_filter_intra` flag and + // the blocks that take one code a filter-intra mode, a different + // prediction and different coefficients -- 7321 -> 7373 at q=150 and + // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these. let pins: [(u8, usize, u64); 2] = - [(150, 7321, 0x34e2_e4e0_d7c5_09f3), (60, 27285, 0xbfd2_41af_dcac_a0c6)]; + [(150, 7373, 0xd0af_b890_28bc_cfbf), (60, 27074, 0x8324_0e9f_5971_e4e7)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( @@ -13963,6 +14133,7 @@ mod tests { let _ = crate::tile::take_palette_uv_hits(); let _ = crate::tile::take_intrabc_hits(); let _ = take_intrabc_search(); + let _ = crate::tile::take_filter_intra_hits(); // The sequence path itself codes the pyramid now // (lane-av1pyrdef), and prints what it requested and what the // content gate left effective. @@ -14009,6 +14180,20 @@ mod tests { search[1], search[2], ); + // gate-blind-to-feature: how often the five recursive filter-intra + // modes actually won a block over this clip's four encodes -- a + // tool that never fires is not measured by the row above it. + let fi = crate::tile::take_filter_intra_hits(); + eprintln!( + "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})", + filter_intra_on(), + fi[0], + fi[1], + fi[2], + fi[3], + fi[4], + fi[5], + ); let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points); let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points); assert_monotone(&format!("{name}: ours"), &ours); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 4f505cf9..e225c38f 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2993,7 +2993,10 @@ pub(crate) mod tests { encoded.base_q_idx, width as u32, height as u32, - false, + // lane-fintra: the sequence bit the encoder wrote this tile under + // (stale-header class -- a hard-coded `false` here reads one symbol + // short at the first DC_PRED block once the search offers filter intra). + crate::encode::filter_intra_on(), &encoded.cdef, &encoded.loop_filter, encoded.tx_select, diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 87a616c4..f9ef0eab 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -343,6 +343,81 @@ fn intrabc_armed() -> bool { INTRABC.with(std::cell::Cell::get) } +thread_local! { + /// This SEQUENCE header's `enable_filter_intra` (spec 5.5.2), armed + /// exactly like [`SCREEN`]: with it every DC_PRED intra block of at most + /// 32x32 that took no luma palette carries a `use_filter_intra` symbol + /// after the palette colours and before the colour-index maps (decode.rs + /// `read_intra_mode`), so a tile written without it and read with it + /// desyncs at the first such block. + static FILTER_INTRA: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Arms the sequence's `enable_filter_intra` bit for the next tile written on +/// this thread; cleared by [`CdefIdxGuard`] when that writer returns. +pub(crate) fn arm_filter_intra(on: bool) { + FILTER_INTRA.with(|c| c.set(on)); +} + +fn filter_intra_armed() -> bool { + FILTER_INTRA.with(std::cell::Cell::get) +} + +/// How many blocks this writer coded `use_filter_intra == 1`, and the +/// histogram of the five `filter_intra_mode`s (index 1..=5) -- the fire count +/// a gate prints so that "filter intra is on" is a measurement rather than a +/// claim (class `gate-blind-to-feature`). Index 0 is the block count. +static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 6]; + +/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the +/// counts to its own encode. +#[cfg(test)] +pub(crate) fn take_filter_intra_hits() -> [usize; 6] { + std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for +/// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every +/// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <= +/// 32, [`crate::decode::filter_intra_size_class`]) and that took no luma +/// palette (`av1_filter_intra_allowed`, reconintra.h:77), then the chosen mode +/// of five. Sits between the palette COLOUR lists and the colour-index maps, +/// where libaom reads it (`av1_visit_palette` runs after +/// `read_filter_intra_mode_info`). +fn write_filter_intra( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + mode: usize, + side: usize, + has_palette_y: bool, + filter_intra: Option, +) { + if !filter_intra_armed() || mode != DC_PRED || has_palette_y { + debug_assert!(filter_intra.is_none(), "no `use_filter_intra` symbol exists here"); + return; + } + let Some(class) = crate::decode::filter_intra_size_class(side) else { + debug_assert!(filter_intra.is_none(), "past av1_filter_intra_allowed_bsize"); + return; + }; + enc.symbol(usize::from(filter_intra.is_some()), &mut cdfs.filter_intra[class]); + if let Some(fi) = filter_intra { + enc.symbol(usize::from(fi), &mut cdfs.filter_intra_mode); + FILTER_INTRA_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + FILTER_INTRA_HITS[usize::from(fi) + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// The coefficient-table row a block's luma transform types are coded from: +/// `fimode_to_intradir[filter_intra_mode]` for a filter-intra block, its own +/// luma mode otherwise (class `filter-intra tx_type row`, decode.rs +/// [`crate::decode::fi_tx_row`]). The block still PUBLISHES `DC_PRED` as its +/// neighbour mode -- libaom's `mbmi->mode` is unchanged by filter intra. +fn tx_row(mode: usize, filter_intra: Option) -> usize { + crate::decode::fi_tx_row(mode, filter_intra.map(usize::from)) +} + /// How many blocks this writer coded `use_intrabc == 1`, and the histogram of /// their DV magnitudes in full pels (index 1..=6 = 1, 2, 4, 8, 16, 32 pels /// and up, by the larger component) -- the fire count a gate prints so that @@ -935,6 +1010,7 @@ impl Drop for CdefIdxGuard { REFERENCE_SELECT.with(|c| c.set(false)); MOTION_MODE.with(|c| c.set(false)); INTRABC.with(|c| c.set(false)); + FILTER_INTRA.with(|c| c.set(false)); INTRABC_GRID.with(|c| *c.borrow_mut() = None); ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); } @@ -1452,6 +1528,14 @@ pub struct BlockCoeffs { /// [`UV_CFL_PRED`]; at least one of the pair is nonzero, since the joint /// sign symbol has no (ZERO, ZERO) value. pub cfl_alphas: Option<(i32, i32)>, + /// This block's `filter_intra_mode` (spec 5.11.14, 0..=4) when it is + /// coded with recursive filter intra, or `None`. `Some` only on a DC_PRED + /// luma block of at most 32x32 with no luma palette, on a sequence whose + /// header set `enable_filter_intra` ([`arm_filter_intra`]); the block's + /// luma transform types are then coded from + /// `fimode_to_intradir[filter_intra_mode]`'s row ([`tx_row`]) while its + /// neighbour mode stays `DC_PRED`. + pub filter_intra: Option, /// This block's `angle_delta_y` (spec `read_intra_angle_info`, -3..=3), /// zero for every non-directional luma mode -- which is what /// [`Default`] gives, and what every writer coded before lane-av1cfl. @@ -3446,6 +3530,7 @@ fn write_intra_mode( neighbours, block.palette.as_ref(), block.palette_uv.as_ref(), + block.filter_intra, mode, uv_mode, mi, @@ -3474,12 +3559,18 @@ fn write_palette_syntax( neighbours: &mut Neighbours, palette: Option<&PaletteY>, palette_uv: Option<&PaletteUv>, + // lane-fintra: this block's chosen `filter_intra_mode`, or `None`. Written + // here rather than by the caller because its symbol sits BETWEEN the + // palette colour lists and the colour-index maps (decode.rs + // `read_intra_mode`), which is inside this function. + filter_intra: Option, mode: usize, uv_mode: usize, mi: (usize, usize), side: usize, ) { if !screen_armed() { + write_filter_intra(enc, cdfs, mode, side, false, filter_intra); return; } let palette = palette.filter(|_| mode == DC_PRED); @@ -3509,6 +3600,7 @@ fn write_palette_syntax( enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]); write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache); } + write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra); // Both colour-index maps come after BOTH colour lists, in plane order // (`av1_visit_palette` runs from the caller, past `filter_intra`). if let Some(pal) = palette { @@ -3527,6 +3619,10 @@ fn write_palette_syntax( ); note_palette_uv(n); } + } else { + // Below `av1_allow_palette`'s size bound there is no palette syntax at + // all, but `av1_filter_intra_allowed_bsize` still admits the block. + write_filter_intra(enc, cdfs, mode, side, false, filter_intra); } neighbours.pending_palette = palette.map(|p| (p.size, p.colors)); neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors)); @@ -3629,6 +3725,10 @@ fn write_block( at_mi, side, ); + // The coefficient tables read `fimode_to_intradir[filter_intra_mode]`'s + // row on a filter-intra block; the neighbour publication below still gets + // the block's own `DC_PRED` ([`tx_row`]). + let tx_mode = tx_row(mode, block.filter_intra); let split = if tx_select { let tx = write_luma_select( enc, @@ -3638,7 +3738,7 @@ fn write_block( side, usize::from(block.tx_depth), &grids[0], - mode, + tx_mode, all_scans, )?; tx < side @@ -3652,7 +3752,7 @@ fn write_block( grids, &scans, &neighbours.around(at, side), - mode, + tx_mode, tx_select, ); neighbours.record_planes(at, side, mode, grids, !split); @@ -3724,6 +3824,9 @@ fn write_leaf8( // unchanged). let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8); let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; + // As [`write_block`]: the coefficient row follows the filter-intra mode, + // the mode this leaf publishes (and returns to the next leaf) does not. + let tx_mode = tx_row(mode, block.filter_intra); let split = if tx_select { let tx = write_luma_select( enc, @@ -3733,7 +3836,7 @@ fn write_leaf8( 8, usize::from(block.tx_depth), &grids[0], - mode, + tx_mode, all_scans, )?; tx < 8 @@ -3747,7 +3850,7 @@ fn write_leaf8( grids, &scans, &neighbours.around_mi(leaf_mi, 8), - mode, + tx_mode, tx_select, ); neighbours.record_mi_planes(leaf_mi, 8, grids, !split); @@ -5811,7 +5914,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } - mode_for_tx = mode; + mode_for_tx = tx_row(mode, block.filter_intra); // Intra: no vote, but still a coded cell -- mvstack's // extended-scan coverage must see it (module doc). let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); @@ -5821,6 +5924,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( &mut neighbours, block.palette.as_ref(), block.palette_uv.as_ref(), + block.filter_intra, mode, uv_mode, (mi_row, mi_col), @@ -6052,7 +6156,7 @@ fn write_inter_frame_leaf( if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } - mode_for_tx = mode; + mode_for_tx = tx_row(mode, block.filter_intra); // Intra: no vote, but still a coded cell -- mvstack's extended-scan // coverage must see it (module doc). let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); @@ -6062,6 +6166,7 @@ fn write_inter_frame_leaf( neighbours, block.palette.as_ref(), block.palette_uv.as_ref(), + block.filter_intra, mode, uv_mode, (mi_row, mi_col), @@ -6299,7 +6404,7 @@ fn write_inter_frame_leaf8( if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } - mode_for_tx = mode; + mode_for_tx = tx_row(mode, block.filter_intra); // Intra: no vote, but still a coded cell -- mvstack's extended-scan // coverage must see it (module doc). let (mi_row, mi_col) = leaf_mi; @@ -6309,6 +6414,7 @@ fn write_inter_frame_leaf8( neighbours, block.palette.as_ref(), block.palette_uv.as_ref(), + block.filter_intra, mode, uv_mode, leaf_mi,