diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index a0667b0b..3fa00cde 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -31,6 +31,13 @@ fn main() { let report = || { let (h, v, c) = ec_av1::stream::rect4_32_counters(); println!("rect4_32: horz={h} vert={v} coded={c}"); + let (rtu, rsplit, robmc) = ec_av1::stream::rect_inter_tu_counters(); + println!("rect_inter: tu={rtu} txsplit={rsplit} obmc_leaf={robmc}"); + let ir = ec_av1::stream::inter_rect_counters(); + println!( + "inter_rect: 32x8={} 8x32={} 64x32={} 32x64={} 64x16={} 16x64={}", + ir.0, ir.1, ir.2, ir.3, ir.4, ir.5 + ); }; // lane-tiles: the tiling a real stream actually uses is a decision input // (every gate in `stream.rs` picks its own `--tile-columns`), so report it diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index fa42e872..47f8df73 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -1628,7 +1628,7 @@ pub const SKIP_MODE: [[u16; 3]; 3] = [[32621, 32768, 0], [20708, 32768, 0], [812 /// `motion_mode_allowed` (spec 5.11.24's `read_motion_mode`) offers /// `OBMC_CAUSAL` rather than `WARPED_CAUSAL` -- lane-motionmode round 1 /// never reaches the three-way `motion_mode_cdf`, see `decode.rs`. -pub const OBMC: [[u16; 3]; 6] = [ +pub const OBMC: [[u16; 3]; 14] = [ [10437, 32768, 0], [17432, 32768, 0], [25817, 32768, 0], @@ -1638,6 +1638,20 @@ pub const OBMC: [[u16; 3]; 6] = [ // (rect-flake-1: the strip's motion_mode read diverged on this). [14423, 32768, 0], [15142, 32768, 0], + // lane-inter4 r1: the rect rows a superblock-level HORZ/VERT/1:4 and a + // 32x32-level 1:4 inter strip read -- BLOCK_32X64 (10), BLOCK_64X32 (11), + // BLOCK_8X32 (18), BLOCK_32X8 (19), BLOCK_16X64 (20), BLOCK_64X16 (21) of + // libaom's `default_obmc_cdf`. + [22823, 32768, 0], + [22083, 32768, 0], + [23664, 32768, 0], + [20901, 32768, 0], + [24008, 32768, 0], + [26879, 32768, 0], + // lane-inter4 r3: the 16x16-level rect inter leaves' own rows -- + // BLOCK_8X16 (4) and BLOCK_16X8 (5) of libaom's `default_obmc_cdf`. + [9371, 32768, 0], + [9301, 32768, 0], ]; /// `default_motion_mode_cdf` (spec 9.4, `entropymode.c`), the square-bsize @@ -1647,7 +1661,7 @@ pub const OBMC: [[u16; 3]; 6] = [ /// `read_motion_mode` reads instead of [`OBMC`] whenever `motion_mode_allowed` /// (spec 5.11.24) resolves to `WARPED_CAUSAL`-eligible (`num_proj_ref >= 1` /// under `allow_warped_motion`) -- lane-warp round 1. -pub const MOTION_MODE: [[u16; 4]; 6] = [ +pub const MOTION_MODE: [[u16; 4]; 14] = [ [7651, 24760, 32768, 0], [19419, 26810, 32768, 0], [26260, 29116, 32768, 0], @@ -1655,6 +1669,18 @@ pub const MOTION_MODE: [[u16; 4]; 6] = [ // lane-rect r2: BLOCK_16X32 / BLOCK_32X16 rows (indices 7/8). [5123, 23606, 32768, 0], [11606, 24308, 32768, 0], + // lane-inter4 r1: BLOCK_32X64 / 64X32 / 8X32 / 32X8 / 16X64 / 64X16 rows + // (libaom `default_motion_mode_cdf` indices 10, 11, 18, 19, 20, 21). + [20360, 28062, 32768, 0], + [21679, 26830, 32768, 0], + [28799, 31390, 32768, 0], + [26431, 30774, 32768, 0], + [28973, 31594, 32768, 0], + [29742, 31203, 32768, 0], + // lane-inter4 r3: BLOCK_8X16 / BLOCK_16X8 rows (libaom + // `default_motion_mode_cdf` indices 4 and 5). + [4738, 24765, 32768, 0], + [5391, 25528, 32768, 0], ]; /// `default_interintra_cdf` (spec 9.4): `interintra`, indexed by diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index f4d4dd64..90b8878c 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 @@ -165,6 +175,24 @@ pub(crate) enum TxbSet { /// 16x16 row's five-symbol reduced CDF here and desynced on the very /// first coded rect leaf. LumaRect16x8Set1, + /// lane-inter4 r3: [`LumaRect16x8`](TxbSet::LumaRect16x8)'s INTER twin -- + /// the same coefficient tables (`get_txsize_entropy_ctx` reduces TX_16X8 + /// and TX_8X16 alike to the 16x16 set, 128-position `eob_pt`), with the + /// inter `tx_type` alphabet in place of the intra one. Under + /// `reduced_tx_set` `av1_get_ext_tx_set_type` (`tx_size_sqr_up == + /// TX_16X16`, `is_inter`) returns `EXT_TX_SET_DCT_IDTX` (2 symbols), + /// whose CDF row is `default_inter_ext_tx_cdf[1][txsize_sqr_map[TX_16X8] + /// == TX_8X8]`, i.e. [`INTER_TX_TYPE_SET3_8`](crate::cdf::INTER_TX_TYPE_SET3_8) + /// -- the same table the square `Luma8Inter` set reads. + LumaRect16x8Inter, + /// [`LumaRect16x8Inter`](TxbSet::LumaRect16x8Inter)'s `reduced_tx_set: + /// false` counterpart: `tx_size_sqr` is `TX_8X8` here (NOT the + /// `txsize_sqr_up_map` `TX_16X16` the coefficient tables use), so + /// `av1_ext_tx_set_lookup[is_inter=1][tx_size_sqr == TX_16X16 -> 0]` is + /// `EXT_TX_SET_ALL16` -- sixteen symbols, `default_inter_ext_tx_cdf[1] + /// [TX_8X8]`, i.e. [`INTER_TX_TYPE_SET1_8`](crate::cdf::INTER_TX_TYPE_SET1_8), + /// the table [`Luma8InterSet1`](TxbSet::Luma8InterSet1) also reads. + LumaRect16x8InterSet1, /// The chroma 8x4/4x8 transform under the same leaf (lane-rectx): /// [`Chroma8`](TxbSet::Chroma8)'s tables except `eob_pt`, which reads the /// true 32-position [`crate::cdf::EOB_PT_32_CHROMA`] instead of @@ -473,13 +501,13 @@ pub(crate) struct Cdfs { /// `BLOCK_8X8`, 1 = `BLOCK_16X16`, 2 = `BLOCK_32X32`, 3 = `BLOCK_64X64` /// (`default_obmc_cdf`'s own `BLOCK_SIZES_ALL` indices 3/6/9/12 -- /// this decoder only ever codes those four square sizes). - pub obmc: [[u16; 3]; 6], + pub obmc: [[u16; 3]; 14], /// `motion_mode` (spec 5.11.24's `read_motion_mode`), the 3-symbol /// `SIMPLE_TRANSLATION`/`OBMC_CAUSAL`/`WARPED_CAUSAL` alphabet read /// instead of [`Self::obmc`] whenever `motion_mode_allowed` resolves to /// `WARPED_CAUSAL`-eligible -- same square-bsize indexing as `obmc`. /// lane-warp round 1. - pub motion_mode: [[u16; 4]; 6], + pub motion_mode: [[u16; 4]; 14], /// `interintra`, indexed by `size_group_lookup[bsize]` -- see /// `cdf::INTERINTRA`'s own doc. pub interintra: [[u16; 3]; 4], @@ -1683,6 +1711,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, @@ -1767,6 +1807,30 @@ impl Cdfs { tx_type: Some(self.intra_tx_type_8_set1[mode].as_mut_slice()), eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), }, + TxbSet::LumaRect16x8Inter => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_128_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_8.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), + }, + TxbSet::LumaRect16x8InterSet1 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_128_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_8_set1.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), + }, TxbSet::ChromaRect8x4 => TxbTables { side: 8, txb_skip: &mut self.txb_skip_chroma_8, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 42bbfea1..c8f43434 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -911,6 +911,15 @@ 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) }; + // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter + // frame -- 16x8 and 8x16 inter leaves. + static INTER_LEAF16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_LEAF16_VERT_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 @@ -934,6 +943,26 @@ pub(crate) fn txfm_split_hits() -> usize { TXFM_SPLIT_HITS.with(|c| c.get()) } +/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3). +pub(crate) fn inter_leaf16_horz_hits() -> usize { + INTER_LEAF16_HORZ_HITS.with(|c| c.get()) +} + +/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3). +pub(crate) fn inter_leaf16_vert_hits() -> usize { + INTER_LEAF16_VERT_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`]/ /// [`ENABLE_FILTER_INTRA_INTER`]. pub(crate) fn set_inter_tx_mode( @@ -1701,6 +1730,19 @@ pub(crate) fn wii_hits() -> usize { WII_HITS.with(|c| c.get()) } +// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC +// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the +// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented +// aomdec, neighbour list included). +thread_local! { + static OBMC_RECT_LEAF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`OBMC_RECT_LEAF_HITS`]. +pub(crate) fn obmc_rect_leaf_hits() -> usize { + OBMC_RECT_LEAF_HITS.with(|c| c.get()) +} + /// Current value of [`OBMC_HITS_8`]. pub(crate) fn obmc_hits_8() -> usize { OBMC_HITS_8.with(|c| c.get()) @@ -1935,6 +1977,17 @@ pub(crate) fn sb_rect4_vert_hits() -> usize { thread_local! { static RECT4_32_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_32_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-inter4 r1: the INTER-frame twins of the two counters above -- + /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` / + /// `PARTITION_VERT_4`. + static RECT4_32_HORZ_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_32_VERT_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT` + /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64). + static INTER_SB_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_SB_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_SB_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_SB_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// How many 32x32-level 1:4 strips actually read coefficients (non-skip): @@ -1983,6 +2036,36 @@ pub(crate) fn rect4_32_vert_hits() -> usize { RECT4_32_VERT_HITS.with(|c| c.get()) } +/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded). +pub(crate) fn rect4_32_horz_inter_hits() -> usize { + RECT4_32_HORZ_INTER_HITS.with(|c| c.get()) +} + +/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded). +pub(crate) fn rect4_32_vert_inter_hits() -> usize { + RECT4_32_VERT_INTER_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded). +pub(crate) fn inter_sb_horz_hits() -> usize { + INTER_SB_HORZ_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded). +pub(crate) fn inter_sb_vert_hits() -> usize { + INTER_SB_VERT_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded). +pub(crate) fn inter_sb_horz4_hits() -> usize { + INTER_SB_HORZ4_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded). +pub(crate) fn inter_sb_vert4_hits() -> usize { + INTER_SB_VERT4_HITS.with(|c| c.get()) +} + // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not @@ -2112,24 +2195,61 @@ pub(crate) fn build_motion_field( mi_cols: usize, mi_rows: usize, order_hint: u32, + order_hint_bits: u32, ref_order_hints: [u32; 7], ) -> crate::motion_field::MotionField { let mut field = crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints); + // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference + // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other + // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block + // referencing one stores only its OTHER side's mv. With + // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and + // nothing is skipped. + let other_side = |rf: i8| -> bool { + if order_hint_bits == 0 { + return false; + } + let oh = ref_order_hints[(rf - LAST_FRAME) as usize]; + crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0 + || oh == order_hint + }; + // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is + // capped at 12 bits per component; a longer one is not stored at all. + const REFMVS_LIMIT: i32 = (1 << 12) - 1; for row in 0..mi_rows { for col in 0..mi_cols { - if let Some(info) = grid.get(row, col) - && info.is_inter - && info.ref_frame > 0 - { - field.set( - row, - col, - crate::motion_field::SavedMv { - mv: info.mv, - ref_frame: info.ref_frame, - }, - ); + let Some(info) = grid.get(row, col) else { + continue; + }; + if !info.is_inter { + continue; + } + // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST + // qualifying one wins -- a compound block stores its second + // reference's mv, never its first (unless the second is on the + // other side or over the limit). Storing slot 0 unconditionally + // put the wrong (mv, ref_frame_offset) pair in every compound + // block's cell, which a later frame's temporal candidate then + // projected with the wrong reference distance. + let mut saved: Option = None; + for (rf, mv) in [ + (info.ref_frame, Some(info.mv)), + (info.ref_frame1.unwrap_or(0), info.mv1), + ] { + let (Some(mv), true) = (mv, rf > 0) else { + continue; + }; + if other_side(rf) { + continue; + } + if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT { + continue; + } + saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf }); + } + if let Some(saved) = saved { + field.set(row, col, saved); } } } @@ -4420,20 +4540,46 @@ impl Neighbours { uv_mode: usize, grids: &[Vec; 3], ) { - let (r, c) = at; + self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids); + } + + /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a + /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the + /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed + /// by the enclosing cell (a sub-16 extent writes none of them, exactly as + /// the [`SUB`]-unit path does). + fn record_rect_mi( + &mut self, + at_mi: (usize, usize), + w: usize, + h: usize, + mode: usize, + uv_mode: usize, + 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; } - self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode); - self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode); - self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids); + self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode); + self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode); + self.record_mi_rect(at_mi, w, h, grids); } /// The coefficient-context half of [`Self::record`], taking the block's @@ -4457,10 +4603,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 @@ -4591,23 +4741,34 @@ impl Neighbours { let (mi_r, mi_c) = at_mi; let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); for cell in 0..w.div_ceil(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.div_ceil(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; } + let (w_mi, h_mi) = (w / MI, h / MI); 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)); @@ -9957,8 +10118,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`. @@ -9973,16 +10151,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; } } } @@ -10204,6 +10396,264 @@ 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) | (16, 8) | (8, 16)) +} + +/// The luma coefficient/`tx_type` table set of a whole-block rectangular +/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits +/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so +/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of +/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and +/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced +/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF +/// row (`txsize_sqr_map`), never the 16x16 one. +fn rect_inter_luma_set(w: usize, h: usize) -> TxbSet { + match (w, h) { + (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter, + (16, 8) | (8, 16) => { + if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) { + TxbSet::LumaRect16x8Inter + } else { + TxbSet::LumaRect16x8InterSet1 + } + } + _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), + } +} + +/// The chroma table set of the same block's single rectangular chroma unit +/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8 +/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit +/// the luma unit's. +fn rect_inter_chroma_set(w: usize, h: usize) -> TxbSet { + match (w, h) { + (16, 8) | (8, 16) => TxbSet::ChromaRect16x8, + (8, 4) | (4, 8) => TxbSet::ChromaRect8x4, + _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), + } +} + +/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's +/// inter path reaches, from the block's TRUE footprint rather than the +/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2, +/// everything 32 and above -> 3. +fn size_group_wh(w: usize, h: usize) -> usize { + // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom + // `common_data.h:60`) is 0 for every block with a 4-px side + // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old + // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0. + match w.min(h) { + 0..=4 => 0, + 8 => 1, + 16 => 2, + _ => 3, + } +} + +#[test] +fn size_group_wh_matches_libaom_size_group_lookup() { + // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s + // transcribed values (common_data.h:60-62). + const TABLE: [((usize, usize), usize); 22] = [ + ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1), + ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3), + ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3), + ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2), + ]; + for ((w, h), want) in TABLE { + assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})"); + } +} + +/// 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 @@ -13741,11 +14191,33 @@ fn obmc_blend( // its OWN neighbour cap (width-log2 for above, height-log2 for left) and // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was // right only for square blocks. + // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by + // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left): + // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old + // `1..=4 => 2` row was right only for blocks at least 16 px on that axis + // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where + // libaom walks one, blending an extra 8-px-tall neighbour into every + // rect leaf with two of them on its left edge (class table-narrowed-to- + // the-reachable-sizes; the square gates could never expose it). let max_nb = |n4: usize| match n4 { - 1..=4 => 2, + 0..=1 => 0, + 2 => 1, + 3..=4 => 2, 5..=8 => 3, _ => 4, }; + // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels + // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in + // both decoders on that exact stream: the neighbour lists agree entry for + // entry (position, span, mv, ref, size, filter) and all six pre-filter + // frames are byte-identical to the instrumented aomdec's. The refusal is + // gone; the counter below is what the gate's `--enable-obmc=1` arm reads. + // The only decode-path change between r3's measurement and this one is the + // lane-interbis merge (`build_motion_field`'s compound slot walk), which + // moves temporal MV candidates -- not bisected further. + if matches!((write_w, write_h), (16, 8) | (8, 16)) { + OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1)); + } let overlap_above = write_h / 2; let overlap_left = write_w / 2; // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc` @@ -14128,6 +14600,12 @@ fn build_gm_mv_table( /// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already /// refuse. #[allow(clippy::too_many_arguments)] +/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit +/// [`decode_inter_block`]'s `at` now takes. +const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) { + (t.0 * (SUB / MI), t.1 * (SUB / MI)) +} + fn decode_inter_block( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, @@ -14164,7 +14642,11 @@ fn decode_inter_block( chroma_tx: usize, scan_luma: &[u16], scan_chroma: &[u16], - size_group: usize, + // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the + // one site that read it (`y_mode`) -- a rect strip's group comes from its + // true footprint, not the caller's square `side`. Kept in the signature + // rather than editing twenty call sites. + _size_group: usize, allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, @@ -14242,13 +14724,16 @@ fn decode_inter_block( // combinations that don't implement scaled MC yet. frame_width: usize, ) -> Result<()> { - let (r, c) = at; + // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can + // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the + // few 16-px-granular uses below. + let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI)); // lane-inter8 r2: the inter side bands are mi-granular; this block's own // above/left neighbour is the mi cell at its top-left corner (libaom // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads // exactly what it read before. - let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI)); - let (px, py) = (c * SUB, r * SUB); + let (rmi, cmi) = at; + let (px, py) = (at.1 * MI, at.0 * MI); let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2); @@ -14256,7 +14741,7 @@ fn decode_inter_block( if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}", - r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 + rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } let skip_mode_ctx = @@ -14272,7 +14757,7 @@ fn decode_inter_block( } // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before // `skip_mode`/`skip`, `inter_segment_id(0)` after them. - let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (seg_mi_r, seg_mi_c) = (rmi, cmi); let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4); inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; @@ -14289,21 +14774,27 @@ fn decode_inter_block( let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false); - maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip); - maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); - maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); + maybe_read_cdef_idx(dec, rmi, cmi, skip); + // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip + // is NOT the whole superblock, so its `skip` never suppresses the read. + let whole_sb = side == 64 && write_w == 64 && write_h == 64; + maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip); + maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip); // 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", )); } let (has_above, has_left) = ( - r > neighbours.tile_row0_mi / (SUB / MI), - c > neighbours.tile_col0_mi / (SUB / MI), + rmi > neighbours.tile_row0_mi, + cmi > neighbours.tile_col0_mi, ); let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); @@ -14311,15 +14802,15 @@ fn decode_inter_block( if std::env::var_os("EC_TRACE_MODE").is_some() { eprintln!( "EC_MODE mi_row={} mi_col={} rng={}", - r * SUB_MI as usize, - c * SUB_MI as usize, + rmi, + cmi, dec.debug_state().0 ); } if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}", - r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 + rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } @@ -14339,7 +14830,7 @@ fn decode_inter_block( // than one luma transform -- read back by the residual loop, the // coefficient-context write-back and the loop-filter grid fill below. let mut vartx_leaves: Option> = None; - let at_mi = (r * (SUB / MI), c * (SUB / MI)); + let at_mi = at; if is_inter { let above_nbr = has_above.then(|| NeighbourRef { is_inter: above_inter, @@ -14384,7 +14875,7 @@ fn decode_inter_block( neighbours.left_ref[rmi], ) }; - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: true footprint, mirroring the single-ref path below. let bw4 = write_w / 4; let bh4 = write_h / 4; @@ -15102,17 +15593,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, @@ -15145,7 +15651,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(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 @@ -15192,6 +15705,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, + rect_inter_luma_set(write_w, write_h), + (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, @@ -15211,6 +15744,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, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (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, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (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, @@ -15247,6 +15829,7 @@ fn decode_inter_block( None, )? .0; + } } } else { let ref_frame = @@ -15260,7 +15843,7 @@ fn decode_inter_block( ); ref_frame_for_lf = ref_frame; if std::env::var_os("EC_AV1_TELL").is_some() { - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 @@ -15288,7 +15871,7 @@ fn decode_inter_block( } }; - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: the mv stack must be queried with the block's // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from // xd->width/xd->height, not a square guess) -- `write_w`/ @@ -15335,6 +15918,10 @@ fn decode_inter_block( ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; + // lane-interbis r1: which single-ref mode this block resolved to, + // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for + // the `EC_MODE_VAL` value ladder below. + let mut dbg_mode = 16u32; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the @@ -15367,9 +15954,11 @@ fn decode_inter_block( let mv = if !not_zero { // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already // computed at this block's own position in `gm_table`. + dbg_mode = 15; gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + dbg_mode = if nearest { 13 } else { 14 }; if nearest { stack.nearest_mv } else { @@ -15391,6 +15980,21 @@ fn decode_inter_block( }; (mv, false) }; + if std::env::var_os("EC_TRACE_MODE").is_some() { + for (i, e) in stack.entries.iter().enumerate() { + eprintln!( + "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", + e.mv.0, e.mv.1, e.weight + ); + } + eprintln!( + "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}", + mv.0, + mv.1, + stack.entries.len(), + dec.debug_state().0 + ); + } // lane-gm r2: the two libaom predicates single-ref GLOBALMV // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating @@ -15422,8 +16026,22 @@ fn decode_inter_block( // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3. let mut interintra_mode: Option = None; let mut wedge_mask: Option<(&'static [u8], usize)> = None; - if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) { - let bsize_group = if side == 16 { 2 } else { 3 }; + // lane-inter4 r1: `is_interintra_allowed_bsize` is + // `BLOCK_8X8..=BLOCK_32X32` in libaom's enum ORDER, which excludes + // every 1:4 shape (BLOCK_8X32 = 18, BLOCK_32X8 = 19) even though + // both dimensions are in range -- reading this symbol on a 1:4 + // strip is a symbol the reference never wrote. + let interintra_shape = + write_w.max(write_h) <= 32 && write_w.max(write_h) / write_w.min(write_h) <= 2; + if enable_interintra_compound + && !skip_mode + && (side == 16 || side == 32) + && interintra_shape + { + // lane-inter4 r3: `size_group_lookup` reads the block's + // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip + // group 2, not their square `side`'s 2/3. + let bsize_group = size_group_wh(write_w, write_h); let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1; if interintra { // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode, @@ -15518,12 +16136,29 @@ fn decode_inter_block( // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4, // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's // strip motion_mode read diverged on the square row. - let bsize_idx = if write_w == write_h { - (write_w.trailing_zeros() - 3) as usize - } else if write_w == 16 { - 4 - } else { - 5 + // lane-inter4 r1: every rect shape this decoder can now + // reach reads its OWN libaom bsize row (the packed order is + // documented on `cdf::MOTION_MODE`); a wrong row is a wrong + // interval narrowing, not a wrong value (class + // wrong-alphabet-same-value). + let bsize_idx = match (write_w, write_h) { + (w, h) if w == h => (w.trailing_zeros() - 3) as usize, + (16, 32) => 4, + (32, 16) => 5, + (32, 64) => 6, + (64, 32) => 7, + (8, 32) => 8, + (32, 8) => 9, + (16, 64) => 10, + (64, 16) => 11, + // lane-inter4 r3: the 16x16-level rect inter leaves. + (8, 16) => 12, + (16, 8) => 13, + _ => { + return Err(unsupported( + "a motion_mode symbol for a block shape with no CDF row here", + )); + } }; // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf` // instead of the 2-symbol `obmc_cdf` exactly when @@ -15936,17 +16571,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, @@ -15979,7 +16629,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(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 @@ -16026,6 +16683,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, + rect_inter_luma_set(write_w, write_h), + (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, @@ -16045,6 +16722,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, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (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, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (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, @@ -16081,6 +16807,7 @@ fn decode_inter_block( None, )? .0; + } } } } else { @@ -16096,7 +16823,7 @@ fn decode_inter_block( this decoder does not code yet", )); } - let mode = dec.symbol(&mut cdfs.y_mode[size_group]); + let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]); if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", @@ -16202,7 +16929,7 @@ fn decode_inter_block( block_filter = [3, 3]; ref_frame_for_lf = 0; globalmv_for_lf = false; - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); for dr in 0..side / 4 { for dc in 0..side / 4 { grid.set( @@ -16343,7 +17070,7 @@ 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(at, side); + let around = neighbours.around_mi(at, side); luma_grid = if split_luma { // Already coded and reconstructed unit by unit above; the // block-level grid is only the neighbour write-back's input, @@ -16429,7 +17156,7 @@ fn decode_inter_block( if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=block_end tell={} range={}", - r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 + rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } if vartx_leaves.is_some() { @@ -16437,9 +17164,9 @@ fn decode_inter_block( // ([`Neighbours::record_mi_luma`] above); this writes everything else // [`Neighbours::record_rect`] would (a var-tx block is always square, // so `write_w == write_h == side`). - neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]); + neighbours.record_split_luma_rect_mi(at, side, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]); } else { - neighbours.record_rect( + neighbours.record_rect_mi( at, write_w, write_h, @@ -16448,10 +17175,10 @@ fn decode_inter_block( &[luma_grid, u_grid, v_grid], ); } - neighbours.record_inter_rect( + neighbours.record_inter_rect_mi( at, - write_w, - write_h, + write_w / MI, + write_h / MI, skip, is_inter, ref_frame_for_lf, @@ -16459,16 +17186,16 @@ fn decode_inter_block( skip_mode, ); if let Some((ref1, group_idx, idx)) = compound_ctx { - neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx); + neighbours.record_compound_ctx_rect_mi(at, write_w / MI, write_h / MI, ref1, group_idx, idx); } neighbours.fill_skip_grid_rect( - (r * (SUB / MI), c * (SUB / MI)), + (rmi, cmi), write_w / MI, write_h / MI, skip, ); neighbours.fill_lf_grid_rect( - (r * (SUB / MI), c * (SUB / MI)), + (rmi, cmi), write_w / MI, write_h / MI, // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the @@ -18456,6 +19183,64 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ); CDEF_TRANSMITTED.with(|c| c.set(false)); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); + // lane-inter4 r1: every rect inter piece below is the same + // `decode_inter_block` call with only position / true footprint / + // transform-set differing; the macro keeps the new arms readable + // instead of six more 60-line copies of the argument list. + macro_rules! inter_piece { + ($at_mi:expr, $side:expr, $li:expr, $lt:expr, $ch:expr, $ltx:expr, + $ctx:expr, $sl:expr, $sc:expr, $sg:expr, $ww:expr, $wh:expr) => { + decode_inter_block( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + $at_mi, + $side, + mi_cols, + mi_rows, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + &ref_slots, + &sign_bias_table, + &global_motion, + base_q_idx, + $li, + $lt, + $ch, + $ltx, + $ctx, + $sl, + $sc, + $sg, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + tpl_frame.as_ref(), + reference_select, + enable_masked_compound, + enable_interintra_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, + switchable_motion_mode, + allow_warped_motion, + true, + $ww, + $wh, + allow_screen_content_tools, + frame_width as usize, + )? + }; + } let sb_ctx = neighbours.partition_ctx(sb_at, SB); let (has_cols, has_rows) = ( sb_c * SB_MI + SB_MI / 2 < mi_cols, @@ -18506,7 +19291,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - sb_at, + sub16_to_mi(sb_at), SB, mi_cols, mi_rows, @@ -18552,10 +19337,73 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )?; continue; } + if matches!( + part64, + PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4 + ) { + // lane-inter4 r1: the superblock-level rect + 1:4 pairs as + // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 / + // 16x64 ones. Each piece keeps `side = SB` for every + // syntax/CDF/prediction-buffer decision (the square-context + // corner-cut PARTITION_HORZ already ships at the 32 level) + // but names its own true footprint through `write_w`/ + // `write_h`, which is what `motion_mode`'s bsize row, the + // mv-stack's bw4/bh4, the delta-q `bSize == sbSize` test and + // every neighbour stamp read. `reject_residual = true`: a + // non-skip strip refuses by name rather than over-read a + // square residual (rectangular inter residual coding is not + // ported -- see lanes/inter4-r1.report.md). + let horz = matches!(part64, PARTITION_HORZ | PARTITION_HORZ_4); + let four = matches!(part64, PARTITION_HORZ_4 | PARTITION_VERT_4); + let base_mi = ( + sb_r as usize * SB_MI as usize, + sb_c as usize * SB_MI as usize, + ); + let (n_pieces, step_mi) = if four { (4usize, 4usize) } else { (2usize, 8usize) }; + let (bw, bh) = match (horz, four) { + (true, false) => (64usize, 32usize), + (false, false) => (32, 64), + (true, true) => (64, 16), + (false, true) => (16, 64), + }; + for i in 0..n_pieces { + let at_mi = if horz { + (base_mi.0 + i * step_mi, base_mi.1) + } else { + (base_mi.0, base_mi.1 + i * step_mi) + }; + // libaom `decode_partition`'s own `i > 0` frame-edge break. + if i > 0 && (at_mi.0 >= mi_rows as usize || at_mi.1 >= mi_cols as usize) { + break; + } + inter_piece!( + at_mi, + SB, + TxbSet::Luma64, + TxbSet::Luma64, + TxbSet::Chroma32, + TX32, + TX32, + &scan32, + &scan32, + 3, + bw, + bh + ); + match (horz, four) { + (true, false) => INTER_SB_HORZ_HITS.with(|c| c.set(c.get() + 1)), + (false, false) => INTER_SB_VERT_HITS.with(|c| c.set(c.get() + 1)), + (true, true) => INTER_SB_HORZ4_HITS.with(|c| c.set(c.get() + 1)), + (false, true) => INTER_SB_VERT4_HITS.with(|c| c.set(c.get() + 1)), + } + } + continue; + } if part64 != PARTITION_SPLIT { return Err(unsupported( - "an inter SB-level partition type other than NONE or SPLIT (this decoder's \ - inter tile path recurses a superblock only as SPLIT)", + "an inter SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B; this \ + decoder's inter tile path codes a superblock as NONE, SPLIT, HORZ, \ + VERT, HORZ_4 or VERT_4)", )); } @@ -18607,7 +19455,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -18708,7 +19556,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at16, + sub16_to_mi(at16), SUB, mi_cols, mi_rows, @@ -18756,9 +19604,96 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( allow_screen_content_tools, frame_width as usize, )?; + } else if part16 == PARTITION_HORZ || part16 == PARTITION_VERT { + // lane-inter4 r3: the 16x16-level rect inter + // leaves -- two true 16x8 (HORZ) or 8x16 + // (VERT) inter blocks. Same shape as the + // 32-level HORZ/VERT arm above: `side = SUB` + // keeps every CDF/prediction-buffer decision + // square, `write_w`/`write_h` carry the true + // footprint into the mv stack, the motion-mode + // row, the neighbour stamps and the rectangular + // residual path (`rect_inter_residual_supported` + // covers 16x8/8x16 since this round). + let horz = part16 == PARTITION_HORZ; + if horz { + INTER_LEAF16_HORZ_HITS.with(|c| c.set(c.get() + 1)); + } else { + INTER_LEAF16_VERT_HITS.with(|c| c.set(c.get() + 1)); + } + let base_mi = sub16_to_mi(at16); + let (ww, wh) = if horz { (16, 8) } else { (8, 16) }; + for piece in 0..2 { + let piece_mi = if horz { + (base_mi.0 + piece * 2, base_mi.1) + } else { + (base_mi.0, base_mi.1 + piece * 2) + }; + // libaom `decode_partition`'s own second- + // half frame-edge break. + if piece > 0 + && (piece_mi.0 >= mi_rows as usize + || piece_mi.1 >= mi_cols as usize) + { + break; + } + decode_inter_block( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + piece_mi, + SUB, + mi_cols, + mi_rows, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + &ref_slots, + &sign_bias_table, + &global_motion, + base_q_idx, + TxbSet::Luma16, + if reduced_tx_set { + TxbSet::Luma16Inter + } else { + TxbSet::Luma16InterSet1 + }, + TxbSet::Chroma8, + TX16, + TX8, + &scan16, + &scan8, + 1, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + tpl_frame.as_ref(), + reference_select, + enable_masked_compound, + enable_interintra_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, + switchable_motion_mode, + allow_warped_motion, + true, + ww, + wh, + allow_screen_content_tools, + frame_width as usize, + )?; + } } else if part16 != PARTITION_SPLIT { return Err(unsupported( - "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)", + "an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT or SPLIT)", )); } else { if has_cols16 && has_rows16 { @@ -18914,7 +19849,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at32, + sub16_to_mi(at32), BLOCK, mi_cols, mi_rows, @@ -18967,7 +19902,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), SUB, mi_cols, mi_rows, @@ -19021,7 +19956,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19085,7 +20020,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -19134,7 +20069,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), BLOCK, mi_cols, mi_rows, @@ -19188,7 +20123,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -19237,7 +20172,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), BLOCK, mi_cols, mi_rows, @@ -19292,7 +20227,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), SUB, mi_cols, mi_rows, @@ -19345,7 +20280,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19398,7 +20333,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), BLOCK, mi_cols, mi_rows, @@ -19453,7 +20388,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), SUB, mi_cols, mi_rows, @@ -19506,7 +20441,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), SUB, mi_cols, mi_rows, @@ -19559,7 +20494,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), BLOCK, mi_cols, mi_rows, @@ -19615,7 +20550,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -19664,7 +20599,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19717,7 +20652,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19766,6 +20701,49 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_width as usize, )?; } + PARTITION_HORZ_4 | PARTITION_VERT_4 => { + // lane-inter4 r1: four 32x8 / 8x32 inter strips, + // `quarter_step` = 2 mi -- the arm ReelC's first inter + // frame stops at (`value=9` = PARTITION_VERT_4). + // `at` is in 16-px cells and cannot name an 8-px + // offset, which is why `decode_inter_block` takes mi + // coordinates now. + let horz = part32 == PARTITION_HORZ_4; + let base_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); + let (bw, bh) = if horz { (32usize, 8usize) } else { (8, 32) }; + for i in 0..4 { + let strip_mi = if horz { + (base_mi.0 + i * 2, base_mi.1) + } else { + (base_mi.0, base_mi.1 + i * 2) + }; + if i > 0 + && (strip_mi.0 >= mi_rows as usize + || strip_mi.1 >= mi_cols as usize) + { + break; + } + inter_piece!( + strip_mi, + BLOCK, + TxbSet::Luma32, + TxbSet::Luma32Inter, + TxbSet::Chroma16, + TX32, + TX16, + &scan32, + &scan16, + 3, + bw, + bh + ); + if horz { + RECT4_32_HORZ_INTER_HITS.with(|c| c.set(c.get() + 1)); + } else { + RECT4_32_VERT_INTER_HITS.with(|c| c.set(c.get() + 1)); + } + } + } _ => { return Err(unsupported(format!( "an INTER 32x32 partition type this decoder does not code (value={part32})" @@ -19821,6 +20799,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mi_cols as usize, mi_rows as usize, order_hint, + order_hint_bits, ref_order_hints, ); @@ -20396,8 +21375,13 @@ mod tests { ) .unwrap_err(); let msg = err.to_string(); + // lane-inter4 r1: this fixture's SB value is PARTITION_HORZ, now + // DECODED rather than refused outright; its first 64x32 strip is + // non-skip, so the named refusal is the rectangular-inter-residual + // one. Either string proves what the pin was written for: a non-SPLIT + // superblock never silently decodes as SPLIT. assert!( - msg.contains("SPLIT"), + msg.contains("SPLIT") || msg.contains("rectangular residual coding"), "expected the named inter-SB-partition refusal, got: {msg}" ); } @@ -20880,7 +21864,7 @@ mod tests { &mut cdfs, &mut neighbours, &mut grid, - (r, c), + sub16_to_mi((r, c)), side, mi_cols, mi_rows, diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index bac2f6eb..7768f7ac 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -420,7 +420,17 @@ pub fn add_tpl_ref_mv( if row8 < 0 || col8 < 0 { return None; } - let (fwd_mv, ref_frame_offset) = tpl.get(row8 as usize / 2, col8 as usize / 2)?; + let probe = tpl.get(row8 as usize / 2, col8 as usize / 2); + if std::env::var_os("EC_TRACE_TPL").is_some() { + match probe { + None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"), + Some((m, rfo)) => eprintln!( + "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}", + m.0, m.1 + ), + } + } + let (fwd_mv, ref_frame_offset) = probe?; let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset); let mv = lower_mv_precision(projected, allow_high_precision_mv); Some(TplCandidate { mv }) diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 6c1d840f..1365c428 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -65,12 +65,13 @@ const REFUSALS: &[&str] = &[ // the 8x8 leaf's TX_4X4 2x2 grid is still refused here. "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 transform units", "an inter frame with no key frame before it", - "an inter SB-level partition type other than NONE or SPLIT (this decoder's inter tile path recurses a superblock only as SPLIT)", - "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)", + "an inter SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B; this decoder's inter tile path codes a superblock as NONE, SPLIT, HORZ, VERT, HORZ_4 or VERT_4)", + "an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT or SPLIT)", "an intra mode this decoder does not code (round 2)", "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet", "warp prediction with a scaled reference (superres, unimplemented)", "an 8x8 partition leaf under a scaled reference (superres, unimplemented)", + "a motion_mode symbol for a block shape with no CDF row here", ]; /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8ff585aa..92724f28 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -55,6 +55,19 @@ fn final_dump_prefix() -> Option { /// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search: /// (HORZ_4 strips, VERT_4 strips, strips that read coefficients). +/// lane-inter4 r1: the INTER-frame partition counters this lane's gates +/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded. +pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) { + ( + crate::decode::rect4_32_horz_inter_hits(), + crate::decode::rect4_32_vert_inter_hits(), + crate::decode::inter_sb_horz_hits(), + crate::decode::inter_sb_vert_hits(), + crate::decode::inter_sb_horz4_hits(), + crate::decode::inter_sb_vert4_hits(), + ) +} + pub fn rect4_32_counters() -> (usize, usize, usize) { ( crate::decode::rect4_32_horz_hits(), @@ -63,6 +76,17 @@ pub fn rect4_32_counters() -> (usize, usize, usize) { ) } +/// lane-inter4 r4: rectangular inter transform units coded whole, rect +/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the +/// three counters a recipe sweep needs to see from outside the crate. +pub fn rect_inter_tu_counters() -> (usize, usize, usize) { + ( + crate::decode::rect_inter_tu_hits(), + crate::decode::rect_inter_txsplit_hits(), + crate::decode::obmc_rect_leaf_hits(), + ) +} + /// Decode every frame in a raw AV1 OBU stream, in coding order. /// /// A key frame becomes the reference for the inter frames that follow it, @@ -1953,6 +1977,10 @@ mod tests { // masked compound, palette, ...) are other lanes' work; // this gate is about hidden frames, not about them. "--enable-warped-motion=0", + // OBMC stays off HERE (this gate is about hidden frames); + // the tool's own coverage is the `obmc*` gates and, on a + // 16x8/8x16 leaf, the `--enable-obmc=1` arm of + // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4). "--enable-obmc=0", "--enable-masked-comp=0", "--enable-interintra-comp=0", @@ -5898,6 +5926,786 @@ mod tests { ); } + /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/ + /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the + /// inter tile path refused outright before this lane ("an inter SB-level + /// partition type other than NONE or SPLIT"). `--min-partition-size=32` + /// keeps every 32x32-level rect shape (already coded, and residual-capable + /// only when skip) out of the picture so the counters can only be earned + /// at the superblock level; the noiseless split-motion source (one half + /// translating, the other static, flat inside each half) is what makes + /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` -- + /// the ONLY inter rect shape this decoder can complete, since rectangular + /// inter residual coding is not ported (see `reject_residual`). + /// + /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt + /// that refuses by name is counted, never turned into a SKIP; and an + /// attempt that decoded without firing the arm is counted separately and + /// still required to be pixel-exact (class gate-skips-on-its-own-failure). + #[test] + fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_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); + // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open + // residue, not a tolerance: across all 16 attempts x both depths, every + // 10-bit attempt that reached a superblock-level rect strip found it + // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B) + // strip needs rectangular residual coding". The 10-bit twin below is + // `#[ignore]`d with that exact reason rather than deleted or weakened. + for bit_depth in [8u32] { + let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = + (0u32, 0u32, 0u32, 0u32); + let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + for attempt in 0..16u32 { + // Two orientations (the transposed pair a one-sided gate could + // never separate) x four quantisers x two motion steps: which + // superblock the RD hands a skip-able rect strip moves with + // the quantiser, and the 10-bit arm needs a different corner + // of the grid from the 8-bit one. + let vertical_split = attempt % 2 == 1; + let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize]; + let sp = 8 + (attempt / 8) * 4; + let geq = if vertical_split { + format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)") + } else { + format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)") + }; + let duration = frame_count as f64 / 25.0; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='{geq}',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 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", + "--enable-tx-size-search=0", "--lag-in-frames=0", + // Per-arm overrides go LAST: aomenc keeps the last + // occurrence of a repeated --enable-* flag. + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", "--min-partition-size=32", + "--max-partition-size=64", + "--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 = crate::stream::inter_rect_counters(); + 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 = crate::stream::inter_rect_counters(); + let (horz, vert) = (after.2 - before.2, after.3 - before.3); + 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 horz + vert == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + superblock-level inter rect strips -- 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)"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + } + horz_proved += horz; + vert_proved += vert; + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \ + {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)" + ); + assert_eq!( + oos_mismatch, 0, + "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \ + decoded but mismatched ffmpeg -- a defect of another shape, not a pass" + ); + assert!( + horz_proved + vert_proved > 0, + "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \ + inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \ + {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing" + ); + } + } + + /// 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. + /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream + /// whose compound blocks feed the next frame's motion field + /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`). + /// + /// lane-interbis r1 pinned this recipe because it is the one the rect + /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a + /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its + /// nearest candidate from a temporal cell holding the wrong reference: + /// `build_motion_field` stored a compound block's FIRST reference where + /// libaom stores its second). Every fully decoded attempt is compared + /// plane by plane; a refusal is counted, never SKIPped; the temporal + /// candidate counter must fire on a compared attempt, or the gate proves + /// nothing. + #[test] + fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_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 compared, mut tmv_proved) = (0u32, 0u32, 0usize); + for attempt in 0..2u32 { + let tx_search = if attempt == 0 { "0" } else { "1" }; + let duration = frame_count as f64 / 25.0; + // The pinned source: horizontal structure translating along X + // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN + // blocks whose stored motion field the last frame reads back. + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',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 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-level=34", "--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::tmv_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 tmv = decode::tmv_hits() - before; + 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); + 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)"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + } + compared += 1; + tmv_proved += tmv; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \ + pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}" + ); + assert!( + compared > 0, + "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing" + ); + assert!( + tmv_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \ + candidate into a block's stack -- gate proved nothing" + ); + } + } + + #[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. + // lane-inter4 r4 re-measured after the 16-level rect inter leaf shipped + // (r3): STILL RED, and the blocker moved -- 12 named refusals over 16 + // 8-bit attempts, 10 of them "an intra-coded HORZ/VERT strip needs + // rectangular intra prediction this decoder does not code yet" and 2 the + // 16-level AB/1:4 inter refusal; 4 attempts decoded with no rect inter + // residual at all and none of them mismatched (tu=0, split=0). Neither + // remaining blocker is this lane's: the gate un-ignores when the intra + // rect strip lands. + #[ignore = "lane-inter4 r4 (re-measured): 12/16 8-bit attempts stop at the intra-rect-strip (10) or 16-level inter AB/1:4 (2) refusal, the other 4 code no rect inter residual -- tu=0, split=0; blocked on rectangular INTRA prediction, not on this lane"] + 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] + // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ / + // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter + // blocks, mode info + rectangular residual + prediction. Every decoded + // frame is compared Y/U/V against ffmpeg, refusals are counted and never + // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that + // also coded a rectangular inter transform unit (i.e. was not `skip`). + fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_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); + // Coded (non-skip) rect inter transform units, summed over both bit + // depths: at 10 bits this recipe's rect leaves all come out `skip` + // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop + // reaching a rect leaf at all), so the RESIDUAL half of the claim is + // proven by the 8-bit arm while the 10-bit arm proves the mode-info, + // prediction and neighbour halves on both axes. + let mut tu_total = 0usize; + 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); + let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize); + // lane-inter4 r4, measured residue of this recipe family (sweep + // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search + // on, via `decode_probe`'s `rect_inter:` counters): the rect + // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit + // rect leaf is always `skip` (tu=0 at every cq that decodes) -- + // below cq 22 every attempt stops at another lane's intra refusal + // ("a HORZ/VERT intra strip below 16x16 with a split transform"). + // Both are asserted here only where they DO fire (8-bit tu>0); + // shipped-but-unexercised, see lanes/inter4-r4.report.md. + // lane-inter4 r4: attempts 16..32 repeat the same sweep with + // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's + // instrumented-aomdec comparison showed the neighbour list AND + // every pre-filter frame bit-exact, so the arm is a gate now. + let mut obmc_leaf_proved = 0usize; + for attempt in 0..32u32 { + let obmc_arg = if attempt >= 16 { "--enable-obmc=1" } else { "--enable-obmc=0" }; + let attempt = attempt % 16; + // 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" }; + // A 10-bit encode of the same source spends fewer bits on + // residual at a given cq, so it needs the lower pair to make + // a rect leaf non-skip at all (measured: cq 34/22 gives zero + // coded rect inter TUs in 16 10-bit attempts). + 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=8", + "--max-partition-size=16", + obmc_arg, + "--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 before_obmc_leaf = decode::obmc_rect_leaf_hits(); + let before_leaf = ( + decode::inter_leaf16_horz_hits(), + decode::inter_leaf16_vert_hits(), + decode::inter_sub16_split_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 obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf; + let (horz, vert, splits16) = ( + decode::inter_leaf16_horz_hits() - before_leaf.0, + decode::inter_leaf16_vert_hits() - before_leaf.1, + decode::inter_sub16_split_hits() - before_leaf.2, + ); + 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 horz + vert == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + 16-level rect inter leaf -- another shape's defect" + ); + } + continue; + } + if mismatched { + // lane-inter4 r3: where, not just that -- a handful of + // 4x4-aligned pixels is a prediction/reconstruction + // defect, a whole band from the first row down is a + // desync. + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + let bad: Vec = (0..got.y.len()) + .filter(|&k| got.y[k] != want.y[k]) + .collect(); + if !bad.is_empty() { + eprintln!( + "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ + pixels differ, first at ({}, {}), max |delta| {}", + bad.len(), + bad[0] % width, + bad[0] / width, + bad.iter() + .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) + .max() + .unwrap_or(0) + ); + } + } + } + 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; + obmc_leaf_proved += obmc_leaf; + split_proved += split; + sub16_split += splits16; + if horz > 0 { + horz_proved += 1; + } + if vert > 0 { + vert_proved += 1; + } + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \ + 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \ + split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \ + leaf={obmc_leaf_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!( + horz_proved > 0 && vert_proved > 0, + "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \ + axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \ + SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \ + scope) -- gate proved nothing" + ); + assert!( + obmc_leaf_proved > 0, + "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \ + 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing" + ); + tu_total += tu_proved; + } + assert!( + tu_total > 0, + "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \ + residual on a 16-level leaf -- the residual half of the claim is unproven" + ); + } + + #[test] fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() { if !have_ffmpeg() { diff --git a/lanes/inter4-r1.report.md b/lanes/inter4-r1.report.md new file mode 100644 index 00000000..9dba6d76 --- /dev/null +++ b/lanes/inter4-r1.report.md @@ -0,0 +1,97 @@ +# lane-inter4 r1 — inter-frame rect / 1:4 partition arms + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off main `146896f` (charter said 8262b99; main had moved two merges further — +the worktree was already at 146896f and was NOT rebased backwards). + +## Premise re-measure (charter's premise was stale) + +`cargo run --release --example decode_probe` on both ReelC extracts, on THIS tree +before any edit of mine, stops at + + unsupported: AV1 tile (a coded HORZ/VERT strip whose chroma transform has no + rect coefficient tables here) + +i.e. an INTRA-frame refusal owned by lane-rectchroma, not "an INTER 32x32 partition +type ... (value=9)". The charter's `value=9` observation was made on lane-rectchroma +587d388, a tree where that intra refusal is already lifted. So ReelC's *next* blocker +after rectchroma merges is plausibly the inter 1:4 arm, but this lane cannot observe it. + +## The real ceiling this round found + +`decode_inter_block` refuses every NON-SKIP rectangular inter block: + + decode.rs:12938 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs + rectangular residual coding" + +Rectangular inter residual coding does not exist. Empirically (30 aomenc recipes swept, +`$HOME/.cache/inter4-probe`), every real stream that reaches an inter rect strip finds it +non-skip and stops there — including every 10-bit attempt of this lane's own gate. +Porting the partition ARMS is therefore necessary but not sufficient: the arms are +reachable, but only an all-skip strip completes. + +## Changed + +- `crates/ec-av1/src/decode.rs` + - `decode_inter_block`'s `at` is now in **MI (4 px) units**, not 16-px cells — a 32-level + 1:4 strip sits at an 8-px offset the old unit could not name. All 20 call sites wrapped + in the new `sub16_to_mi` helper; the body routes through `around_mi`, + `record_rect_mi` (new), `record_split_luma_rect_mi` (new), `record_inter_rect_mi`, + `record_compound_ctx_rect_mi`. `record_rect`/`record_split_luma_rect` now delegate to the + new mi variants, so there is one implementation each. + - `motion_mode`/`obmc` CDF row selection: `bsize_idx` is a full `(write_w, write_h)` match + over every shape the decoder can now reach; an unknown shape refuses by name instead of + reading the wrong-width alphabet (class wrong-alphabet-same-value). + - `interintra` is no longer read on a 1:4 strip: `is_interintra_allowed_bsize` is + `BLOCK_8X8..=BLOCK_32X32` in libaom's ENUM ORDER, which excludes BLOCK_8X32 (18) and + BLOCK_32X8 (19) even though both dimensions are in range (class + equal-range-means-unread / symbol the reference never wrote). + - `maybe_read_delta_q`/`_lf`'s `is_whole_sb` is now `bsize == sbSize` (`side == 64 && + write_w == 64 && write_h == 64`), not `side == 64` — a 64x32 strip's `skip` must not + suppress the read. + - inter tile, superblock level: `PARTITION_HORZ`/`VERT`/`HORZ_4`/`VERT_4` arms + (two 64x32/32x64 strips, four 64x16/16x64 ones) with libaom's `i > 0` frame-edge break. + AB at superblock level still refuses, by a new named string. + - inter tile, 32x32 level: `PARTITION_HORZ_4`/`VERT_4` arms (four 32x8 / 8x32 strips, + quarter step 2 mi). + - new counters + accessors: `rect4_32_{horz,vert}_inter_hits`, + `inter_sb_{horz,vert,horz4,vert4}_hits`. + - a local `inter_piece!` macro carries the shared 50-argument call instead of six more copies. +- `crates/ec-av1/src/cdf.rs`, `cdf_state.rs` — `OBMC`/`MOTION_MODE` widened 6 -> 12 rows with + libaom's BLOCK_32X64/64X32/8X32/32X8/16X64/64X16 rows (`default_{obmc,motion_mode}_cdf`, + `entropymode.c:549,562` of the oracle source). +- `crates/ec-av1/src/refusal_inventory.rs` — the SB-level string now names AB only; new + "a motion_mode symbol for a block shape this decoder has no CDF row for". +- `crates/ec-av1/src/stream.rs` — `inter_rect_counters()` + the new gate. +- `crates/ec-av1/examples/decode_probe.rs` — prints the six inter rect counters. + +## Gate + +`a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact` +(stream.rs). 16 attempts x {2 orientations, 4 quantisers, 2 motion steps}, 192x128, 6 frames, +`--min-partition-size=32 --max-partition-size=64 --enable-rect-partitions=1 +--enable-1to4-partitions=1 --lag-in-frames=0 --cpu-used=0` (overrides last, aomenc keeps the +last occurrence). Noiseless split-motion source (one half translating, the other static) is +what makes aomenc's RD pick a superblock HORZ whose strips are `skip`. Every decoded frame is +compared Y/U/V to ffmpeg; refusals are counted, never SKIPped; a decoded attempt that carried +no rect strip is still required to be pixel-exact. + + EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib superblock_level_rect_partition -- --nocapture + +EVIDENCE: $HOME/.cache/inter4-suite.log + `cargo test -p ec-av1 --lib superblock_level_rect_partition` | 16 aomenc encodes, decode + ffmpeg Y/U/V pixel compare over 6 frames each | 8-bit: 4 named refusals, 2 pixel-exact attempts carrying the arm, 64x32 strips=4, 32x64 strips=0, 10 out-of-scope (0 mismatched); gate ok. Full suite at commit 754a7dd: 321 passed / 2 failed / 30 ignored; both failures were stale pins of MINE (the SB refusal string and a line-continuation in a new refusal literal) and are fixed in the follow-up commit -- the suite has NOT been re-run end to end since. + +## Open residue (nothing here is claimed done) + +- **fix-now (r2): rectangular inter residual coding.** Until it exists no gate can cover a + non-skip inter rect strip, and that is 100% of what real content produces. This blocks: + the 32-level 1:4 inter arms (0 hits in every recipe swept), the SB-level VERT arm (fires, + then its second strip is non-skip), the SB-level 1:4 arms, and the whole 10-bit side. +- **deferred: the 10-bit twin of the new gate** — every 10-bit attempt found the strip + non-skip. Unblocked by the item above. Written as an 8-bit-only loop with the reason in + the source, not a weakened assert. +- **deferred: SB-level AB inter partitions** — refused by name, no gate. Unblocked by the + same residue (their pieces are rect too). +- **accepted: `size_group` stays 3 for rect pieces** — inert (it only feeds the intra + `y_mode` branch, which refuses non-square) and it matches the existing 32-level HORZ arm. +- **DO NOT MERGE the two new arms as a capability claim**: the SB-level HORZ arm is gated, + the SB-level VERT/1:4 and the 32-level 1:4 arms are NOT (class refusal-lifted-without-a-gate). diff --git a/lanes/inter4-r2.report.md b/lanes/inter4-r2.report.md new file mode 100644 index 00000000..aa71f368 --- /dev/null +++ b/lanes/inter4-r2.report.md @@ -0,0 +1,128 @@ +# 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) + test result: ok. 323 passed; 0 failed; 31 ignored; finished in 410.27s + +Same 323 passing as the 59ccb01 baseline; the one extra ignored test is this +round's red gate. + +EVIDENCE: $HOME/.cache/inter4-suite-r2.log | ec-av1 --lib under systemd-run at b9dec1f | 323 passed / 0 failed / 31 ignored + +Sibling gates inside that run: inter_sequence*, 8x8_leaf_split, tx_select, +superblock_level_*, obmc, warp, globalmv, force_integer_mv, refusal_inventory, +gate_coverage -- all green. + +## 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. +- **open (not this lane's shape): 1-2 attempts per recipe decode fully with + ZERO rect inter transform units and still MISMATCH ffmpeg** on 192x128 + rect-partition inter content. Proven pre-existing for the banded recipe: with + r1's square skip-context recording restored the same three attempts mismatch + identically, so it is not this round's change. Not bisected (budget). +- **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. diff --git a/lanes/inter4-r3.report.md b/lanes/inter4-r3.report.md new file mode 100644 index 00000000..9c3bbdc5 --- /dev/null +++ b/lanes/inter4-r3.report.md @@ -0,0 +1,125 @@ +# lane-inter4 r3 — the 16x16-level rectangular INTER leaf + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off r2's `d2d7327` (main `11633d7`). No rebase needed (main unchanged since r2). + +## What shipped (commit `d913935`) + +The refusal r2 named as the reach blocker is gone: `PARTITION_HORZ`/`PARTITION_VERT` +at 16x16 on an inter frame now decodes two 16x8 / 8x16 inter blocks. + +- `crates/ec-av1/src/decode.rs` (16-level partition site, ~17930): the HORZ/VERT + arms. `side = SUB` keeps every CDF / prediction-buffer decision square (the + corner-cut the 32-level rect arm already ships), `write_w`/`write_h` carry the + true 16x8 / 8x16 footprint into the mv stack, the motion-mode row, the neighbour + stamps and the rect residual path. AB / 1:4 at 16 refuse by name. +- `rect_inter_residual_supported` + `rect_inter_luma_set` / `rect_inter_chroma_set` + (decode.rs ~9020): 16x8/8x16 joins 32x16/16x32; the residual call sites pick the + TxbSet from the block's TRUE shape instead of the hard-coded 32x16 pair. +- `TxbSet::LumaRect16x8Inter` / `LumaRect16x8InterSet1` (cdf_state.rs): + `LumaRect16x8`'s coefficient tables with the INTER `tx_type` alphabet. + `av1_get_ext_tx_set_type(TX_16X8, is_inter=1, reduced)` = `EXT_TX_SET_DCT_IDTX` + reduced, `EXT_TX_SET_ALL16` otherwise (`tx_size_sqr == TX_8X8`, not TX_16X16), + both at the **TX_8X8** CDF row -- i.e. the existing `inter_tx_type_8` / + `inter_tx_type_8_set1` tables, no new CDF and no new counter-reset entry. + **r2's report was wrong here** (it predicted the 12-symbol + `default_inter_ext_tx_cdf[2][TX_8X8]`); checked against + `blockd.h:1092-1122` + `av1_num_ext_tx_set = {1,2,5,7,12,16}` in the oracle tree. +- **Defect found in shipped code (class: table narrowed to the reachable sizes):** + `eob_pt_128_luma_class1` and `eob_pt_32_chroma_class1` did not exist, so + `LumaRect16x8`/`LumaRect16x8Set1` (the INTRA rect leaf, already shipping) and + `ChromaRect8x4` fell back to the 2D `eob_pt` alphabet for `V_DCT`/`H_DCT` + units. Added from `token_cdfs.h:792-848` (plane 0 / plane 1, class index 1), + wired into all four `LumaRect16x8*` sets, `ChromaRect8x4`, and the per-frame + `reset1` list. +- **Second defect in shipped code:** `obmc_blend`'s `max_nb` closure was + `1..=4 => 2`, while libaom's `max_neighbor_obmc[] = {0,1,2,3,4,4}` indexed by + `mi_size_{wide,high}_log2` gives 0 for 1 mi and 1 for 2 mi. Only a block under + 16 px on that axis can expose it -- i.e. exactly this round's leaves. +- `size_group_wh` (decode.rs): `y_mode` (intra block in an inter frame) and the + `interintra` / `interintra_mode` rows now come from `size_group_lookup[bsize]` + of the block's TRUE footprint. The 32-level rect strips were reading the square + row (3 where libaom says 2); a 16x8 leaf would have read 2 where libaom says 1. + Deviation from charter: not requested, but it is the same defect shape and one + helper covers every caller. +- `MOTION_MODE` / `OBMC` CDFs extended from 12 to 14 packed rows with libaom's + `BLOCK_8X16` (index 4) and `BLOCK_16X8` (index 5) entries. + +## Gate — GREEN + +`a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_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=8 --max-partition-size=16 +--enable-obmc=0`, per-arm overrides LAST. Every decoded frame compared Y/U/V vs +ffmpeg; a refusal is counted, never SKIPped; an attempt carrying no 16-level rect +leaf is still required pixel-exact (`oos_mismatch == 0`). Hard asserts: a +pixel-exact attempt carrying a 16x8 leaf AND one carrying an 8x16 leaf, per bit +depth, plus at least one coded (non-skip) rectangular inter transform unit across +the two depths. + + cargo test -p ec-av1 --lib 16_level_rect_leaf -- --nocapture + +EVIDENCE: $HOME/.cache/inter4-suite-r3.log (gate line) | 32 aomenc encodes, decode + ffmpeg Y/U/V compare of every frame | 8-bit: 6 refusals, 5 pixel-exact leaf-carrying attempts, 16x8=3, 8x16=2, coded rect TUs=2, 0 mismatches; 10-bit: 2 refusals, 4 leaf-carrying attempts, 16x8=2, 8x16=3, 0 mismatches + +## Refusals + +Lifted: `"an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter +leaves are not coded yet)"`. + +Added (both in `refusal_inventory.rs`, both named, both narrow): + +- `"an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; ...)"` +- `"OBMC on a 16x8/8x16 inter leaf (blend mismatches the reference on this shape)"` + +## The OBMC residue (open, instrumented) + +With `--enable-obmc=1` and everything else identical, attempt 10 (8-bit, cq 22, +tx-size-search off) decodes all 6 frames but frame 5 has **5302 luma pixels +wrong, max |delta| 84, first at (176,0)**; frames 0-4 are exact. The same recipe +with `--enable-obmc=0` decodes 5 leaf-carrying attempts pixel-exact, and a run +with obmc/warp/interintra/masked-compound ALL off is also exact -- re-enabling +obmc alone reproduces it, so warp, interintra and masked compound are exonerated +for this shape. The blend geometry in `obmc_blend` was checked element by element +against libaom `build_obmc_inter_pred_above`/`_left` and +`av1_skip_u4x4_pred_in_obmc` and matches for these shapes; `max_neighbor_obmc` +was wrong and is fixed, but the fix left the mismatch byte-identical, so the +cause is upstream of the blend (the neighbour walk's `size`/`size_h` stamps for a +rect leaf, or `has_top_right`, whose doc still says "no rectangular partition +ever produces an inter leaf here"). Refused by name rather than shipped. + +EVIDENCE: gate run with `--enable-obmc=1` | same 16 attempts, decode + ffmpeg compare | attempt 10 frame 5: 5302 luma pixels differ, max |delta| 84; with `--enable-obmc=0`: 0 mismatches over 5 leaf-carrying attempts + +## Suite + + $HOME/.cache/inter4-suite-r3.log (systemd user unit inter4-suite-1788315557) + test result: ok. 324 passed; 0 failed; 31 ignored; finished in 412.37s + +Same 323 as r2's baseline plus this round's new gate; the one ignored addition +is still r2's own 32x16/16x32 gate. Sibling gates inside that run: every +`inter_sequence*`, `8x8_leaf_split`, `tx_select`, `superblock_level_rect_partition`, +`obmc`, `warp`, `globalmv`, `force_integer_mv`, `refusal_inventory`, +`gate_coverage` -- all green, including the ones that read the tables this round +touched (`MOTION_MODE`/`OBMC` rows, `LumaRect16x8*`, `ChromaRect8x4`). + +EVIDENCE: $HOME/.cache/inter4-suite-r3.log | ec-av1 --lib under a systemd user unit at d913935 | 324 passed / 0 failed / 31 ignored + +## Residue + +- **fix-now (r4): OBMC on a 16x8/8x16 leaf** -- named refusal today. Next step is + `has_top_right` for rect inter blocks (libaom's `xd->width < xd->height` / + `> ` / `PARTITION_VERT_A` branches are dropped in our copy) and the + `overlappable_above/left` step caps (`AOMMIN(xd->width, mi_size_wide[nb])`). +- **deferred: r2's 32x16/16x32 gate** (`..._with_a_coded_rectangular_residual_...`) + -- still `#[ignore]`d; not re-measured this round (budget). With the 16-level + leaves reachable it may now get past its first rect strip; unblocked by simply + re-running it, which r4 should do before anything else. +- **deferred: 16x16 SPLIT under this recipe** -- the gate counts `16x16 SPLITs=0` + on every attempt (aomenc picks NONE/HORZ/VERT at 16 here); the 8x8-leaf path is + gated by its own sibling test, so the count is printed, not asserted. +- **accepted: the 10-bit arm proves no residual** -- every 10-bit rect leaf in + this recipe is `skip` at cq 34/22, and cq 30/26 or 24/12 stops reaching a rect + leaf at all (measured). The residual half is asserted across both depths. +- **accepted: `_size_group` is now a dead parameter** of `decode_inter_block` + (superseded by `size_group_wh`), kept rather than editing twenty call sites. diff --git a/lanes/inter4-r4.report.md b/lanes/inter4-r4.report.md new file mode 100644 index 00000000..ee12df72 --- /dev/null +++ b/lanes/inter4-r4.report.md @@ -0,0 +1,142 @@ +# lane-inter4 r4 — OBMC on a 16x8/8x16 inter leaf (refusal lifted, gated) + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off r3's `96847a3`, with `lane-interbis` (`8a6bede`, `build_motion_field`'s compound +slot walk) merged FIRST as chartered. + +## TASK 1 — r2's ignored 32x16/16x32 gate: re-measured, STILL RED, blocker moved + + cargo test -p ec-av1 --lib coded_rectangular_residual -- --ignored --nocapture + +`a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact` +still cannot prove itself: over its 16 8-bit attempts, **12 named refusals** — 10 of +them `"an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder +does not code yet"` and 2 `"an inter 16x16-level AB or 1:4 partition ..."` — and the +other 4 attempts decode with **zero** rect inter residual (`tu=0`, `split=0`, 0 +mismatches). So the 16-level leaf landing in r3 did NOT unblock it: what stops these +streams now is rectangular *intra* prediction, another lane's refusal. Kept `#[ignore]`, +with the reason string replaced by that measurement (stream.rs:4902). + +EVIDENCE: $HOME/.cache/inter4-t1.log | 16 aomenc encodes, decode + counter read | 12 named refusals (10 intra-rect-strip, 2 inter AB/1:4), 4 attempts with tu=0/split=0, 0 mismatches + +## TASK 2 — the OBMC residue: no defect left; refusal lifted + +r3 refused `"OBMC on a 16x8/8x16 inter leaf (blend mismatches the reference on this +shape)"` off a measured 5302-luma-pixel mismatch (attempt 10, 8-bit, cq 22, frame 5). +Re-measured on THIS tree before touching any code: + +- Rebuilt that exact stream from the gate's attempt-10 recipe with `--enable-obmc=1` + (`scratchpad/o10.obu`, md5 `b643a93a8db45e2a1b89b2d777147ee3`, 828 B). +- Added an `EC_OBMC` rung to the oracle `aomdec` + (`dec_build_prediction_by_above_pred` / `_left_pred`, printing the block, the + neighbour's rel position, `op_mi_size`, mv, ref, bsize, filter) and the matching + rung to our `obmc_blend`, then compared. + +Both decoders emit **exactly 9 OBMC neighbour invocations**, in the same order, with +identical block shape, `off4`/`rel`, `span4`/`op_mi_size`, neighbour mv, ref frame and +filter — including the three on `wh=(8x16)` leaves. And every one of the six +`EC_AV1_PREFILT_DUMP` frames is **byte-identical** between our decoder and aomdec +(luma diff 0 on f0..f5). There is nothing left to fix on this shape: the mismatch r3 +saw is gone. The only decode-path change between r3's measurement and this one is the +lane-interbis merge (temporal MV candidates); not bisected further. + +EVIDENCE: scratchpad/{ours.obmc,ref.obmc,ours.yuv.f0-5,ref.yuv.f0-5} | EC_OBMC + EC_AV1_PREFILT_DUMP on o10.obu, ours (release decode_probe) vs instrumented aomdec | 9 vs 9 identical neighbour lines; per-frame luma diff 0/0/0/0/0/0 + +### What shipped + +- `crates/ec-av1/src/decode.rs` (`obmc_blend`, ~12843): the `(16,8)|(8,16)` refusal + deleted; in its place the new `OBMC_RECT_LEAF_HITS` counter (+ `obmc_rect_leaf_hits()` + at ~1355) that the gate reads. +- `crates/ec-av1/src/refusal_inventory.rs`: the OBMC-rect-leaf string removed. +- `crates/ec-av1/src/stream.rs` (`..._with_a_16_level_rect_leaf_...`, ~5090): the sweep + runs **32 attempts** now — the same 16 (2 sources x 2 quantisers x 2 tx-size-search + arms x 2 motion steps) with `--enable-obmc=0`, then repeated with `--enable-obmc=1` + as the LAST flag. New hard assert per bit depth: `obmc_leaf_proved > 0`. +- `crates/ec-av1/src/stream.rs` ~1948: the hidden-frames gate's `--enable-obmc=0` + comment no longer cites a refusal that does not exist. + +### Gate — GREEN + + cargo test -p ec-av1 --lib 16_level_rect_leaf -- --nocapture + +- 8-bit: 15 named refusals, 9 pixel-exact leaf-carrying attempts (16x8=5, 8x16=4), + whole-block rect TUs=4, **OBMC blends on a rect leaf=10**, 8 attempts carried none + (0 mismatched). +- 10-bit: 4 named refusals, 8 pixel-exact leaf-carrying attempts (16x8=4, 8x16=6), + **OBMC blends on a rect leaf=4**, 20 carried none (0 mismatched). + +EVIDENCE: $HOME/.cache/inter4-g4.log | 64 aomenc encodes (32 attempts x 2 depths), every decoded frame Y/U/V vs ffmpeg | test result: ok. 1 passed; 0 failed; OBMC-on-rect-leaf blends 10 (8-bit) / 4 (10-bit), 0 mismatches + +## Verifier findings folded in (r4, after the OBMC commit) + +1. **`size_group_wh` was wrong for a 4-px side** (decode.rs ~9126): libaom + `size_group_lookup[BLOCK_SIZES_ALL]` (`common_data.h:60`) is **0** for + BLOCK_4X4/4X8/8X4/4X16/16X4, and our `0..=8 => 1` row gave those group 1 -- + the `y_mode` / `interintra` / `interintra_mode` CDF row of every sub-8 leaf. + Fixed, and pinned by a new unit test `size_group_wh_matches_libaom_size_group_lookup` + that enumerates all 22 `BLOCK_SIZES_ALL` entries against the transcribed table + (class enumerate-the-table-domain). + + cargo test -p ec-av1 --lib size_group_wh_matches -- --nocapture + +2. **rect var-tx SPLIT and the 10-bit coded rect TU are shipped unexercised.** + Swept cq {8,12,16,22} x both source axes x both depths with tx-size-search on, + reading `decode_probe`'s new `rect_inter: tu=.. txsplit=.. obmc_leaf=..` line: + `txsplit=0` in every single decoding attempt, and every 10-bit rect leaf is + `skip` (`tu=0`) at every cq that decodes at all. Below cq 22 the attempts stop + at another lane's refusal -- mostly `"a HORZ/VERT intra strip below 16x16 with + a split transform (per-unit rect prediction is not ported)"`, plus the sub-16 + `HORZ_A/HORZ_B/VERT_A` and 32-level 1:4 ones. Deviation from the verifier's + ask, stated: I did NOT add an `#[ignore]`d pin -- an ignored test that runs + nothing carries the same information as the measurement now written into the + gate's own comment (stream.rs ~5097) and into the residue below, at less code. + The asserts stay where the feature does fire (8-bit `tu_total > 0`). + +3. `stream.rs` "aomenc keeps the last occurrence of a repeated `--enable-*` flag" + is CORRECT (class aomenc-first-flag-wins is about `--enable-*` repeats resolving + to the last one, and it is what the r4 obmc arm relies on) -- left unchanged. + +4. `cdf.rs` doc slip fixed: `EOB_PT_128_CHROMA_CLASS1_Q0` had lost its doc comment + to the `EOB_PT_128_LUMA_CLASS1_Q0` block added in r3; moved back. + +EVIDENCE: sweep output in this round's transcript | 16 aomenc encodes (cq 8/12/16/22 x 2 axes x 8/10-bit) decoded through release decode_probe | txsplit=0 in all 7 decoding attempts, 10-bit tu=0 in all 4, 8-bit cq22 tu=1 txsplit=0 obmc_leaf=1 + +## Refusals + +Lifted: `"OBMC on a 16x8/8x16 inter leaf (blend mismatches the reference on this shape)"`. +None added. + +## Suite + + $HOME/.cache/inter4-suite-r4.log + + test result: ok. 326 passed; 0 failed; 31 ignored; finished in 776.14s + +r3's 324 + the lane-interbis gate + this round's `size_group_wh` unit test; the 31 +ignored are unchanged (still including r2's 32x16/16x32 gate). Every sibling ran in +it: `obmc*`, `16_level_rect_leaf`, `superblock_level_rect_partition`, +`inter_sequence*`, `temporal_mv_candidates`, `refusal_inventory`, `gate_coverage`. + +EVIDENCE: $HOME/.cache/inter4-suite-r4.log | ec-av1 --lib under a systemd user unit at b0588e4 + this report | 326 passed / 0 failed / 31 ignored + +## Film + +`scratchpad/hg-head.obu` through the release `decode_probe` on this lane still stops at +`unsupported: AV1 tile (filter intra on a HORZ/VERT strip (this decoder predicts +square-only))` — an intra refusal owned by another lane, unchanged by this round. + +EVIDENCE: scratchpad/hg-head.obu | release decode_probe under a 6G scope | REFUSED: filter intra on a HORZ/VERT strip + +## Residue + +- deferred: r2's 32x16/16x32 rect-residual gate — still `#[ignore]`d — unblocked by + rectangular INTRA prediction (`an intra-coded HORZ/VERT strip ...`) landing, not by + anything in this lane. +- accepted: which change fixed r3's OBMC mismatch is not bisected (interbis merge is the + only candidate); the shape is now proven exact against an instrumented aomdec, so the + question is archaeology, not a defect. +- deferred: the rect var-tx SPLIT path and a coded 10-bit rect TU are unexercised -- + unblocked by the sub-16 intra-rect-strip refusal landing (every lower-cq attempt + stops there before a rect inter leaf can carry a split tree). +- accepted: `16x16 SPLITs=0` under this recipe (aomenc picks NONE/HORZ/VERT at 16); + covered by the 8x8-leaf sibling gate. diff --git a/lanes/interbis-r1.report.md b/lanes/interbis-r1.report.md new file mode 100644 index 00000000..5d3293d0 --- /dev/null +++ b/lanes/interbis-r1.report.md @@ -0,0 +1,129 @@ +# lane-interbis r1 — the "decodes fully, still mismatches" inter defect + +Branch `lane-interbis`, worktree `edith_codecs-interbis`, off lane-inter4 `d2d7327`. +No rebase (main unchanged since that base). + +## STEP 1 — reproduced and pinned + +The rect gate's 8-bit **attempt 1** is the one that decodes fully and mismatches: +192x128, 6 frames @25, `geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)'`, cq 34, +`--enable-tx-size-search=1`, `--min/max-partition-size=16/32`, cpu-used=0, lag 0. +Regenerated twice, byte-identical: +`fa70b7f68d311e577e3d14a86574909e6e58cac817b5a7fae04341c41ff50260` +(script `$HOME/.cache/interbis/gen.sh`; 10-bit twin +`67cad9bd5341db897de8a5308faecaedb1b0df761e4f315f1817156d124caef7`). + +Decode order == display order (no hidden frames; `--lag-in-frames=0`). +Frames 0..4 exact; **frame 5** luma only, 646 px, bbox x160-191 y93-127, max delta 39. +`EC_AV1_PREFILT_DUMP` (ours) vs the same rung from the instrumented aomdec: +frames 0-4 byte-identical, frame 5 differs in 640 luma px at x160-191 y96-127 — +i.e. **reconstruction**, not deblock/CDEF/LR, and exactly one 32x32 block: +mi (row 24, col 40), the frame's last block. + +EVIDENCE: $HOME/.cache/interbis/{o_pre.f5,a_pre.f5} | EC_AV1_PREFILT_DUMP ours vs aomdec, per-frame byte diff | frames 0-4 identical, frame 5 640 luma px wrong in the single 32x32 block at mi(24,40) + +## STEP 2 — first divergent element + +Entropy is **exact**: the msac range ladder agrees at that block's entry +(`EC_MODE ... rng=37852` both) and at the end of its mode read +(`rng=59818` both). Both decoders read mode 13 (NEARESTMV), ref0=2 (LAST2), +stack size 3. The **VALUE** differs: + + ours EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,72) + aomdec EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,-230) + +New `EC_STACK` rung (added to both decoders) shows entries 1 and 2 identical +(`(0,24) w=2`, `(0,-785) w=2`, the extra-search neighbours) and entry 0 — +the temporal (MFMV) candidate — wrong: ours `(0,72) w=32`, aomdec `(0,-230) w=16`. + +New `EC_TPL` rung (per `add_tpl_ref_mv` probe, both decoders) isolates it to the +projected motion field itself: over the 16 probes of that block, aomdec reads +`INVALID` at blk_col 0/2 and `mfmv0=(0,-230) rfo=3` at blk_col 4/6; ours reads +`mfmv0=(0,24) rfo=1` at all 16. `(0,24)*3/1 = (0,72)` — our wrong stored pair +projected exactly to the wrong candidate. + +EVIDENCE: $HOME/.cache/interbis/{o_tpl.txt,a_tpl.txt} | EC_TRACE_MODE + EC_TRACE_TPL on both decoders, block mi(24,40) of frame 5 | ours mfmv0=(0,24) rfo=1 x16 vs aomdec INVALID x8 + (0,-230) rfo=3 x8; stack entry 0 (0,72) vs (0,-230) + +## Root cause (decode.rs `build_motion_field`, spec 7.19 / libaom `av1_copy_frame_mvs`) + +Our per-frame saved motion field stored **`ref_frame[0]`/`mv[0]` of every inter +block**. libaom walks **both** reference slots and the **last qualifying one +wins**, skipping a slot when + +* `cm->ref_frame_side[ref]` is non-zero — the reference's OrderHint is ahead of + (or equal to) this frame's (`av1_calculate_ref_frame_side`), or +* `|mv| > REFMVS_LIMIT` (`(1<<12)-1`). + +Every compound block in this stream is `LAST + GOLDEN` (both past), so libaom +stores GOLDEN's mv with `ref_frame_offset = 3` where we stored LAST's with +offset 1 — a wrong (mv, distance) pair in every compound block's 8x8 cell, which +the next frame's temporal candidate then projects with the wrong reference +distance. Class name: **saved-field-keeps-slot-0** — a per-frame/DPB *summary* +of a multi-slot field must replay the reference's own slot walk (order + skips), +not keep slot 0. (Sibling of `neighbour-votes-all-its-fields`: there the +consumer voted only one slot, here the producer stores only one.) + +Fix: `crates/ec-av1/src/decode.rs:1728-1800` (`build_motion_field` now takes +`order_hint_bits`, walks both slots last-wins, applies the side and +`REFMVS_LIMIT` skips); call site `decode.rs:19040`. + +## Sweep + +`build_motion_field` is the only writer of `MotionField`/`SavedMv` +(`grep -rn "SavedMv\|MotionField" crates/ec-av1/src`); the mv-stack neighbour +maps already carry both slots (`MiInfo::ref_frame1`/`mv1`), and +`motion_field_projection`/`setup_motion_field` were re-read line-for-line +against `mvref_common.c` this round and match (one known, unreached gap noted +below). + +## Gate — GREEN, and it binds + +`a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact` +(`crates/ec-av1/src/stream.rs`, next to the rect gate): the pinned recipe above, +2 tx-size-search arms x {8-bit, 10-bit}, every fully decoded attempt compared +Y/U/V against ffmpeg, refusals counted (never SKIPped), and `decode::tmv_hits()` +asserted > 0 per depth. + + cargo test -p ec-av1 --lib temporal_mv_candidates -- --nocapture + 8-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 66 + 10-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 67 + test result: ok. 1 passed; 0 failed + +EVIDENCE: $HOME/.cache/interbis-tmvgate.log | cargo test -p ec-av1 --lib temporal_mv_candidates | 8-bit + 10-bit pixel-exact, tmv counter 66/67 + +Negative control (gate binds): with the store put back to first-slot-wins the +same gate fails at `frame 5 luma vs ffmpeg (attempt 1, 8-bit)`. + +EVIDENCE: $HOME/.cache/interbis-tmvgate-neg.log | one-line revert to `if saved.is_none()` then re-run the gate | FAILED, frame 5 luma, restored immediately after + +## Instruments added (env-gated, both decoders) + +- ours: `EC_MODE_VAL` + `EC_STACK` on the single-ref path of `decode_inter_block` + (byte-format-identical to the oracle's rung), `EC_TPL` per `add_tpl_ref_mv` probe. +- oracle (`~/.cache/aom-oracle/src`): `EC_STACK` (stack dump at `EC_MODE_VAL`) and + `EC_TPL` (per probe, incl. the `INVALID_MV` arm); `ninja aomdec` rebuilt. + +## Residue + +- **accepted: `motion_field_projection` does not check the source frame's + frame_type.** libaom returns 0 for a KEY/INTRA_ONLY source; here an intra + frame's saved field has no cells set, so the projection is inert — but its + *return value* (which feeds `ref_stamp`) can differ. Unreached on every stream + swept; fix-now if a future stream shows a `ref_stamp` divergence. +- **deferred: the rect inter residual gate** stays `#[ignore]`d (lane-inter4's + own residue, unblocked by 16x8/8x16 rect inter leaves); its + `out_of_scope_mismatch` assert is what surfaced this defect and is now + satisfiable on the 8-bit arm. +- **deferred: film probe** — this diff lifts no refusal; both films still stop at + lane-rectchroma's intra-rect-strip refusal. + +## Suite + + $HOME/.cache/interbis-suite.log (systemd-run unit, MemoryMax=10G) + test result: ok. 324 passed; 0 failed; 31 ignored; finished in 443.08s + +323 (lane-inter4 r2 baseline) + this round's new gate. Siblings inside that run: +inter_sequence*, obmc, warp, globalmv, compound_*, altref/hidden-frame, +tx_select, refusal_inventory, gate_coverage — all green. + +EVIDENCE: $HOME/.cache/interbis-suite.log | ec-av1 --lib at 0527911 | 324 passed / 0 failed / 31 ignored