From b59491989442e517ac86b246883c726433fda61e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 04:56:05 +0300 Subject: [PATCH] feat(av1): rectangular inter residual coding for 32x16/16x32 strips (gate red, refusal kept for every other shape) The r1 ceiling was that no rectangular inter block could carry a residual: decode_inter_block refused every non-skip HORZ/VERT/HORZ_B strip. This ports the path for the 2:1 shapes whose coefficient tables already exist: - read_block_tx_size_rect: spec 5.11.17 from the block's own rect max_txsize_rect_lookup entry. TX_MODE_LARGEST -> one rect TU, no symbol; TX_MODE_SELECT -> one depth-0 txfm_partition symbol (new txfm_partition_ctx_rect: above vs tx_size_wide, left vs tx_size_high, category from txsize_sqr_up_map), and a split resolves to sub_tx_size_map's SQUARE sub-transforms, from which the existing square read_var_tx_size continues at depth 1. - txfm_partition_update_rect, and the skipped-inter case now records the block's own width above / height left (set_txfm_ctxs(.., skip && is_inter)). - read_inter_plane_rect: read_coeffs_rect + dequant_and_inverse_typed_wh onto the top-left w x h of the square-strided MC predictor; luma txb_skip_ctx 0 (plane_bsize == txsize_to_bsize[tx_size]); chroma at av1_get_max_uv_txsize (16x8/8x16) inheriting the luma tx_type. - TxbSet::LumaRect32x16Inter: LumaRect32x16's coefficient tables plus default_inter_ext_tx_cdf[3][TX_16X16] (EXT_TX_SET_DCT_IDTX, what av1_get_ext_tx_set_type returns for an inter TU with sqr_up == TX_32X32). - two r1 out-of-bounds fixes surfaced by the new content: a rect strip's around_mi read `side` cells left and indexed past the tile's last mi row; the rect mode/side stamps ran past the frame's last 16-px column. The refusal string is unchanged and still fires for every shape but 32x16 and 16x32, so refusal_inventory is untouched. The new gate is RED and #[ignore]d with its exact reason: on real motion content the decode stops at the 16x8/8x16 inter leaf or intra-rect-strip refusal before any 32-level 2:1 strip, so this capability is implemented but NOT proven -- see lanes/inter4-r2.report.md. --- crates/ec-av1/src/cdf_state.rs | 22 ++ crates/ec-av1/src/decode.rs | 518 ++++++++++++++++++++++++++++++--- crates/ec-av1/src/stream.rs | 198 +++++++++++++ lanes/COMMON-20260901.md | 11 + lanes/inter4-r2.report.md | 113 +++++++ 5 files changed, 827 insertions(+), 35 deletions(-) create mode 100644 lanes/inter4-r2.report.md diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 822c31d1..c2c3efff 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -119,6 +119,16 @@ pub(crate) enum TxbSet { /// [`LumaRect32x16`](TxbSet::LumaRect32x16) has none). LumaRect32x8, LumaRect32x16, + /// lane-inter4 r2: [`LumaRect32x16`](TxbSet::LumaRect32x16)'s INTER twin -- + /// same coefficient tables (`get_txsize_entropy_ctx` reduces TX_32X16 and + /// TX_16X32 alike to the 32x32 set, 512-coefficient `eob_pt`), but an + /// inter block DOES code a `tx_type` symbol here: `av1_get_ext_tx_set_type` + /// with `tx_size_sqr_up == TX_32X32` and `is_inter` returns + /// `EXT_TX_SET_DCT_IDTX` (2 symbols), whose CDF is + /// `default_inter_ext_tx_cdf[3][txsize_sqr_map[TX_32X16] == TX_16X16]`, + /// i.e. exactly [`INTER_TX_TYPE_SET3_16`](crate::cdf::INTER_TX_TYPE_SET3_16) + /// -- the same table the square `Luma16Inter` set reads. + LumaRect32x16Inter, /// The chroma 16x8/8x16 transform under the same strip (lane-rectwire): /// [`Chroma16`](TxbSet::Chroma16)'s tables except `eob_pt`, which reads /// the true 128-position [`crate::cdf::EOB_PT_128_CHROMA`] instead of @@ -1663,6 +1673,18 @@ impl Cdfs { tx_type: None, eob_pt_class1: Some(&mut self.eob_pt_256_luma_class1), }, + TxbSet::LumaRect32x16Inter => TxbTables { + side: 32, + txb_skip: &mut self.txb_skip_luma_32, + eob_pt: &mut self.eob_pt_512_luma, + eob_extra: &mut self.eob_extra_luma_32, + base: &mut self.base_luma_32, + base_eob: &mut self.base_eob_luma_32, + br: &mut self.br_luma_32, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_16.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_512_luma_class1), + }, TxbSet::LumaRect32x16 => TxbTables { side: 32, txb_skip: &mut self.txb_skip_luma_32, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index aed50595..a6025eb8 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -769,6 +769,11 @@ pub(crate) fn tx_depth_hits() -> usize { thread_local! { static TXFM_SPLIT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; static TXFM_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + // lane-inter4 r2: rectangular INTER residual coding -- how many rect + // strips coded one whole-block rect transform unit, and how many split + // their rect max transform into square sub-transforms. + static RECT_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT_INTER_TXSPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits, // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] -- // `decode_inter_block` already carries forty parameters and both are @@ -787,6 +792,16 @@ pub(crate) fn txfm_split_hits() -> usize { TXFM_SPLIT_HITS.with(|c| c.get()) } +/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2). +pub(crate) fn rect_inter_tu_hits() -> usize { + RECT_INTER_TU_HITS.with(|c| c.get()) +} + +/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2). +pub(crate) fn rect_inter_txsplit_hits() -> usize { + RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) +} + /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]. pub(crate) fn set_inter_tx_mode(tx_select: bool, reduced_tx_set: bool) { TX_SELECT_INTER.with(|c| c.set(tx_select)); @@ -3874,12 +3889,21 @@ impl Neighbours { grids: &[Vec; 3], ) { let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI)); + // lane-inter4 r2: a strip whose own footprint runs past the frame's + // last 16-px column/row stamps only the cells that exist (libaom's + // arrays are padded past the frame and those cells are never read). for cell in 0..w / SUB { + if c + cell >= self.above_mode.len() { + break; + } self.above_mode[c + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h / SUB { + if r + cell >= self.left_mode.len() { + break; + } self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; @@ -3910,10 +3934,14 @@ impl Neighbours { let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); let (w_mi, h_mi) = (w / MI, h / MI); for cell in 0..h_mi { - self.left_side_mi[mi_r + cell] = h; + if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) { + *slot = h; + } } for cell in 0..w_mi { - self.above_side_mi[mi_c + cell] = w; + if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) { + *slot = w; + } } // A chroma 4x4 unit straddling the true luma edge is still whole in // chroma's own halved grid, so libaom rounds the luma bound up to the @@ -4018,11 +4046,17 @@ impl Neighbours { ) { let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI)); for cell in 0..w / SUB { + if c + cell >= self.above_mode.len() { + break; + } self.above_mode[c + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h / SUB { + if r + cell >= self.left_mode.len() { + break; + } self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; @@ -4032,10 +4066,14 @@ impl Neighbours { self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode); self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode); for cell in 0..h_mi { - self.left_side_mi[mi_r + cell] = h; + if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) { + *slot = h; + } } for cell in 0..w_mi { - self.above_side_mi[mi_c + cell] = w; + if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) { + *slot = w; + } } let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); @@ -8705,8 +8743,25 @@ fn read_tx_size( /// the two neighbour terms (whether the transform last written above/left of /// this unit is narrower/shorter than the unit itself). fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize { - let above = usize::from(usize::from(above_px) < tx_px); - let left = usize::from(usize::from(left_px) < tx_px); + txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px) +} + +/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2): +/// libaom's `txfm_partition_context` compares the above context against +/// `tx_size_wide` and the left one against `tx_size_high`, and takes its +/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one +/// side for a square transform, which is why the square form above is a +/// special case of this one. +fn txfm_partition_ctx_rect( + above_px: u8, + left_px: u8, + blk_max_px: usize, + tx_w: usize, + tx_h: usize, +) -> usize { + let above = usize::from(usize::from(above_px) < tx_w); + let left = usize::from(usize::from(left_px) < tx_h); + let tx_px = tx_w.max(tx_h); // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as // `log2(px) - 2`. @@ -8721,16 +8776,30 @@ fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize /// resolved transform's own size. fn txfm_partition_update( n: &mut Neighbours, - (mi_r, mi_c): (usize, usize), + at_mi: (usize, usize), tx_px: usize, txb_px: usize, ) { - for i in 0..txb_px / MI { + txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px)); +} + +/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2): +/// the left column records `tx_size_high` over the parent's own height and +/// the above row records `tx_size_wide` over its width. +fn txfm_partition_update_rect( + n: &mut Neighbours, + (mi_r, mi_c): (usize, usize), + (tx_w, tx_h): (usize, usize), + (txb_w, txb_h): (usize, usize), +) { + for i in 0..txb_h / MI { if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { - *cell = tx_px as u8; + *cell = tx_h as u8; } + } + for i in 0..txb_w / MI { if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { - *cell = tx_px as u8; + *cell = tx_w as u8; } } } @@ -8939,6 +9008,198 @@ fn read_block_tx_size( Ok((tx, None)) } +/// lane-inter4 r2: the shapes whose *rectangular inter* residual this +/// decoder codes -- a 2:1 strip whose own max rect transform +/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a +/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient +/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a +/// 64-point rect transform, and 16x8/8x16 needs +/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol +/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a +/// rect transform), neither of which exists yet -- both stay refused by name. +fn rect_inter_residual_supported(w: usize, h: usize) -> bool { + matches!((w, h), (32, 16) | (16, 32)) +} + +/// The default (2D) coefficient scan of a rectangular transform. +fn rect_scan(w: usize, h: usize) -> &'static [u16] { + match (w, h) { + (32, 16) => &SCAN_32X16, + (16, 32) => &SCAN_16X32, + (16, 8) => &SCAN_16X8, + (8, 16) => &SCAN_8X16, + (8, 4) => &SCAN_8X4, + (4, 8) => &SCAN_4X8, + _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), + } +} + +/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2): +/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own +/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The +/// depth-0 `txfm_partition` symbol reads its context off the rect transform's +/// own width/height; a `0` leaves one whole-block rect transform unit +/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE +/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the +/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so +/// every leaf of a split rect block is square and the existing square leaf +/// loop reconstructs it unchanged. +#[allow(clippy::too_many_arguments)] +fn read_block_tx_size_rect( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + n: &mut Neighbours, + at_mi: (usize, usize), + (bw, bh): (usize, usize), + (mi_cols, mi_rows): (usize, usize), + skip: bool, +) -> Result>> { + if skip { + // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records + // its own BLOCK size -- width above, height left -- not a transform. + txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh)); + return Ok(None); + } + // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and + // `rect_inter_residual_supported` has already excluded everything above 32. + let (tx_w, tx_h) = (bw, bh); + if !TX_SELECT_INTER.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. + txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); + RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1)); + return Ok(None); + } + let ctx = txfm_partition_ctx_rect( + n.above_txfm[at_mi.1], + n.left_txfm[at_mi.0], + bw.max(bh), + tx_w, + tx_h, + ); + let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; + TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1)); + if std::env::var_os("EC_TRACE_MODE_STEP").is_some() { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}", + at_mi.0, + at_mi.1, + u8::from(split) + ); + } + if !split { + txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); + RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1)); + return Ok(None); + } + TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1)); + let sub = tx_w.min(tx_h); + let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1)); + let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0)); + let mut leaves = Vec::new(); + for row in (0..bh / MI).step_by(sub / MI) { + for col in (0..bw / MI).step_by(sub / MI) { + read_var_tx_size( + dec, + cdfs, + n, + at_mi, + bw.max(bh), + (max_w_mi, max_h_mi), + sub, + 1, + row, + col, + &mut leaves, + ); + } + } + Ok(Some(leaves)) +} + +/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2): +/// the coefficients are read with the rect coefficient machinery +/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*` +/// types), inverted with the rect inverse transform +/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale), +/// and added onto the top-left `w x h` of the block's own square-strided +/// motion-compensated prediction buffer. Returns the *rect* coefficient grid +/// and the coded `tx_type`. +/// +/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e. +/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch. +#[allow(clippy::too_many_arguments)] +fn read_inter_plane_rect( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + set: TxbSet, + (w, h): (usize, usize), + stride: usize, + plane_idx: usize, + around: (bool, bool, i32), + tx_mode: usize, + plane: &mut PlaneBuf, + x: usize, + y: usize, + prediction: &[u16], + inherited_luma_tx_type: Option, +) -> Result<(Vec, TxType)> { + let skip_ctx = if plane_idx == 0 { + 0 + } else { + usize::from(around.0) + usize::from(around.1) + }; + let mut coding = cdfs.txb(set, tx_mode); + // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e. + // the *longer* side of this rect transform. + let default_tx_type = match inherited_luma_tx_type { + Some(t) if w.max(h) < 32 => t, + _ => TxType::DctDct, + }; + let (grid, tx_type) = read_coeffs_rect( + dec, + &mut coding, + rect_scan(w, h), + w, + h, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + )?; + let (dc_delta, ac_delta) = plane_q_delta(plane_idx); + let residual = dequant_and_inverse_typed_wh( + &grid, + w, + h, + bit_depth(), + block_q_idx(), + dc_delta, + ac_delta, + tx_type, + ); + // `reconstruct_mc_rect` reads both buffers at the square prediction + // stride, so the dense `w x h` residual is re-laid at that stride first. + let mut strided = vec![0i32; stride * stride]; + for row in 0..h { + strided[row * stride..][..w].copy_from_slice(&residual[row * w..][..w]); + } + plane.reconstruct_mc_rect(x, y, stride, w, h, prediction, &strided); + Ok((grid, tx_type)) +} + +/// 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 { + let mut full = vec![0i32; stride * stride]; + for row in 0..h { + full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]); + } + full +} + /// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8 /// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single /// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in @@ -13019,7 +13280,10 @@ fn decode_inter_block( // lane-warp r5: see `reject_residual` -- a square-block decode of a // HORZ_B strip is symbol-exact only for `skip` (no residual, no // motion_mode/warp symbol), so gate here before any further read. - if reject_residual && !skip { + if reject_residual && !skip && !rect_inter_residual_supported(write_w, write_h) { + if std::env::var_os("EC_AV1_RECT_DUMP").is_some() { + eprintln!("EC_RECT_REFUSE mi_row={rmi} mi_col={cmi} w={write_w} h={write_h} side={side}"); + } return Err(unsupported( "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", )); @@ -13823,17 +14087,32 @@ fn decode_inter_block( mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v); } - vartx_leaves = read_block_tx_size( - dec, - cdfs, - neighbours, - at_mi, - side, - (mi_cols as usize, mi_rows as usize), - true, - skip, - )? - .1; + // lane-inter4 r2: a rectangular strip's transform tree starts from + // its own rect `max_txsize_rect_lookup` entry, not a square one. + let rect_tu = (write_w, write_h) != (side, side); + vartx_leaves = if rect_tu { + read_block_tx_size_rect( + dec, + cdfs, + neighbours, + at_mi, + (write_w, write_h), + (mi_cols as usize, mi_rows as usize), + skip, + )? + } else { + read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1 + }; if skip { y.reconstruct_mc_rect( px, @@ -13866,7 +14145,14 @@ fn decode_inter_block( u_grid = vec![0i32; chroma_side * chroma_side]; v_grid = vec![0i32; chroma_side * chroma_side]; } else { - let around = neighbours.around_mi(at, side); + // lane-inter4 r2: a rect strip's coefficient context spans its + // OWN width above and height left -- reading `side` cells both + // ways indexes past the tile's last mi row for a bottom strip. + let around = if rect_tu { + neighbours.around_mi_rect(at_mi, write_w, write_h) + } else { + neighbours.around_mi(at, side) + }; let luma_tx_type; if let Some(leaves) = vartx_leaves.clone() { // spec 5.11.17's transform tree, leaf by leaf in the order @@ -13913,6 +14199,26 @@ fn decode_inter_block( // inherits the *first* (top-left) luma unit's coded type. luma_tx_type = first_tx_type; luma_grid = vec![0i32; side * side]; + } else if rect_tu { + // The whole-block rectangular transform unit + // (`txfm_partition` said 0 at depth 0). + let (grid, tx_type) = read_inter_plane_rect( + dec, + cdfs, + TxbSet::LumaRect32x16Inter, + (write_w, write_h), + side, + 0, + around[0], + mode_for_tx, + y, + px, + py, + &pred_y, + None, + )?; + luma_tx_type = tx_type; + luma_grid = embed_rect_grid(&grid, write_w, write_h, side); } else { (luma_grid, luma_tx_type) = read_inter_plane( dec, @@ -13932,6 +14238,55 @@ fn decode_inter_block( None, )?; } + if rect_tu { + // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a + // 2:1 strip is the strip's own rect chroma size (16x8 / + // 8x16), one unit for the whole block, and it codes no + // `tx_type` symbol -- it inherits the luma unit's. + let (uw, uh) = (write_chroma_w, write_chroma_h); + u_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + TxbSet::ChromaRect16x8, + (uw, uh), + chroma_side, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + &pred_u, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + v_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + TxbSet::ChromaRect16x8, + (uw, uh), + chroma_side, + 2, + around[2], + mode_for_tx, + v, + cpx, + cpy, + &pred_v, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + } else { u_grid = read_inter_plane( dec, cdfs, @@ -13968,6 +14323,7 @@ fn decode_inter_block( None, )? .0; + } } } else { let ref_frame = @@ -14663,17 +15019,32 @@ fn decode_inter_block( interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v); } - vartx_leaves = read_block_tx_size( - dec, - cdfs, - neighbours, - at_mi, - side, - (mi_cols as usize, mi_rows as usize), - true, - skip, - )? - .1; + // lane-inter4 r2: a rectangular strip's transform tree starts from + // its own rect `max_txsize_rect_lookup` entry, not a square one. + let rect_tu = (write_w, write_h) != (side, side); + vartx_leaves = if rect_tu { + read_block_tx_size_rect( + dec, + cdfs, + neighbours, + at_mi, + (write_w, write_h), + (mi_cols as usize, mi_rows as usize), + skip, + )? + } else { + read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1 + }; if skip { y.reconstruct_mc_rect( px, @@ -14706,7 +15077,14 @@ fn decode_inter_block( u_grid = vec![0i32; chroma_side * chroma_side]; v_grid = vec![0i32; chroma_side * chroma_side]; } else { - let around = neighbours.around_mi(at, side); + // lane-inter4 r2: a rect strip's coefficient context spans its + // OWN width above and height left -- reading `side` cells both + // ways indexes past the tile's last mi row for a bottom strip. + let around = if rect_tu { + neighbours.around_mi_rect(at_mi, write_w, write_h) + } else { + neighbours.around_mi(at, side) + }; let luma_tx_type; if let Some(leaves) = vartx_leaves.clone() { // spec 5.11.17's transform tree, leaf by leaf in the order @@ -14753,6 +15131,26 @@ fn decode_inter_block( // inherits the *first* (top-left) luma unit's coded type. luma_tx_type = first_tx_type; luma_grid = vec![0i32; side * side]; + } else if rect_tu { + // The whole-block rectangular transform unit + // (`txfm_partition` said 0 at depth 0). + let (grid, tx_type) = read_inter_plane_rect( + dec, + cdfs, + TxbSet::LumaRect32x16Inter, + (write_w, write_h), + side, + 0, + around[0], + mode_for_tx, + y, + px, + py, + &pred_y, + None, + )?; + luma_tx_type = tx_type; + luma_grid = embed_rect_grid(&grid, write_w, write_h, side); } else { (luma_grid, luma_tx_type) = read_inter_plane( dec, @@ -14772,6 +15170,55 @@ fn decode_inter_block( None, )?; } + if rect_tu { + // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a + // 2:1 strip is the strip's own rect chroma size (16x8 / + // 8x16), one unit for the whole block, and it codes no + // `tx_type` symbol -- it inherits the luma unit's. + let (uw, uh) = (write_chroma_w, write_chroma_h); + u_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + TxbSet::ChromaRect16x8, + (uw, uh), + chroma_side, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + &pred_u, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + v_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + TxbSet::ChromaRect16x8, + (uw, uh), + chroma_side, + 2, + around[2], + mode_for_tx, + v, + cpx, + cpy, + &pred_v, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + } else { u_grid = read_inter_plane( dec, cdfs, @@ -14808,6 +15255,7 @@ fn decode_inter_block( None, )? .0; + } } } } else { diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 0b066a6d..2ea18d78 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -4717,6 +4717,204 @@ mod tests { } } + /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT` + /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1 + /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs + /// rectangular residual coding"). The strip's own rectangular max + /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree, + /// its coefficients through [`TxbSet::LumaRect32x16Inter`] / + /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse + /// transform. + /// + /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock + /// level (64x32, still refused -- no 64-point rect transform) out, so + /// every counted hit is a 32-level strip. The source is textured and + /// translating precisely so the strips are NOT skip: a flat source (r1's) + /// makes aomenc code them skip and proves nothing about the residual. + /// Both `--enable-tx-size-search` arms run: `=0` exercises the + /// whole-block rect transform with no `txfm_partition` symbol at all, + /// `=1` the rect var-tx tree (no-split rect unit, or the split into square + /// sub-transforms). + /// + /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and + /// V; a refusal is counted, never SKIPped; an attempt that carried no rect + /// inter residual is counted separately and still required pixel-exact. + #[test] + // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter + // residual path IS implemented and reached, but no aomenc recipe swept + // this round produced a stream whose FIRST rect inter block is a 32x16 / + // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or + // an intra rect strip) earlier in the tile, and both of those still refuse + // by name, so the decode stops before any 32-level 2:1 strip. The 16x8 + // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the + // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect + // transform), which this round did not add. See lanes/inter4-r2.report.md. + #[ignore = "lane-inter4 r2: every real-content attempt stops at the 16x8/8x16 inter leaf or intra-rect-strip refusal before reaching a 32x16/16x32 strip; the rect residual path itself is unproven, not claimed"] + fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = + (0u32, 0u32, 0u32, 0u32); + let (mut tu_proved, mut split_proved) = (0usize, 0usize); + for attempt in 0..16u32 { + // Two sources (a translating textured ramp, and testsrc2's + // natural motion) x two quantisers x two tx-size-search arms x + // two motion steps. + let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; + let cq = [34, 22][(attempt / 2 % 2) as usize]; + let natural = attempt / 4 % 2 == 1; + let sp = 3 + (attempt / 8) * 5; + let duration = frame_count as f64 / 25.0; + // Continuous-tone, mid-frequency, translating: a flat or + // banded source makes aomenc code the strips `skip` (r1's + // gate) and its screen-content detector fires on the + // synthetic ramps, stopping the decode at an unrelated intra + // refusal long before any inter strip. + // Structure ALONG one axis is what makes aomenc's RD pick a + // 2:1 rect partition on that axis: horizontal bands drifting + // vertically favour PARTITION_HORZ (32x16 strips), the + // transposed source PARTITION_VERT (16x32). + let lum = if natural { + format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)") + } else { + format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)") + }; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='{lum}',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let cq_arg = format!("--cq-level={cq}"); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let tx_arg = format!("--enable-tx-size-search={tx_search}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--lag-in-frames=0", + // Per-arm overrides go LAST: aomenc keeps the last + // occurrence of a repeated --enable-* flag. + &tx_arg, + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=32", + "--obu", "-o", "-", "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits()); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits()); + let (tu, split) = (after.0 - before.0, after.1 - before.1); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if tu + split == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + coded rect inter transform units -- another shape's defect" + ); + } + continue; + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + } + tu_proved += tu; + split_proved += split; + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \ + rect trees that split={split_proved}, {out_of_scope} attempts carried none \ + ({oos_mismatch} of them mismatched)" + ); + assert_eq!( + oos_mismatch, 0, + "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \ + mismatched ffmpeg -- a defect of another shape, not a pass" + ); + assert!( + tu_proved > 0, + "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \ + residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \ + {out_of_scope} out of scope) -- gate proved nothing" + ); + } + } + #[test] fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() { if !have_ffmpeg() { diff --git a/lanes/COMMON-20260901.md b/lanes/COMMON-20260901.md index 6da7ff3d..07c3a305 100644 --- a/lanes/COMMON-20260901.md +++ b/lanes/COMMON-20260901.md @@ -89,3 +89,14 @@ NEVER wait with a foreground `until/while ... sleep` loop or `tail --pid`. ## NEVER pkill BY BINARY NAME (2026-09-02: one lane's `pkill -f ec_av1-` killed another lane's suite) The test binary hash is identical across worktrees. Kill only by PID you own (`$!`, or the systemd unit name you started). `pkill -f`/`killall` on cargo/ec_av1 patterns is forbidden. + +## NEVER `cargo fmt` IN A LANE (3 lanes lost their diffs to it on 2026-09-02) +main is not rustfmt-clean (~6000 lines of churn). Hand-indent; `cargo test --no-run` is the check. +If you ran it: extract your own hunks, `git checkout -- crates/`, re-apply. + +## MEMORY (user order 2026-09-02: an unsteady box fails the job) +30 GB box shared by ~10 agents. Every decode/encode/probe invocation runs under +`systemd-run --user --scope -q -p MemoryMax=6G `; suites under a unit with `-p MemoryMax=10G`; +never two suites per lane; film extracts ≤2 s; a watchdog (`ec-memwatch` user unit, log +`$HOME/.cache/ec-memwatch.log`) SIGKILLs any codec/test process above 6 GiB RSS or the largest one +when MemAvailable < 3 GiB — a killed run means YOUR command exceeded the budget: bound it, do not retry as-is. diff --git a/lanes/inter4-r2.report.md b/lanes/inter4-r2.report.md new file mode 100644 index 00000000..c38218b3 --- /dev/null +++ b/lanes/inter4-r2.report.md @@ -0,0 +1,113 @@ +# lane-inter4 r2 — rectangular INTER residual coding + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off r1's `59ccb01` (main `146896f`). No rebase this round (main unchanged since). + +## Owed from r1: the full suite at 59ccb01 + + $HOME/.cache/inter4-suite-r2a.log + test result: ok. 323 passed; 0 failed; 30 ignored; finished in 458.10s + +r1's two self-failures were indeed fixed by `59ccb01`. + +EVIDENCE: $HOME/.cache/inter4-suite-r2a.log | ec-av1 --lib under systemd-run at 59ccb01 | 323 passed / 0 failed / 30 ignored + +## What this round built (capability present, NOT claimed proven) + +Rectangular inter residual coding for the 2:1 shapes whose tables exist — +32x16 / 16x32 (`crates/ec-av1/src/decode.rs`): + +- `rect_inter_residual_supported` (decode.rs) — the shape gate. The r1 refusal + string ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular + residual coding") is now conditional on it, so `refusal_inventory` is + unchanged and 64x32/64x16/32x8/8x32/16x8 keep refusing by name. +- `read_block_tx_size_rect` — spec 5.11.17 from the block's own *rect* + `max_txsize_rect_lookup` entry. `TX_MODE_LARGEST`: no symbol, one rect TU. + `TX_MODE_SELECT`: one depth-0 `txfm_partition` symbol whose context comes + from the new `txfm_partition_ctx_rect` (above compares `tx_size_wide`, left + `tx_size_high`, category from `txsize_sqr_up_map`); `0` leaves one rect TU, + `1` splits into `sub_tx_size_map`'s two SQUARE sub-transforms from which the + existing square `read_var_tx_size` continues at depth 1 — so every leaf of a + split rect block is square and the existing square leaf loop reconstructs it. +- `txfm_partition_update_rect` / the skipped-inter case — a skipped rect inter + block records its own BLOCK width above and height left (libaom + `set_txfm_ctxs(.., skip && is_inter)`), where r1 recorded a square `side` + both ways. +- `read_inter_plane_rect` + `embed_rect_grid` — rect coefficients via + `read_coeffs_rect` (TxClass-aware scans/contexts), rect inverse via + `dequant_and_inverse_typed_wh`, added onto the top-left `w x h` of the + square-strided MC predictor. `txb_skip_ctx` 0 for luma (this unit IS the + block: `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch); + chroma at `av1_get_max_uv_txsize` (16x8 / 8x16, `TxbSet::ChromaRect16x8`), + inheriting the luma unit's `tx_type`. +- `cdf_state.rs`: new `TxbSet::LumaRect32x16Inter` — `LumaRect32x16`'s + coefficient tables (512-coefficient `eob_pt`) plus the inter `tx_type` + alphabet `default_inter_ext_tx_cdf[3][TX_16X16]` (`EXT_TX_SET_DCT_IDTX`, + which is what `av1_get_ext_tx_set_type` returns for an inter TU with + `tx_size_sqr_up == TX_32X32`) — i.e. the existing `INTER_TX_TYPE_SET3_16`. +- Two out-of-bounds fixes found by the new content (both in r1 code, both hit + before any of this round's residual code runs): `around_mi(at, side)` read + `side` cells left for a rect strip and indexed past the tile's last mi row + (now `around_mi_rect(at_mi, write_w, write_h)` for a rect strip); and + `record_rect_mi`/`record_split_luma_rect_mi` stamped past the frame's last + 16-px column for an edge strip (now bounds-checked). +- `EC_AV1_RECT_DUMP=1` prints the shape of every refused rect strip. +- New counters `rect_inter_tu_hits` / `rect_inter_txsplit_hits` + accessors. + +## Gate — RED, kept and `#[ignore]`d with its exact reason + +`a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact` +(stream.rs): 16 attempts x {2 axis-structured sources, 2 quantisers, 2 +`--enable-tx-size-search` arms, 2 motion steps} x {8-bit, 10-bit}, 192x128, +6 frames, `--enable-rect-partitions=1 --enable-ab-partitions=0 +--enable-1to4-partitions=0 --min-partition-size=16 --max-partition-size=32`, +overrides last; every decoded frame compared Y/U/V to ffmpeg, refusals counted +never SKIPped, out-of-scope attempts still required pixel-exact. + +It never fires, and the reason is NOT the residual code: on real motion content +the decode stops earlier, every attempt, at one of + + an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet) + an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet + an inter partition below 8x8 ... + +so no stream ever reached a 32x16/16x32 inter strip. Content sweep this round +(4 source families x cq 22..61): flat/banded sources make the strips `skip` +(r1's case) or trip aomenc's screen-content detector into an intra-strip +refusal; textured/natural ones reach 16-level rect leaves first. `EC_AV1_RECT_DUMP` +on the earlier recipe showed the only rect shapes actually refused were 32x8 / +8x32 (the 32-level 1:4 arms), never 32x16. + +EVIDENCE: `cargo test -p ec-av1 --lib coded_rectangular_residual -- --nocapture` | 16 aomenc encodes x 8-bit, decode + ffmpeg Y/U/V compare | 15 named refusals, 0 attempts carrying a rect inter residual, whole-block rect TUs=0 -- gate proved nothing, so it is `#[ignore]`d with that sentence, not weakened + +EVIDENCE: `cargo test -p ec-av1 --lib superblock_level_rect_partition -- --nocapture` | r1's skip-strip gate re-run on this round's tree | 4 named refusals, 2 pixel-exact attempts carrying the arm, 64x32 strips=4, 0 mismatches -- the rect skip-context change did not regress it + +## Suite + + $HOME/.cache/inter4-suite-r2.log (systemd-run, unit inter4-suite-r2) + +## Residue + +- **fix-now (r3): 16x8/8x16 inter rect leaves.** They are the real reach + blocker: real content codes one before any 32-level 2:1 strip. Needs (a) the + 16-level rect inter partition arm, (b) `default_inter_ext_tx_cdf[2][TX_8X8]` + (12-symbol `DTT9_IDTX_1DDCT` at `tx_size_sqr == TX_8X8`, reachable only + through a rect transform) as a new CDF + adaptation field, (c) a + `TxbSet::LumaRect16x8Inter`. The residual machinery this round added then + covers them unchanged. +- **deferred: the 32x16/16x32 gate** — unblocked by the item above (or by a + recipe that reaches a 32-level strip first; four source families did not). +- **deferred: 64x32/32x64/64x16/16x64 and 32x8/8x32 rect residual** — 64-point + and 1:4 rect transforms have no coefficient tables here; still refused by name. +- **deferred: film probe** — not re-run: r1 measured both ReelC extracts stopping + at lane-rectchroma's INTRA refusal ("a coded HORZ/VERT strip whose chroma + transform has no rect coefficient tables here"), which nothing in this diff + touches. +- **accepted: a rect block's luma/chroma coefficient grid is embedded in the + square grid** the downstream neighbour/deblock stamps expect (top-left + placement). The split-leaf path already hands those stamps an all-zero square + grid, so this is strictly more information than the shipping behaviour. +- **DO NOT MERGE as a capability claim**: rectangular inter residual coding is + implemented and compiles, and is exercised by no green gate (class + refusal-lifted-without-a-gate). The refusal itself is still in place for every + shape but 32x16/16x32.