diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index df4f0df1..057257d2 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -58,6 +58,11 @@ fn main() { "skipped_intrabc_chroma_arm_hits: {}", ec_av1::stream::skipped_intrabc_chroma_arm_hits() ); + println!( + "intrabc_rect: {} (var-tx tree: {})", + ec_av1::decode::intrabc_rect_hits(), + ec_av1::decode::intrabc_rect_vartx_hits() + ); let (rtu, rsplit, robmc) = ec_av1::stream::rect_inter_tu_counters(); println!("rect_inter: tu={rtu} txsplit={rsplit} obmc_leaf={robmc}"); println!( diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a29fd228..946657be 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -130,6 +130,11 @@ pub(crate) struct FrameCtx { /// decoder's inter-side publishing was wired. See /// [`Neighbours::fill_lf_grid_rect`]'s band publish. pub(crate) intra_only: std::cell::Cell, + /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame + /// (intra included). [`Self::tx_select_inter`] cannot stand in for it: + /// an intrabc block rides an INTRA frame, but libaom still reads its + /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`. + pub(crate) tx_select_frame: std::cell::Cell, pub(crate) reduced_tx_set_inter: std::cell::Cell, pub(crate) enable_filter_intra_inter: std::cell::Cell, pub(crate) palette_pred: std::cell::RefCell>>, @@ -229,6 +234,7 @@ impl FrameCtx { cur_segment_id: std::cell::Cell::new(0), seg_tile_origin: std::cell::Cell::new((0, 0)), tx_select_inter: std::cell::Cell::new(false), + tx_select_frame: std::cell::Cell::new(false), intra_only: std::cell::Cell::new(false), reduced_tx_set_inter: std::cell::Cell::new(false), enable_filter_intra_inter: std::cell::Cell::new(false), @@ -1626,6 +1632,7 @@ pub(crate) fn set_inter_tx_mode( ) { fctx.tx_select_inter.with(|c| c.set(tx_select)); fctx.intra_only.with(|c| c.set(false)); + fctx.tx_select_frame.with(|c| c.set(tx_select)); fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra)); } @@ -3743,6 +3750,64 @@ thread_local! { /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no /// symbol here desynced `warped.obu` at the very next block. static RECT_INTRABC_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction + /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip + /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never + /// this one). + static INTRABC_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT). + static INTRABC_RECT_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction + /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read), + /// split by the strip's orientation -- `bw > bh` is a HORZ strip, + /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED + /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS` + /// counts neither orientation nor the skip flag, so an arm that flipped + /// to an all-skip stream (no residual reader at all) would stay green. + static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> = + const { std::cell::Cell::new([0, 0]) }; + /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`] + /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split + /// by orientation. The r5 panic (residual stride `bw * bh` underrunning + /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was + /// invisible to every gate because they only counted CODED strips. + static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> = + const { std::cell::Cell::new([0, 0]) }; +} + +/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed, +/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`]. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub fn intrabc_rect_coded_hits() -> [usize; 2] { + INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get) +} + +/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks +/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`]. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub fn intrabc_rect_skipped_hits() -> [usize; 2] { + INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get) +} + +/// Current value of [`INTRABC_RECT_HITS`]. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub fn intrabc_rect_hits() -> usize { + INTRABC_RECT_HITS.with(|c| c.get()) +} + +/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`]. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn reset_intrabc_rect_hits() { + INTRABC_RECT_HITS.with(|c| c.set(0)); + INTRABC_RECT_VARTX_HITS.with(|c| c.set(0)); + INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0])); + INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0])); +} + +/// Current value of [`INTRABC_RECT_VARTX_HITS`]. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub fn intrabc_rect_vartx_hits() -> usize { + INTRABC_RECT_VARTX_HITS.with(|c| c.get()) } /// Current value of [`INTRABC_VARTX_HITS`]. @@ -7729,6 +7794,19 @@ impl Neighbours { } } } + // lane-av1-intrabc r4: publish this coded block's own mi footprint + // into the intrabc MV grid's block-COVERAGE map -- every coded block, + // not just the intrabc ones. A later intrabc block's DV predictor is + // built by libaom's own row/col scans over `xd->mi[]`, which holds an + // `MB_MODE_INFO` for EVERY block and steps by + // `mi_size_wide/height[candidate->bsize]`; without this footprint a + // non-intrabc neighbour reads as uncovered and the scan advances it + // by one cell instead of by its real width. + fctx.intrabc_mi_grid.with(|g| { + if let Some((grid, _, _)) = g.borrow_mut().as_mut() { + grid.cover_rect(mi_r, mi_c, w_mi, h_mi); + } + }); } /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span. @@ -9258,7 +9336,13 @@ fn read_intra_mode_rect( Option, Option, Option, - // lane-av1-rect14: Some(dv) for an intrabc 16x4/4x16 pair strip. + // lane-av1-intrabc: the block vector, `Some` exactly when this block's + // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns + // straight out of `read_intra_frame_mode_info` then, so every later field + // of the tuple is at its default (mode/uv_mode DC, no angle, no palette, + // no filter intra). A caller that can reconstruct intrabc at its shape + // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by + // name with the same string it always did. Option<(i32, i32)>, )> { // lane-av1mono: libaom guards every chroma symbol read with @@ -9338,18 +9422,22 @@ fn read_intra_mode_rect( istep!("intrabc", use_intrabc as i32); if use_intrabc { hit!(INTRABC_HITS); - // 16x4/4x16 is a chroma PAIR ([`decode_rect4_16_intrabc`]). - // Every other rect shape still refuses by name: its - // reconstruction is `decode_intrabc_rect` (lane-av1-intrabc, - // not on this tree). 32x8/8x32, 64x16/16x64 and 128-axis strips - // own their chroma and must not take the pair helper. - // Every rect shape returns the DV. 16x4/4x16 reconstructs in - // [`decode_rect4_16_intrabc`]; other shapes in - // [`decode_intrabc_owned_rect`]. A shape with no coefficient - // table still refuses there, by the same name. + // libaom `read_intrabc_info`: the DV read, then an immediate + // return out of the mode-info read -- no `y_mode`, no `uv_mode`, + // no angle deltas, no palette, no filter intra. The caller owns + // the reconstruction at its own shape. let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx); return Ok(( - skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None, Some(dv), + skip, + DC_PRED, + 0, + DC_PRED, + 0, + None, + None, + None, + None, + Some(dv), )); } } @@ -10927,6 +11015,348 @@ fn decode_intra_rect_in_inter( Ok(()) } +/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real +/// mi `(mi_r, mi_c)` (lane-av1-intrabc). +/// +/// libaom treats an intrabc block as INTER for everything except the mode-info +/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA` +/// (`blockd.h:373`), so +/// +/// * `parse_decode_block` reads the transform size through the INTER var-tx +/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose +/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and +/// whose leaves publish their own resolved size back; +/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT +/// frame's own pre-loop-filter reconstruction, at the coded block vector +/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`); +/// * `decode_token_recon_block`'s inter branch then reads one residual per +/// transform unit, through the INTER coefficient sets +/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane +/// inheriting the colocated luma unit's coded `tx_type`. +/// +/// Text order is libaom's: transform tree, prediction, luma residual, chroma +/// residual, bookkeeping. A skipped block codes no residual at all -- the +/// prediction is the reconstruction. +#[allow(clippy::too_many_arguments)] +fn decode_intrabc_rect( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + (mi_r, mi_c): (usize, usize), + (bw, bh): (usize, usize), + skip: bool, + (dv_row, dv_col): (i32, i32), + y: &mut PlaneBuf<'static>, + u: &mut PlaneBuf<'static>, + v: &mut PlaneBuf<'static>, + base_q_idx: u8, + fctx: &crate::decode::FrameCtx, +) -> Result<()> { + hit!(INTRABC_RECT_HITS); + // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`. + let idx = usize::from(bh > bw); + if skip { + INTRABC_RECT_SKIPPED_HITS.with(|c| { + let mut seen = c.get(); + seen[idx] += 1; + c.set(seen); + }); + } else { + INTRABC_RECT_CODED_HITS.with(|c| { + let mut seen = c.get(); + seen[idx] += 1; + c.set(seen); + }); + } + let (px, py) = (mi_c * MI, mi_r * MI); + let (cpx, cpy) = (px / 2, py / 2); + // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the + // halved shape's own `max_txsize_rect_lookup` entry IS that size for every + // shape this helper is called at, so the uv plane block is ONE unit -- + // the same call `decode_token_recon_block`'s own chroma loop makes. + let (cw, ch) = (bw / 2, bh / 2); + // lane-av1-intrabc r2: the square stride the proven INTER path uses + // (`side`). The residual grids, the prediction windows AND + // `TxParams::stride` are all laid out at it -- the block's own width + // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h` + // exceeds the stride). + let side = bw.max(bh); + let cside = cw.max(ch); + // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right + // or bottom frame edge reads no transform-tree symbol for the units + // outside it. + let mi_cols = 2 * y.true_width.div_ceil(8); + let mi_rows = 2 * y.true_height.div_ceil(8); + let leaves = read_block_tx_size_rect( + dec, + cdfs, + neighbours, + (mi_r, mi_c), + (bw, bh), + (mi_cols, mi_rows), + skip, fctx, + )?; + if leaves.is_some() { + hit!(INTRABC_RECT_VARTX_HITS); + } + // The whole-block prediction: `predict_inter_block` runs once, before any + // coefficient is read. `flush_recon` first -- the source is this frame's + // own reconstruction, including the writes this superblock has queued. + flush_recon(fctx, y, u, v); + // `mc::predict_with_filter` writes a DENSE window; the residual machinery + // reads it at the square stride, so re-lay it -- the same step the inter + // path takes for its own square prediction buffer. + let mut pred_y_dense = vec![0u16; bw * bh]; + mc::predict_with_filter( + &y.data, y.width, y.true_width, y.true_height, + mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true), + bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx, + ); + let mut pred_y = vec![0u16; side * side]; + for row in 0..bh { + pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]); + } + let mut pred_u_dense = vec![0u16; cw * ch]; + mc::predict_with_filter( + &u.data, u.width, u.true_width, u.true_height, + mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), + cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx, + ); + let mut pred_u = vec![0u16; cside * cside]; + for row in 0..ch { + pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]); + } + let mut pred_v_dense = vec![0u16; cw * ch]; + mc::predict_with_filter( + &v.data, v.width, v.true_width, v.true_height, + mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false), + cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx, + ); + let mut pred_v = vec![0u16; cside * cside]; + for row in 0..ch { + pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]); + } + let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); + let luma_tx_type: TxType; + let (luma_grid, u_grid, v_grid); + if skip { + // No residual syntax at all: the prediction IS the block. + // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes + // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip + // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm. + push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx); + push_mc_rect(1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx); + push_mc_rect(2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx); + luma_tx_type = TxType::DctDct; + luma_grid = Grid::Zero(side * side); + u_grid = Grid::Zero(cside * cside); + v_grid = Grid::Zero(cside * cside); + } else { + match leaves.as_ref() { + None => { + // One whole-block rectangular transform unit. + let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); + let (grid, tx_type) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_luma_set(bw, bh, fctx)?, + (bw, bh), + side, + 0, + around[0], + 0, + y, + px, + py, + Pred::Inline(&pred_y, side), + None, + None, fctx, + )?; + luma_tx_type = tx_type; + luma_grid = embed_grid_stride(&grid, bw, bh, side); + let (ug, _) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(cw, ch)?, + (cw, ch), + cside, + 1, + around[1], + 0, + u, + cpx, + cpy, + Pred::Inline(&pred_u, cside), + Some(luma_tx_type), + None, fctx, + )?; + u_grid = embed_grid_stride(&ug, cw, ch, cside); + let (vg, _) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(cw, ch)?, + (cw, ch), + cside, + 2, + around[2], + 0, + v, + cpx, + cpy, + Pred::Inline(&pred_v, cside), + Some(luma_tx_type), + None, fctx, + )?; + v_grid = embed_grid_stride(&vg, cw, ch, cside); + } + Some(leaves) => { + // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies + // the split override to LUMA only, per leaf -- the step the + // proven inter var-tx path applies right after its own residual + // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the + // leaf's own transform edges are never filtered. + for &(row, col, tw, th) in leaves.iter() { + neighbours.fill_lf_grid_leaf_luma( + (mi_r + row, mi_c + col), + tw / MI, + th / MI, + tw as u8, + th as u8, + ); + } + // One residual per transform unit, in the order the tree coded + // them; each unit reads its own neighbour-magnitude context off + // the units already decoded before it, and every unit adds onto + // its own window of the block's single prediction. + let mut first_tx_type = TxType::DctDct; + for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { + let tu_mi = (mi_r + row, mi_c + col); + let (tu_px, tu_py) = (px + col * MI, py + row * MI); + let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI); + let (tu_grid, tu_tx_type) = if tw == th { + let scan = default_scan(tw.min(32)); + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI); + read_inter_plane( + dec, + cdfs, + inter_txbset_for(tw, reduced), + scan, + 0, + neighbours.around_mi(tu_mi, tw)[0], + 0, + y, + tu_px, + tu_py, + tw, + base_q_idx, + tu_pred, + None, + Some(tu_skip_ctx), fctx, + )? + } else { + let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); + read_inter_plane_rect( + dec, + cdfs, + rect_inter_luma_set(tw, th, fctx)?, + (tw, th), + side, + 0, + neighbours.around_mi_rect(tu_mi, tw, th)[0], + 0, + y, + tu_px, + tu_py, + tu_pred, + None, + Some(tu_skip_ctx), fctx, + )? + }; + if idx == 0 { + first_tx_type = tu_tx_type; + } + neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); + } + // `av1_get_tx_type`'s chroma lookup lands on the colocated + // LUMA unit, which for a split block is the top-left one. + luma_tx_type = first_tx_type; + let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); + let (ug, _) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(cw, ch)?, + (cw, ch), + cside, + 1, + around[1], + 0, + u, + cpx, + cpy, + Pred::Inline(&pred_u, cside), + Some(luma_tx_type), + None, fctx, + )?; + u_grid = embed_grid_stride(&ug, cw, ch, cside); + let (vg, _) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(cw, ch)?, + (cw, ch), + cside, + 2, + around[2], + 0, + v, + cpx, + cpy, + Pred::Inline(&pred_v, cside), + Some(luma_tx_type), + None, fctx, + )?; + v_grid = embed_grid_stride(&vg, cw, ch, cside); + luma_grid = Grid::Zero(side * side); + } + } + } + let _ = luma_tx_type; + // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the + // next block reads a neighbour mode, its own block size in both `TXFM` + // bands (already done by `read_block_tx_size_rect`), a zeroed palette + // state (a stale entry would feed the next block's colour cache), and its + // DV into the intrabc mi grid the next block's DV predictor reads. + if leaves.is_some() { + neighbours.record_split_luma_rect_mi( + (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid], + ); + } else { + neighbours.record_rect_mi( + (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid], + ); + } + neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); + neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]); + neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); + neighbours.fill_lf_grid_rect( + (mi_r, mi_c), + bw / MI, + bh / MI, + bw.min(64) as u8, + bh.min(64) as u8, + 0, fctx, + ); + record_intrabc_mi_rect( + mi_r, + mi_c, + bw / MI, + bh / MI, + Some((dv_row, dv_col)), + neighbours, + fctx, + ); + Ok(()) +} + /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ @@ -10977,10 +11407,20 @@ fn decode_block_rect( r * (SUB / MI), c * (SUB / MI), fctx, )?; + if let Some((dv_row, dv_col)) = intrabc { - return decode_intrabc_owned_rect( - dec, cdfs, neighbours, (r * (SUB / MI), c * (SUB / MI)), (bw, bh), skip, - (dv_row, dv_col), y, u, v, base_q_idx, tx_select, reduced_tx_set, fctx, + return decode_intrabc_rect( + dec, + cdfs, + neighbours, + (r * (SUB / MI), c * (SUB / MI)), + (bw, bh), + skip, + (dv_row, dv_col), + y, + u, + v, + base_q_idx, fctx, ); } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); @@ -11033,6 +11473,14 @@ fn decode_block_rect( } else { 0 }; + // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame + // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`]. + publish_txfm_bands_if_in_inter( + neighbours, + (mi_r, mi_c), + depth_to_tx_wh(bw, bh, depth, fctx), + (bw, bh), fctx, + ); if depth != 0 || lossless(fctx) { hit!(TX_DEPTH_HITS); // lane-rectsplit r1: a split transform is predicted and reconstructed @@ -11478,10 +11926,11 @@ fn decode_leaf_rect( leaf_mi.0, leaf_mi.1, fctx, )?; + if let Some((dv_row, dv_col)) = intrabc { - decode_intrabc_owned_rect( + decode_intrabc_rect( dec, cdfs, neighbours, leaf_mi, (bw, bh), skip, (dv_row, dv_col), - y, u, v, base_q_idx, tx_select, reduced_tx_set, fctx, + y, u, v, base_q_idx, fctx, )?; return Ok(DC_PRED); } @@ -11548,6 +11997,14 @@ fn decode_leaf_rect( } else { 0 }; + // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads + // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`]. + publish_txfm_bands_if_in_inter( + neighbours, + leaf_mi, + depth_to_tx_wh(bw, bh, depth, fctx), + (bw, bh), fctx, + ); if depth != 0 || lossless(fctx) { // The same per-transform-unit walk the bigger strips take // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at @@ -11816,10 +12273,9 @@ fn decode_block_rect4( mi_c, fctx, )?; if let Some((dv_row, dv_col)) = intrabc { - decode_intrabc_owned_rect( - dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), skip, (dv_row, dv_col), - y, u, v, base_q_idx, tx_select, - fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, + decode_intrabc_rect( + dec, cdfs, neighbours, strip_mi, (bw, bh), skip, (dv_row, dv_col), + y, u, v, base_q_idx, fctx, )?; return Ok((DC_PRED, DC_PRED)); } @@ -16143,19 +16599,22 @@ fn decode_block_128rect( logical_tx as u8, 0, fctx, ); - if in_inter { + if in_inter || allow_intrabc_frame(fctx) { // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an // inter frame, intra ones included: an intra block stamps its // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands. - // A key frame has no var-tx tree and its readers use the deblock grid, - // so this is the inter path's alone. + // A key frame reads those bands only when it allows intrabc + // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom + // stamps here too -- lane-av1-intrabc r3. txfm_partition_update_rect( neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh), ); + } + if in_inter { hit_do! { INTRA128_IN_INTER_HITS.with(|c| { let mut h = c.get(); @@ -18892,13 +19351,26 @@ fn txfm_partition_update( /// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF, /// range 39156 where the reference has 54736 (class tx-grid-published-block-side /// / early-return-skips-tail). +/// +/// lane-av1-intrabc r3: an `allow_intrabc` KEY frame reads the same bands -- +/// `read_intra_frame_mode_info` returns early for an intrabc block, so +/// [`read_block_tx_size_rect`]'s var-tx tree is the intra path's one +/// `txfm_partition_context` reader, and it reads whatever the block ABOVE and +/// the block LEFT published. [`decode_block`] has published on such a frame +/// since lane-t900 r32; the RECT strips did not, so the band still held the +/// value of an older, smaller neighbour -- measured on the 256x192 testsrc2 +/// cq45 var-tx arm: the coded 16x8 intrabc strip at mi(38,48) read ctx 14 +/// where libaom reads 13 (`left_ctx` 4 vs the 8 the 16x8 intra strip at +/// mi(38,44) should have published), desyncing the tile there. fn publish_txfm_bands_if_in_inter( n: &mut Neighbours, at_mi: (usize, usize), (tx_w, tx_h): (usize, usize), (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx, ) { - if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() { + if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() + && !allow_intrabc_frame(fctx) + { return; } let (mi_r, mi_c) = at_mi; @@ -19676,7 +20148,7 @@ fn read_block_tx_size_rect( (bh / MI).min(mi_rows.saturating_sub(at_mi.0)), ); let mut leaves = Vec::new(); - if !fctx.tx_select_inter.with(std::cell::Cell::get) { + if !fctx.tx_select_frame.with(std::cell::Cell::get) { for row in (0..bh / MI).step_by(tx / MI) { for col in (0..bw / MI).step_by(tx / MI) { leaves.push((row, col, tx, tx)); @@ -19712,7 +20184,7 @@ fn read_block_tx_size_rect( return Ok(Some(leaves)); } let (tx_w, tx_h) = (bw, bh); - if !fctx.tx_select_inter.with(std::cell::Cell::get) { + if !fctx.tx_select_frame.with(std::cell::Cell::get) { // `TX_MODE_LARGEST`: no symbol at all, the whole block is one // transform, and `set_txfm_ctxs` records exactly what // `txfm_partition_update` would for that same unit. @@ -19913,6 +20385,16 @@ fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid Grid::Own(full) } +/// [`embed_rect_grid`] that keeps the shared zero marker zero: an all-zero +/// transform unit's grid IS `Grid::Zero` (whose deref is the shared +/// `ZERO_RESIDUAL`), so re-laying it would read a zero-length slice. +fn embed_grid_stride(grid: &Grid, w: usize, h: usize, stride: usize) -> Grid { + if is_zero_grid(grid) { + return Grid::Zero(stride * stride); + } + Grid::Own(embed_rect_grid(grid, w, h, stride)) +} + /// A rect coefficient grid re-laid into the square `stride x stride` grid the /// neighbour/deblock stamps downstream of the residual expect. fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec { @@ -23490,6 +23972,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // otherwise inherit it and read its `tx_depth` context off the inter // frame's stale `TXFM_CONTEXT` bands. fctx.tx_select_inter.with(|c| c.set(false)); + fctx.tx_select_frame.with(|c| c.set(tx_select)); // lane-av1-rect14: an intrabc block is `is_inter_block`, so its // `tx_type` CDF is the INTER set selected by this frame's // `reduced_tx_set`. Left at the cell default, the first coded diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index c3421099..0d1f672c 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -251,6 +251,30 @@ pub struct MiGrid { cols: usize, rows: usize, cells: Vec>, + /// lane-av1-intrabc r4: the CODED BLOCK's own `(width, height)` in mi + /// units for every cell of the frame, whatever the block is -- the + /// block-COVERAGE map a scan's run-length stepping needs. + /// + /// libaom's candidate scans walk `xd->mi[]`, which holds an + /// `MB_MODE_INFO` for EVERY coded block, and step by + /// `mi_size_wide/height[candidate->bsize]`. A decoder grid that only + /// holds the blocks with an MV (the intrabc blocks here) makes every + /// intra neighbour read as *uncovered*: the scan then advances that cell + /// by one instead of by the neighbour's real width, which walks it + /// straight into a cell libaom never probes -- and can even vote. + /// Measured on the 512x384 `testsrc2` cq45 `--enable-tx-size-search=0` + /// arm: at `mi(84,104)` the row scan's extended offset `-3` over-reached + /// from `(81,106)` (libaom's last probe, an 8x16 intrabc voting + /// `-520`) to `(81,108)` (a 16x16 intrabc voting `-512` with a 16-wide + /// weight), flipping the sorted stack so `nearestmv` became `-512` where + /// libaom's is `-520` -- one whole-pel-wrong DV predictor, identical + /// coded diff, 528 wrong luma samples. + /// + /// `[0, 0]` means "no block recorded here" and reads as uncovered, so + /// every grid that never fills this map (the tile writer's own, and + /// every synthetic test grid) keeps exactly its old `None`-per-cell + /// behaviour. + cover: Vec<[u8; 2]>, /// One `skip` flag per cell, beside `cells` rather than inside `MiInfo` /// -- the mv-stack scan walks `cells` for every inter block, so the CELL /// must stay 16 bytes (`mi_info_cell_stays_compact`), and nothing on the @@ -287,6 +311,7 @@ impl MiGrid { cols, rows, cells: vec![None; cols * rows], + cover: vec![[0, 0]; cols * rows], skips: vec![false; cols * rows], tile_row0: 0, tile_col0: 0, @@ -415,8 +440,33 @@ impl MiGrid { } } + /// Records the `w_mi` x `h_mi` footprint of the coded block at + /// `(row, col)` in this grid's block-coverage map (see `cover`) -- called + /// for EVERY coded block, not just the ones that carry an MV. Out-of-range + /// coordinates are a no-op, and an overhanging width is clipped to the + /// grid (the recorded width still names the block's real one, exactly as + /// `mi_size_wide[bsize]` does). + pub fn cover_rect(&mut self, row: usize, col: usize, w_mi: usize, h_mi: usize) { + if row >= self.rows || col >= self.cols || w_mi == 0 || h_mi == 0 { + return; + } + let w = w_mi.min(self.cols - col); + let cell = [w_mi as u8, h_mi as u8]; + for r in row..(row + h_mi).min(self.rows) { + let base = r * self.cols + col; + self.cover[base..base + w].fill(cell); + } + } + /// The unit at `(row, col)`, or `None` when it is outside the grid, hasn't /// been coded, or sits outside the current tile's own bounds ([`Self::set_tile_bounds`]). + /// + /// A cell that holds no MV but IS covered by a recorded block + /// ([`Self::cover_rect`]) reads as that block's own footprint with + /// `is_inter == false` -- libaom's `xd->mi[]` always holds an + /// `MB_MODE_INFO`, and a candidate that casts no vote still advances the + /// scan by its own width. Such an entry can never match + /// (`single_ref_match` rejects a non-inter unit) and carries a zero MV. pub fn get(&self, row: usize, col: usize) -> Option { if row < self.rows && col < self.cols @@ -425,10 +475,28 @@ impl MiGrid { && col >= self.tile_col0 && col < self.tile_col1 { - self.cells[row * self.cols + col] - } else { - None + let idx = row * self.cols + col; + if let Some(info) = self.cells[idx] { + return Some(info); + } + let [w, h] = self.cover[idx]; + if w == 0 { + return None; + } + return Some(MiInfo { + is_inter: false, + ref_frame: 0, + ref_frame1: NO_REF1, + mv: (0, 0), + mv1: (0, 0), + is_new_mv: false, + is_global_mv0: false, + is_global_mv1: false, + size: w, + size_h: h, + }); } + None } /// The unit at `(row, col)` ignoring the tile window -- the frame-level diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 5c9ad31b..2b2ad28f 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -6330,6 +6330,12 @@ pub(crate) mod tests { // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal, // must_read_use_intrabc_on_a_rect_strip) let arms: [(&str, &str, &[&str], bool, bool); 8] = [ + // lane-av1-intrabc (2026-09-20): this arm used to REFUSE here -- the + // 16x8 rect strip it decodes is the first block on main that reaches + // `decode_intrabc_rect`, so the whole arm stopped at a named refusal. + // Reconstruction is ported now, so the arm decodes pixel-exact and + // the `rect_total` assert below keeps it from quietly falling back + // to an ordinary-intra decode of the same block. ("testsrc2-cq50-txs0", TS, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=0"], false, true), ("smptebars-cq40-txs0", SB, &["--cq-level=40", "--enable-palette=0", "--enable-tx-size-search=0"], false, false), ("smptebars-cq45-txs0", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=0"], false, true), @@ -6348,6 +6354,7 @@ pub(crate) mod tests { let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0usize, 0u32, 0u32, 0u32); let mut leaf8_total = 0usize; + let mut rect_total = 0usize; for (arm, src, extra, expect_refusal, must_read) in &arms { let render = || { let out = Command::new("ffmpeg") @@ -6420,6 +6427,7 @@ pub(crate) mod tests { decode::reset_rect_intrabc_reads(); crate::decode::reset_intrabc_hits(); crate::decode::reset_leaf8_intrabc_hits(); + crate::decode::reset_intrabc_rect_hits(); let decoded = decode_stream(&stream); let reads = decode::rect_intrabc_reads(); // Blocks that decoded `use_intrabc == 1` (square path), i.e. that @@ -6434,6 +6442,7 @@ pub(crate) mod tests { // `gate-blind-to-feature`). let leaf8 = crate::decode::leaf8_intrabc_hits(); leaf8_total += leaf8; + rect_total += crate::decode::intrabc_rect_hits(); if *arm == "testsrc2-cq55-leaf8" { assert!( leaf8 > 0, @@ -6510,7 +6519,9 @@ pub(crate) mod tests { {refused} refused by name, {frames_compared} frames compared, \ {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)" ); - eprintln!("{NAME}: {leaf8_total} intrabc block(s) at an 8x8 leaf"); + eprintln!( + "{NAME}: {rect_total} intrabc block(s) on a HORZ/VERT rect strip (decode_intrabc_rect)" + ); assert!(reads_total > 0, "{NAME}: gate is vacuous -- no arm read the symbol"); assert!( leaf8_total > 0, @@ -6520,10 +6531,16 @@ pub(crate) mod tests { blocks_total > 0 && fired_arms > 0, "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block" ); - assert_eq!( - refused, 0, - "{NAME}: a rect-strip intrabc block refused -- reconstruction regressed" + assert!( + rect_total > 0, + "{NAME}: no arm decoded an intrabc block on a HORZ/VERT rect strip -- \ + `decode_intrabc_rect` is untested" ); + // lane-av1-intrabc: this used to be exactly one -- the 2:1 rect strips + // now reconstruct. The 1:4 pair strips (`decode_rect4_16_strip` et al.) + // still refuse by name, but no arm HERE reaches that shape; it stays + // pinned by `refusal_inventory`'s own gate. + assert_eq!(refused, 0, "{NAME}: an arm still refuses by name"); assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact"); assert_eq!( out_of_scope_mismatch, 0, @@ -6646,6 +6663,290 @@ pub(crate) mod tests { // even if some other prefix sample happens to match. assert_eq!(frames[0].y[108], refs[0].y[108], "{NAME}: measured byte 108"); } + /// lane-av1-intrabc r4: the reviewer's unblock witness for the rect-strip + /// reconstruction -- a CODED `use_intrabc` block (so its residual reader + /// runs, not just the prediction copy) on a 2:1 strip in BOTH + /// orientations, plus the `TX_MODE_SELECT` (var-tx) shape, every arm + /// byte-exact against ffmpeg. + /// + /// The orientation counters (`intrabc_rect_coded_hits`) are the + /// non-vacuity instrument: [`intrabc_rect_hits`] counts neither the skip + /// flag nor the orientation, so an arm that silently became an all-skip + /// stream (or a stream with only one orientation) would keep the old gate + /// green while the coded residual path went untested + /// (class `gate-blind-to-feature`). + /// + /// # The VERT arm is also the DV-PREDICTOR regression witness + /// + /// The 512x384 arm is the stream that exposed r4's defect: 528 of 294912 + /// luma samples were wrong, all inside one `skip == 1` intrabc copy at + /// `mi(84,104)`. Its coded diff was identical to aomdec's and the post-read + /// range matched exactly (`rng=33207` both), so nothing was misread -- the + /// DV PREDICTOR differed. libaom picks `nearestmv` (`-520`) from the + /// `INTRA_FRAME` MV stack; this decoder picked `-512`, one stack entry + /// lower, because the scan that builds that stack walked further than + /// libaom's. The scans step by the candidate BLOCK's own width + /// (`mi_size_wide[bsize]`) over `xd->mi[]`, which holds an entry for every + /// coded block; this decoder's MV grid held only the intrabc blocks, so a + /// non-intrabc neighbour read as uncovered and the scan advanced that cell + /// by one instead of by its real width. See `MiGrid::cover` for the + /// measured walk. A stream that decodes the DV predictor from the wrong + /// stack entry cannot pass this arm's pixel comparison. + #[test] + fn a_coded_rect_intrabc_block_reconstructs_in_both_orientations() { + const NAME: &str = "a_coded_rect_intrabc_block_reconstructs_in_both_orientations"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + const TS256: &str = "testsrc2=s=256x192:r=25"; + const TS512: &str = "testsrc2=s=512x384:r=25"; + // (arm, source, width, height, per-arm overrides, the coded orientation + // this arm must exercise, and whether the frame must code + // `TX_MODE_SELECT` with `allow_intrabc` still set) + let arms: [(&str, &str, usize, usize, &[&str], u8, bool); 3] = [ + // HORZ (16x8) coded strip -- the shape the in-gate witness above + // already reconstructs, pinned here with its own orientation counter. + ("horz-coded-256-cq45-pal0-txs0", TS256, 256, 192, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=0"], 0, false), + // VERT (8x16) coded strip AND the DV-predictor regression stream. + ("vert-coded-512-cq45-pal1-txs0", TS512, 512, 384, &["--cq-level=45", "--enable-palette=1", "--enable-tx-size-search=0"], 1, false), + // The `TX_MODE_SELECT` (stream A) shape: `--enable-tx-size-search=1` + // makes the frame code `tx_mode == Select`, so the intrabc block's + // transform size comes off the INTER var-tx tree. + ("txmode-select-256-cq45-pal0-txs1", TS256, 256, 192, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=1"], 0, true), + ]; + let mut coded_total = [0usize; 2]; + let mut frames_compared = 0usize; + for (arm, src, width, height, extra, want_orient, want_select) in &arms { + let render = || { + let out = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt", + "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); + out.stdout + }; + let y4m = render(); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--bit-depth=8", + "--input-bit-depth=8", + "--passes=1", + "--end-usage=q", + "--cpu-used=0", + "--lag-in-frames=0", + "--kf-max-dist=1", + "--limit=1", + "--threads=1", + "--tile-columns=0", + "--enable-rect-partitions=1", + "--enable-1to4-partitions=1", + "--min-partition-size=8", + "--max-partition-size=32", + "--sb-size=64", + "--tune-content=screen", + "--enable-intrabc=1", + ]) + // aomenc keeps the LAST occurrence of a repeated flag. + .args(*extra) + .args(["--obu", "-o", "-", "-"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m) + .or_else(|e| match e.kind() { + std::io::ErrorKind::BrokenPipe => Ok(()), + _ => Err(e), + }) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{NAME}: aomenc refused {arm}: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + if *want_select { + let (select, premise) = tx_select_and_intrabc_frames(&stream); + assert!( + select > 0 && premise > 0, + "{NAME}: {arm} no longer codes a frame with both tx_mode == Select and \ + allow_intrabc (select={select} premise={premise}), so the TX_MODE_SELECT \ + shape is untested here" + ); + } + crate::decode::reset_intrabc_rect_hits(); + let frames = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME}: {arm} refused: {e}")); + assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame"); + let coded = crate::decode::intrabc_rect_coded_hits(); + coded_total[0] += coded[0]; + coded_total[1] += coded[1]; + assert!( + coded[*want_orient as usize] > 0, + "{NAME}: {arm} reconstructed no CODED ({}) rect intrabc block -- the residual \ + reader for this orientation is untested (coded horz/vert = {coded:?})", + if *want_orient == 0 { "HORZ" } else { "VERT" } + ); + let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len()); + assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count"); + for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { + assert!( + ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, + "{NAME}: {arm} frame {i} does not match ffmpeg" + ); + frames_compared += 1; + } + eprintln!( + "{NAME}: {arm} {} frame(s) exact, coded rect intrabc horz={} vert={}", + frames.len(), + coded[0], + coded[1] + ); + } + assert!( + coded_total[0] > 0 && coded_total[1] > 0, + "{NAME}: gate is vacuous -- coded rect intrabc blocks seen: horz={} vert={}", + coded_total[0], + coded_total[1] + ); + assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact"); + + // lane-av1-intrabc r5: the SKIPPED VERT 2:1 strip -- the arm the + // reviewer's sweep panicked on (a skipped 8x32 strip passed a + // `bw * bh`-sized ZERO_RESIDUAL slice at stride `side`, and + // `reconstruct_mc_rect` indexed `row * side + w` past its end). + // Skip-heavy recipes (low cq, palette off AND on), each decoded + // byte-exact vs ffmpeg on BOTH the default single-threaded path + // (`EC_AV1_RECON_THREADS == 1`, the inline ReconPlanes arm that + // panicked pre-fix) AND the wavefront path. The skipped-orientation + // counter is asserted per arm (`gate-blind-to-feature`): a recipe + // that stops producing a skipped VERT strip fails instead of passing + // vacuously. `lock_gate_counters` because `set_recon_threads` is a + // process-wide knob. + let _par_lock = lock_gate_counters(); + let skip_arms: [(&str, &str, usize, usize, &[&str]); 2] = [ + ("vert-skip-512-cq30-pal0-txs0", TS512, 512, 384, &["--cq-level=30", "--enable-palette=0", "--enable-tx-size-search=0"]), + ("vert-skip-512-cq30-pal1-txs0", TS512, 512, 384, &["--cq-level=30", "--enable-palette=1", "--enable-tx-size-search=0"]), + ]; + for (arm, src, width, height, extra) in &skip_arms { + let y4m = { + let out = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt", + "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); + out.stdout + }; + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--bit-depth=8", "--input-bit-depth=8", "--passes=1", + "--end-usage=q", "--cpu-used=0", "--lag-in-frames=0", "--kf-max-dist=1", + "--limit=1", "--threads=1", "--tile-columns=0", + "--enable-rect-partitions=1", "--enable-1to4-partitions=1", + "--min-partition-size=8", "--max-partition-size=32", "--sb-size=64", + "--tune-content=screen", "--enable-intrabc=1", + ]) + // aomenc keeps the LAST occurrence of a repeated flag. + .args(*extra) + .args(["--obu", "-o", "-", "-"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m) + .or_else(|e| match e.kind() { + std::io::ErrorKind::BrokenPipe => Ok(()), + _ => Err(e), + }) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{NAME}: aomenc refused {arm}: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + // Default single-threaded path first (the arm that panicked + // pre-fix), then the wavefront path; both must match ffmpeg. + let mut skipped_vert = 0usize; + for threads in [1usize, 4] { + crate::par::set_recon_threads(threads); + crate::decode::reset_intrabc_rect_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + crate::par::set_recon_threads(1); + panic!("{NAME}: {arm} refused at {threads} recon thread(s): {e}") + } + }; + let skipped = crate::decode::intrabc_rect_skipped_hits(); + assert!( + !frames.is_empty(), + "{NAME}: {arm} decoded no frame at {threads} recon thread(s)" + ); + let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len()); + assert_eq!( + frames.len(), + theirs.len(), + "{NAME}: {arm} frame count at {threads} recon thread(s)" + ); + for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() { + assert!( + ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v, + "{NAME}: {arm} frame {i} does not match ffmpeg at {threads} recon thread(s)" + ); + } + if threads == 1 { + skipped_vert = skipped[1]; + } else { + assert_eq!( + skipped[1], skipped_vert, + "{NAME}: {arm} skipped VERT strip count changed across recon paths" + ); + } + eprintln!( + "{NAME}: {arm} {} frame(s) exact at {threads} recon thread(s), skipped rect intrabc horz={} vert={}", + frames.len(), + skipped[0], + skipped[1] + ); + } + crate::par::set_recon_threads(1); + assert!( + skipped_vert > 0, + "{NAME}: {arm} reconstructed no SKIPPED VERT rect intrabc strip -- the r5 stride arm is untested" + ); + } + } /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1` /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled` diff --git a/lanes/av1intrabc.report.md b/lanes/av1intrabc.report.md new file mode 100644 index 00000000..f0f3098b --- /dev/null +++ b/lanes/av1intrabc.report.md @@ -0,0 +1,539 @@ +# lane-av1-intrabc - rect-strip intrabc reconstruction (HORZ/VERT 2:1 shapes) + +Base `main` **3ecd4a10**. Worktree `../edith_codecs-av1ibc`, branch +`lane-av1-intrabc`, `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1ibc`. + +## 1. What landed + +`decode_intrabc_rect` (`crates/ec-av1/src/decode.rs`, ~10910): the missing +reconstruction arm for a `use_intrabc` block on a **2:1 rect strip**, ported +from libaom's `av1_predict_intra_block`/`predict_inter_block` intrabc path: + +- whole-block prediction once (`predict_inter_block`), for luma at the block + footprint and for both chroma planes at `av1_get_max_uv_txsize(bw x bh)`; +- skip case: prediction IS the block (`push_mc_rect`, zero residual); +- coded case: residual per transform unit -- one whole-block rect TU + (`read_inter_plane_rect`, `TxbSet::LumaRect32x16`/`ChromaRect16x8` and the + real rect scan/context tables) or one residual per var-tx leaf; +- bookkeeping identical in shape to the square intrabc path: mode + `DC_PRED` into the mode maps, coefficient contexts, zeroed palette state, + skip/LF grids, and the DV into the intrabc mi grid. + +Wired at all 2:1 rect intrabc slots: `decode_block_rect` (16x32/32x16), +`decode_block_rect4` (32x8/8x32 + 16x8/8x16), `decode_leaf_rect`; in +`decode_block_rect64`/`decode_block_128rect` the wiring REFUSES the shape (a +named refusal slot, not a reconstruction); engagement counters +`intrabc_rect_hits` / `intrabc_rect_vartx_hits` exposed on `decode_probe`. + +## 2. Byte-exactness witnesses + +In-gate (flipped pin -> witness): `stream::tests:: +a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips`. Its +`testsrc2-cq50-txs0` arm used to stop at the rect-strip refusal; it now decodes +1 frame, **1 intrabc block on a HORZ/VERT rect strip**, pixel-exact vs ffmpeg. +Gate totals (re-measured at r4, on the committed tree): **5** intrabc blocks +over **5** arms -- 3 arms decode ZERO intrabc blocks (out of scope), 187 rect +`use_intrabc` reads, 8 frames compared, 0 mismatches, 0 named refusals, 1 +intrabc block on a HORZ/VERT rect strip. The r4 gate +`a_coded_rect_intrabc_block_reconstructs_in_both_orientations` adds 3 more +byte-exact frames (HORZ coded, VERT coded, TX_MODE_SELECT). + +Standalone recipes (aomenc oracle at `~/.cache/aom-oracle/build/aomenc`, probe +`cargo run --release -p ec-av1 --example decode_probe -- `): + +| recipe (base: `--cpu-used=0 --tune-content=screen --enable-intrabc=1 +--min-partition-size=8 --max-partition-size=32 --sb-size=64 --enable-palette=1 +--enable-tx-size-search=0 --enable-rect-partitions=1 --enable-1to4-partitions=1`) | intrabc rect blocks | shape (mi) | skip | result | +|---|---|---|---|---| +|`testsrc2=s=256x192:r=25 --cq-level=50 --enable-palette=0`, 1:4 off|0|--|--|REFUSED (16x8 CPR block, `--enable-1to4-partitions=0`)| +|`testsrc2=s=256x192:r=25 --cq-level=50 --enable-palette=0 --min-partition-size=4 --max-partition-size=16`|1|16x8 @(38,48)|0|**EXACT**| +|`testsrc2=s=256x192:r=25 --cq-level=45 --enable-palette=0`|1|16x8 @(38,48)|0|**EXACT**| +|`testsrc2=s=256x192:r=25 --cq-level=45 --enable-palette=1`|1|16x8 @(38,48)|0|**EXACT**| +|`testsrc2=s=256x192:r=25 --cq-level=50`, 1:4 off, `--enable-tx-size-search=1`|0|--|--|REFUSED| + +Every `EXACT` row is `cmp` of the probe's raw output against ffmpeg +`-pix_fmt yuv420p` decoded from the same `.obu`, i.e. byte-identical planes. +The 16x8 witnesses exercise the residual reader (`skip=0`); the 8x32 +witnesses exercise `decode_block_rect4`'s wiring through the same helper. + +## 3. Still refused by name + +**1:4 pair strips** (`PARTITION_HORZ_4`/`VERT_4`, 16x4/4x16): +`intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not +ported at this shape)` at `decode_rect4_16_strip`, `decode_block_rect4`'s 1:4 +arm and `decode_block_128rect`. Reason this is NOT this lane's helper: a 1:4 +strip is coded as a PAIR (both children share one chroma block). The chroma is +sourced at the pair's **odd-mi member** -- the BOTTOM strip of a `HORZ_4` pair, +the RIGHT strip of a `VERT_4` one (`is_chroma_reference`, `av1_common_int.h` +-- the reviewer corrected an earlier, inverted note in this report) -- and the +pair's chroma transform is read once for the pair, so its neighbour and +coefficient bookkeeping is a different model from the 2:1 helper above. Reachable witnesses for whoever takes it next: +`aomenc --allintra` (already stops there today), `--allintra` cpu-used 0 +(lands there after the tx-depth/tx-band work, see lane-av1-txbands), and this +hand-made recipe: `testsrc2=s=640x480:r=25 --cq-level=60 --enable-palette=1 +--enable-tx-size-search=0 --enable-rect-partitions=1 --enable-1to4-partitions=1 +--sb-size=64` (16x4 @ mi(76,108), skip=0). + +**Mixed-leaf var-tx intrabc** (`decode.rs:14816`): unchanged. The census gate +`an_intrabc_vartx_census_measures_the_mixed_leaf_refusal` (green) shows the +four-quantiser census still produces UNIFORM var-tx trees only, so no reachable +stream exercises it -- census-pinned, as the wave plan expected. The 2:1 helper +itself already handles a var-tx tree's leaves (`INTRABC_RECT_VARTX_HITS`), so +the refusal that remains is only the square/leaf path's. + +## 4. Gates run + +- `cargo check -p ec-av1 --all-targets` -> 0 warnings. +- `cargo test -p ec-av1 --lib -- --exact stream::tests:: + a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips` -> ok. +- `cargo test -p ec-av1 --lib -- refusal` -> 21 passed. +- Full `--lib` suite: NOT run to completion by this lane (budget); sibling lane + lane-av1-txbands is editing the same file, so the workspace-wide run belongs + to the batch-level gate. + +## 4b. Review round 2 (2026-09-20) -- what the fixes did and what is STILL open + +Fixed on this branch (reviewer findings P1-2 / P2 and part of P1-1): + +- **P1-2 (panic)**: every rect residual/prediction in `decode_intrabc_rect` now + uses the proven INTER path's square stride (`side = bw.max(bh)`, + `cside = cw.max(ch)`), and the prediction window is re-laid at that stride. + Before: `TxParams::run` panicked (`range end index 8 out of range`) on every + coded VERT strip. +- **P2 (LF grid)**: the var-tx arm now applies + `Neighbours::fill_lf_grid_leaf_luma` per leaf (LUMA only), the step the + proven inter var-tx path applies. +- **P1-1 (tx-mode)**: the intrabc tx-size read no longer keys on + `fctx.tx_select_inter` (forced false by the key-frame tile decoder) but on a + new frame-level `fctx.tx_select_frame`, set for EVERY frame from the frame + header's own `tx_mode == TxMode::Select`. Measured effect: the var-tx arm now + fires (`intrabc_rect_vartx_hits == 1`) on the encode below. + +**STILL NOT BYTE-EXACT** -- two repros, both with the mismatch confined to the +frame's BOTTOM 64-row band (luma rows h-64..h-1, chroma rows h/2-32..h/2-1): + +``` +# var-tx leaf arm (intrabc_rect=1, var-tx tree=1): 4520/73728 bytes differ +ffmpeg -v error -f lavfi -i testsrc2=s=256x192:r=25 -t 0.2 -pix_fmt yuv420p -strict -1 -f yuv4mpegpipe - | ~/.cache/aom-oracle/build/aomenc --codec=av1 --bit-depth=8 --input-bit-depth=8 --passes=1 --end-usage=q --cpu-used=0 --lag-in-frames=0 --kf-max-dist=1 --limit=1 --threads=1 --tile-columns=0 --min-partition-size=8 --max-partition-size=32 --sb-size=64 --tune-content=screen --enable-intrabc=1 --cq-level=45 --enable-palette=0 --enable-tx-size-search=1 --enable-rect-partitions=1 --enable-1to4-partitions=1 --obu -o /tmp/a31.obu - +# coded rect arm (intrabc_rect=2): no panic now, 7900/294912 bytes differ +# ... same recipe, testsrc2=s=512x384:r=25 --cq-level=45 --enable-palette=1 +# --enable-tx-size-search=0 +``` + +First divergence of the 256x192 arm: luma row 128, column 224 (the bottom +superblock row); of the 512x384 arm: luma row 320, column 424. So a coded rect +intrabc block in the bottom band still reconstructs wrong -- the shapes the +in-gate witness covers (`testsrc2-cq50-txs0`, `--enable-tx-size-search=0`, +skip and coded 16x8) stay pixel-exact, and every `smptebars`/`testsrc2` recipe +above is EXACT, so the defect is specific to these two arms and is the first +thing the next round must localize (per-block DV/prediction trace against +`EC_VARTX`/`EC_ISTEP`). + +**Verdict: NOT merge-ready.** The two P1s are addressed structurally (no panic, +correct tx-mode keying) and the P2 step is in, but the reviewer's merge +unblock condition -- a coded rect intrabc witness in BOTH orientations plus a +TX_MODE_SELECT one, all byte-exact -- is NOT met: the TX_MODE_SELECT arm is +exactly the 256x192 repro above and it is still 4520 bytes off. + +## 5. Deferred + +1. **1:4 pair-strip intrabc** -- named above, with the model difference and the + witness recipes. `deferred(1:4 pair-chroma model)` +2. **Full-suite gate** -- `deferred(batch-level run after lane-av1-txbands + merges; same file, mid-flight run would measure a half-built tree)` + +## 4c. Round 3 (2026-09-20) -- two frame-level root causes found, one stream now exact + +Both repros were localized with a per-symbol range ladder +(`EC_TRACE_MODE_STEP` on our decoder vs the instrumented aomdec), then the +first untraced region with `EC_TRACE_COEFF`/`EC_ISTEP`. + +### Root cause 1 (stream A, and latent for every rect strip): the key-frame RECT path never published the `TXFM_CONTEXT` bands + +`read_intra_frame_mode_info` (libaom `decodemv.c:909`) returns EARLY for an +intrabc block, so the block's transform size comes from +`parse_decode_block`'s INTER var-tx branch -- `read_tx_size_vartx`, whose +depth-0 context is `txfm_partition_context(above_txfm[mi_col], +left_txfm[mi_row], bsize, tx_size)`. Those bands are written by libaom's +`set_txfm_ctxs` at the end of EVERY `decode_block`/`decode_token_recon_block`, +key frames included. + +Only `decode_block` (lane-t900 r32, gated on the frame's `allow_intrabc`) and +`decode_block_rect4`/`decode_block_rect64`/`decode_rect4_16_strip`/ +`decode_leaf_rect8` (gated on `INTRA_IN_INTER_MODE`) published. The 2:1 strip +readers reached on a key frame -- `decode_block_rect` (16x32/32x16), +`decode_leaf_rect` (8x16/16x8 leaves of a 16x16 HORZ/VERT split) and +`decode_block_128rect` -- published nothing. + +Measured (256x192 testsrc2 cq45 var-tx arm): the coded intrabc 16x8 strip at +mi(38,48) read `txfm_split_rect ctx=14` where aomdec reads `ctx=13`; the left +band held 4 (from the 8x8 at mi(38,42)) where libaom had 8 (published by the +non-intrabc 16x8 intra strip at mi(38,44), `tx_depth=0` -> `TX_16X8`, +`tx_size_high=8`), i.e. `left = 4 < 8` (true) instead of `8 < 8` (false). From +that wrong CDF row the tile desynced at the very next symbol. + +Fix: `publish_txfm_bands_if_in_inter`'s guard now also fires when +`allow_intrabc_frame(fctx)`, and the three missing readers above call it with +`depth_to_tx_wh(bw, bh, depth, fctx)` (one call each, placed before their +`depth != 0` split branch so both arms publish once). + +### Root cause 2 (stream B): a key frame never published the frame's `reduced_tx_set` + +`decode_key_frame_tile_with_cdfs` set `tx_select_inter=false` and the (r2) +`tx_select_frame`, but not `reduced_tx_set_inter`, which therefore kept its +`true` DEFAULT (or an inter frame's stale value). An intrabc block is +`is_inter_block`, so `read_tx_type` resolves its `tx_type` through the INTER +sets -- `av1_get_ext_tx_set_type` off `cm->features.reduced_tx_set_used`. + +Measured (512x384 testsrc2 cq45 `--enable-tx-size-search=0`): the first rect +(8x16) intrabc block at mi(80,106) read `tx_type` from a 2-symbol CDF +(`inter_tx_type_8`, `head=[4167,32768,0]`) where aomdec read the 16-symbol +`EXT_TX_SET_ALL16` row (`inter_ext_tx_cdf[1][TX_8X8]`, +`eset=1 set=5 sqr=1 nsym=16`, `head=[31123,30195,27990,27057]`); post-read +range 37912 vs 62176. Every earlier intrabc block in that frame was 16x16 +(square), which never consults this cell, so the defect surfaced exactly at the +first rect strip. + +Fix: `decode_key_frame_tile_with_cdfs` now publishes the header's +`reduced_tx_set` into `fctx.reduced_tx_set_inter`, mirroring `tx_select_frame`. + +### State after the two fixes (no push; committed on the lane) + +| stream | bytes differ before | now | +|---|---|---| +| A 256x192 var-tx 16x8 | 4520/73728 | **BYTE-EXACT** (Y/U/V, `cmp` vs ffmpeg) | +| B 512x384 coded 8x16 | 7900/294912 | 528 luma samples | + +### What is STILL open on B (precise) + +The mode-info ladder is now fully IN SYNC (identical symbol sequence AND +identical post-read ranges through the end of the frame), and the residual +reads agree. The single remaining difference is a **DV VALUE**: + +``` +O EC_DV mi_row=84 mi_col=104 dv_col=0 dv_row=-512 rng=33207 +U EC_DV mi_row=84 mi_col=104 dv_col=0 dv_row=-504 rng=33207 +``` + +Same pre-range (33207 after the read on both sides) means the coded +`diff` is identical; the reconstructed DV differs because the **DV predictor** +differs. aomdec's own `EC_IBC` line for that block reads +`bsize=6 skip=1 nstack=2 nearest=(-520,0) near=(-512,0) dv_ref=(-520,0) +dv=(-512,0)`, i.e. `ref = nearest = -520`; our result `-504` is consistent with +`ref = -512` (the `nearmv`), so our intrabc `INTRA_FRAME` MV-stack ORDERING at +that block differs from libaom's (`av1_find_mv_refs` -> `setup_ref_mv_list` -> +`av1_find_best_ref_mvs`, then `dv_ref = nearestmv != 0 ? nearestmv : nearmv`). + +The 528 mismatched luma samples (`rows 351..383`, `cols 416..431`) are all +inside this one wrong copy: the block is `skip=1`, so the wrong DV is a wrong +pixel copy, and the region below it inherits the shift. + +Next step for whoever takes it: instrument `read_intrabc_dv`'s candidate +gathering (`record_intrabc_mi_rect` / the mv-stack build) with the candidate +list for mi(84,104) and diff it against aomdec's `EC_IBC` +`nstack/nearest/near/dv_ref` (already printed) -- the defect is candidate +ORDER/WEIGHT, not the DV syntax. + +### Gates run this round + +- `cargo check -p ec-av1 --all-targets` -> 0 warnings. +- Standalone: A byte-exact; B 528 luma samples (from 7900). +- **Not run**: the in-gate `--lib` arms, the refusal suite, and the full suite. + The lane is NOT merge-ready (B is not byte-exact and the reviewer's + TX_MODE_SELECT gate is still red); the batch-level suite run stays deferred. + +`deferred(DV-predictor candidate ordering at mi(84,104))` + +## 4d. Round 4 (2026-09-20) -- the DV predictor's root cause is BLOCK COVERAGE, not candidate weighting; stream B is byte-exact + +The remaining defect was localized to a single wrong DV at `mi(84,104)` on the +512x384 stream, with identical coded diff and identical post-read range. The +task named candidate ORDER/WEIGHT; the order was indeed wrong, but the cause is +one level down: **our intrabc MV grid only contained the intrabc blocks.** + +### Mechanism (measured, not inferred) + +libaom's `setup_ref_mv_list` row/col scans walk `xd->mi[]`, which holds an +`MB_MODE_INFO` for EVERY coded block, and step by +`mi_size_wide/height[candidate->bsize]`. Our `MiGrid` was filled only by +`record_intrabc_mi_rect`, so every intra non-intrabc neighbour read as +`None` and the scan advanced that cell by ONE instead of by the neighbour's +real width. At `mi(84,104)` (16x16, `bsize=6`) the row scan's extended offset +`-3` therefore over-reached from libaom's last probe `(81,106)` (the 8x16 +intrabc voting `-520`) to `(81,108)` -- a 16x16 intrabc voting `-512` with a +16-wide (`len 4 * weight 4`) contribution libaom never makes. + +Instrumented oracle (`~/.cache/aom-oracle`, new `EC_TRACE_STACK` / +`EC_TRACE_STACK2` prints in `setup_ref_mv_list` + `scan_row_mbmi` / +`scan_col_mbmi` / `scan_blk_mbmi`): + +``` +O EC_STACK mi_row=84 mi_col=104 ref=0 w=4 h=4 cnt=2 near_match=1 ref_match=1 \ + [0 w=656 mv=(-520,0)] [1 w=648 mv=(-512,0)] +U EC_STACK_OURS mi_row=84 mi_col=104 ... n=2 near_match=1 ref_match=1 prows=6 pcols=0 + [0 w=648 mv=(-520,0)] [1 w=664 mv=(-512,0)] +``` + +libaom's `-520` votes: `4` (row `-1`) + `4` (row `-3`) + `8` (row `-5`) = `16` +(`640 + 16 = 656`); `-512`'s: `4` (top-right `(83,108)`) + `4` (corner +`(83,103)`) = `8` (`648`). Ours lost `-520`'s `8` (the row `-5` contribution) +and gained `-512` `+16` from the over-reach, so the weight sort flipped: +`nearestmv` became `-512` where libaom's is `-520`, and +`dv = ref + diff = -512 + 8 = -504` instead of `-520 + 8 = -512`. One whole-pel +wrong `skip == 1` copy; the 528 wrong luma samples are that copy plus the +region that inherits its 1-px shift. + +### Fix + +`MiGrid` gained a block-COVERAGE map (`cover: Vec<[u8; 2]>`, the covering +coded block's own `(width, height)` in mi units) with `MiGrid::cover_rect`; +`MiGrid::get` returns the stored `MiInfo` when there is one and otherwise +synthesizes a non-inter entry (`is_inter == false`, zero MV) from the cover, so +a candidate that casts no vote still advances the scan by its real width -- +exactly libaom's `xd->mi[]` semantics. `single_ref_match` rejects a non-inter +unit, so a synthetic entry can never vote. + +The map is published for EVERY coded block from `Neighbours::fill_lf_grid_rect` +(the one place every block's mi span already passes through, paired 1:1 with +`fill_skip_grid_rect`), and only when the frame has an MV grid at all +(`intrabc_mi_grid` is `Some` exactly when `allow_intrabc`), so an inter frame +and the tile writer's own grid are untouched: an unfilled cover reads as +uncovered and reproduces the old `None`-per-cell behaviour exactly. + +### Byte-exactness after the fix + +| stream | before | now | +|---|---|---| +| B 512x384 testsrc2 cq45 `--enable-palette=1 --enable-tx-size-search=0` | 528/294912 luma | **BYTE-EXACT** (`cmp` vs ffmpeg `-pix_fmt yuv420p`) | +| A 256x192 testsrc2 cq45 var-tx (`--enable-tx-size-search=1`) | BYTE-EXACT | **BYTE-EXACT** | + +Standalone arms re-run (all `cmp`-exact against ffmpeg): `cq50p0-txs0`, +`cq45p0-txs0`, `cq45p1-txs0`, `cq50p0-txs0`, `cq50p0-1to4-off`, `minp4` +(`--min-partition-size=4 --max-partition-size=16`), `cq50-txs1-1to4-off`. The +`(84,104)` DV trace now reads `dv_row=-512 rng=33207`, the oracle's own value. + +### New reviewer-unblock gate + +`stream::tests::a_coded_rect_intrabc_block_reconstructs_in_both_orientations` +-- three arms, ALL frames byte-exact against ffmpeg, each asserting the arm +reconstructed a CODED (`skip == 0`) rect intrabc block in the orientation it +names: + +- `horz-coded-256-cq45-pal0-txs0` -- 16x8 coded strip, HORZ. +- `vert-coded-512-cq45-pal1-txs0` -- 8x16 coded strip, VERT, **and the + DV-predictor regression stream** (this is stream B). +- `txmode-select-256-cq45-pal0-txs1` -- stream A's shape; the arm re-derives + `tx_mode == Select && allow_intrabc` out of the frame header rather than + trusting the encoder flags. + +New instrument `decode::intrabc_rect_coded_hits() -> [horz, vert]` (bumped in +`decode_intrabc_rect` when `!skip`, indexed by `bh > bw`): the old +`intrabc_rect_hits` counts neither the skip flag nor the orientation, so an arm +that quietly became all-skip or single-orientation would keep it green +(`gate-blind-to-feature`). + +**Non-vacuity (fail-pre-fix, measured):** with only the `MiGrid::get` cover +fallback neutralized (the fix's load-bearing line) and nothing else touched, +the gate fails exactly where it must -- + +``` +horz-coded-256-cq45-pal0-txs0 ... exact, coded rect intrabc horz=1 vert=0 +vert-coded-512-cq45-pal1-txs0 frame 0 does not match ffmpeg +test ... FAILED +``` + +and passes again with the line restored. + +### Gates run this round + +- `cargo check -p ec-av1 --all-targets` -> 0 warnings. +- New gate (3 arms, 3 frames, byte-exact; fail-pre-fix proven above). +- `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips` -> ok + (187 rect reads, 5 intrabc blocks over 5 arms, 8 frames compared, 0 + refused, 0 mismatched, 1 rect-strip block). +- `an_intrabc_block_under_tx_mode_select_decodes_pixel_exact` -> ok + (cq30 16 blocks / 1 var-tx, cq45 12 blocks / 3 var-tx). +- Refusal suite `-- refusal` -> **21 passed**. `reelb` -> 3 passed. + `monochrome` -> 1 passed. `cdf` -> 13 passed. `non_420` -> 1 passed. +- Full `--lib` suite, re-measured 2026-09-23 on commit `db15bb5a` (see below): + `test result: ok. 599 passed; 0 failed; 60 ignored; 0 measured; 0 filtered out; finished in 10087.77s` + +### Deferred / open + +- 1:4 pair-strip intrabc -- unchanged, named in §3. +- The cover records the mi span its `fill_lf_grid_rect` caller passes; a + sub-8x8 leaf publishes a 4x4 (1x1 mi) or an 8x8-square span exactly as its + own `fill_skip_grid`/`fill_lf_grid` call already does, so the coverage map + inherits that convention. No gate or arm reaches a sub-8x8 neighbour of an + intrabc block today; if one ever does, the leaf's true `bsize` dims are what + libaom's `mi_size_wide/height[candidate->bsize]` would report. + + +### Verified 2026-09-23 (r4 commit `db15bb5a` was UNVERIFIED) + +Re-measured on that committed tree. Probe rebuilt from it +(`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1ibc`). 8-bit comparison is +`decode_probe ` vs `ffmpeg -pix_fmt yuv420p -f rawvideo`. `git +status --porcelain` was empty before the suite and empty after it: the suite +ran these bytes. + +| stream | verdict | +|---|---| +| A 256x192 testsrc2 cq45 `--enable-palette=0 --enable-tx-size-search=1` | **BYTE-EXACT** (73728 B) | +| B 512x384 testsrc2 cq45 `--enable-palette=1 --enable-tx-size-search=0` | **BYTE-EXACT** (294912 B; was 528/294912 luma) | + +Previously-green arms, all `cmp`-exact: `cq50p0-txs0`, `cq45p0-txs0`, +`cq45p1-txs0`, `minp4` (`--min-partition-size=4 --max-partition-size=16`), +`smptebars` cq40 and cq45. + +Unblock gate +`a_coded_rect_intrabc_block_reconstructs_in_both_orientations` (with the +in-gate and the tx-mode-select witness, one `cargo test` invocation): + +``` +horz-coded-256-cq45-pal0-txs0 1 frame(s) exact, coded rect intrabc horz=1 vert=0 +vert-coded-512-cq45-pal1-txs0 1 frame(s) exact, coded rect intrabc horz=0 vert=1 +txmode-select-256-cq45-pal0-txs1 1 frame(s) exact, coded rect intrabc horz=1 vert=0 +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 656 filtered out; finished in 3.45s +``` + +In-gate `a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips`: 187 +rect-strip `use_intrabc` reads, 5 intrabc blocks over 5 arms, 8 frames +compared, 0 refused, 0 mismatched, 1 rect-strip block. +`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`: cq=30 16 blocks / +1 var-tx, cq=45 12 blocks / 3 var-tx. + +Regression filters (same tree, `--nocapture --test-threads=1`): + +- `-- refusal` -> **21 passed** (111.09s). +- `monochrome` -> 1 passed: 4:2:0 twin 60 frames, monochrome 60 frames + byte-exact vs ffmpeg. +- `non_420` -> 1 passed. +- `quantisation` -> 1 passed: qm-off control 3 frames, qm-on refused by name + (`a frame using quantisation matrices`). +- `cdf_update` -> 1 passed: 3 `disable_cdf_update` frame headers, all frames + sample-exact. +- `reelb` -> 3 passed. +- `a_10bit_film` -> 5 passed (126.80s), including + `reelb_rect64` 33 frames, `reelb_arf` 37 frames, `reelb_head_mvclamp` 52 frames. + +Wave-1 probes (release `decode_probe`, not the debug suite): + +- gray 60-frame key frame (`testsrc2` 320x240 2s `-pix_fmt gray -c:v + libaom-av1`): `OK: 60 frames`, low byte of `EC_PROBE_OUT16` EQUAL to + `ffmpeg -pix_fmt gray` (4,608,000 B). +- `fixtures/bitstreams/av1-monochrome.ivf` remuxed to OBU: `OK: 60 frames`, + EQUAL the same way. +- `av1-profile1-444.ivf` remuxed to OBU: REFUSED by name (`a chroma format + other than 4:2:0`). +- every `crates/ec-av1/fixtures/reelb_*.obu` (8 files) EQUAL to + `ffmpeg -pix_fmt yuv420p10le` (`EC_PROBE_OUT16`). + +`cargo check -p ec-av1 --all-targets` after `touch` of `lib.rs`: 0 warnings +(`Finished dev profile in 1.15s`, `CHECK_RC=0`, no `warning:` lines). + +Full suite, hub process `av1ibc-suite`, `cargo test -p ec-av1 --lib -- +--test-threads=1`, `EC_AV1_REQUIRE_AOMENC=1`, `TMPDIR` on `$HOME`. Literal +line: + +``` +test result: ok. 599 passed; 0 failed; 60 ignored; 0 measured; 0 filtered out; finished in 10087.77s +``` + +599 = 598 (this branch's base, the txrouting merge at `3ecd4a10`, before +txbands) + this lane's one new gate. Main's `600/0/60` includes txbands' two +gates, which are not on this branch. Not a missing test. Hub log grep for +`FAILED` was empty. Exit 0. + +The first suite attempt (default threads) did not finish. After 3h20m it was +deadlocked in `run_8x8_leaf_motion_gate` +(`a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact`): `write_all` of +the y4m runs before `wait_with_output`, and that aomenc's stdout pipe had been +shrunk to 8192 bytes (a fresh pipe on this box is 65536). Both sides sat in +`anon_pipe_write`. Pre-existing spawn pattern, not this lane's diff. Stopped +(exit 143) and re-run single-threaded; that run is the line above. +`deferred(concurrent stdin/stdout drain for aomenc spawns that write_all +before wait_with_output -- unblocked by a charter that may edit the spawn +helper)`. + +## 4e. Round 5 (2026-09-23) -- the skip arm's residual slice was sized `bw * bh`, not `side * side` + +### Root cause (the reviewer's one P1) + +`decode_intrabc_rect`'s skip arm (pre-fix `decode.rs:11047-11049`) passed +`push_mc_rect(..., stride = side = bw.max(bh), w = bw, h = bh, ..., +&ZERO_RESIDUAL[..bw * bh])` (chroma: `cw * ch`). `PlaneBuf::reconstruct_mc_rect` +(`decode.rs:25726-25731`) indexes `residual[row * side .. row*side + w]` for +`row in 0..h`, needing up to `(bh-1)*side + bw` elements. For a VERT strip +(`bh > bw`) that EXCEEDS the slice: a skipped 8x32 strip reads a 256-element +slice at stride 32 and panics at row 8 -- `range end index 264 out of range +for slice of length 256`. The panic is a bounds check, never silent +corruption; a HORZ strip (`bw > bh`) never overruns (`(bh-1)*side + bw <= +bw*bh` when `bw == side`). + +### Why every gate missed it + +Two stacked blind spots. (1) Only the default single-threaded path crashes: +at `EC_AV1_RECON_THREADS == 1` the rect is reconstructed inline through +`ReconPlanes` (the `dense_residual` read above); on the wavefront path the +`Residual::done` ZERO_RESIDUAL pointer-compare maps the slice to the empty +marker and never indexes it. (2) Every existing VERT intrabc witness was +CODED (`skip == 0`), so no gate ever walked the skip arm on a VERT strip +(`gate-blind-to-feature`: the counters counted neither the skip flag nor the +orientation for skipped blocks). + +### Fix (bug-for-bug with the proven inter path) + +Three lines, `decode.rs` skip arm: `&ZERO_RESIDUAL[..side * side]` and +`&ZERO_RESIDUAL[..cside * cside]` (x2), exactly what the inter skip arm at +`decode.rs:28906-28916` passes. `(h-1)*side + w <= side*side` for every rect +shape. + +### Repro (before) / verdict (after) + +Reviewer's corpus at `~/.cache/tmp-av1ibcreview/repro`. Pre-fix, stock +release `decode_probe sweep_testsrc2_cq30_p0.obu` panics with the exact +message above (`decode.rs:25731:32`); post-fix it decodes clean, rc=0. The +new gate arm was also proven fail-pre-fix: with only the three fix lines +reverted, `a_coded_rect_intrabc_block_reconstructs_in_both_orientations` +panics at the same index (`264 out of range for slice of length 256`, +`decode.rs:25755:32` after the counter edit shifted lines). + +### New gate arm (non-vacuous) + +`stream::tests::a_coded_rect_intrabc_block_reconstructs_in_both_orientations` +gains two SKIPPED-strip arms, `vert-skip-512-cq30-pal0-txs0` and +`vert-skip-512-cq30-pal1-txs0` (testsrc2 512x384, `--cq-level=30`, palette +off AND on, txs off -- the reviewer's panic recipe family). Each arm decodes +the stream at 1 AND 4 recon threads and asserts byte-exact vs ffmpeg on +BOTH paths, and a new counter `decode::intrabc_rect_skipped_hits()` (bump in +`decode_intrabc_rect`, `[horz, vert]` split, reset with the coded one) +HARD-asserts a SKIPPED VERT 2:1 strip was actually reconstructed -- an arm +that stops producing one fails instead of passing vacuously. Measured this +round: + +``` +vert-skip-512-cq30-pal0-txs0 1 frame(s) exact at 1 recon thread(s), skipped rect intrabc horz=11 vert=2 +vert-skip-512-cq30-pal0-txs0 1 frame(s) exact at 4 recon thread(s), skipped rect intrabc horz=11 vert=2 +vert-skip-512-cq30-pal1-txs0 1 frame(s) exact at 1 recon thread(s), skipped rect intrabc horz=1 vert=2 +vert-skip-512-cq30-pal1-txs0 1 frame(s) exact at 4 recon thread(s), skipped rect intrabc horz=1 vert=2 +``` + +### Corpus sweep (post-fix, release `decode_probe` on the committed tree) + +All 39 obus in `~/.cache/tmp-av1ibcreview/repro` decode without panic +(rc=0, no `panicked` in output). Byte-exactness where the reviewer compared: + +| group | result | +|---|---| +| sweep_* 16 streams with a non-zero ffmpeg ref | all 16 `cmp`-EXACT (294912 B each) | +| sweep_* 14 streams whose ref is 0 B (the reviewer's panicking cells) | all decode clean now, no ref to compare | +| A.obu / B.obu / C_gradients / C_mandelbrot / C_smptebars | all `cmp`-EXACT vs `*_ref.raw` | +| D.obu | probe dispatches 0 frames (unchanged: reviewer's own `D_ours.raw`/`D_ours2.raw` are 0 B too) | +| gray60.obu, av1-monochrome.obu | `cmp`-EXACT vs `gray_ref.raw` / `mono_ref.raw` | +| reelb_* 10-bit (8 fixtures, `EC_PROBE_OUT16`) | all 8 `cmp`-EXACT vs `ref_reelb_*.raw` | +| av1-profile1-444.obu | still REFUSED by name (`a chroma format other than 4:2:0`) | + +### Full suite + +`test result: ok. 599 passed; 0 failed; 60 ignored; 0 measured; 0 filtered out; finished in 9555.99s` — hub-supervised `--test-threads=1` on the committed tree (`86ba99f6`), exit 0.