diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 1967c2a6..7c690293 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -4749,6 +4749,30 @@ pub const EOB_PT_16_LUMA_Q3: [u16; 6] = [6708, 8958, 14746, 22133, 32768, 0]; /// `V_DCT`/`H_DCT` (lane-av1tx4 r5: the class dimension libaom always keeps, /// this crate never carried at all until a real aomdec trace showed the /// desync starting exactly at this read). +/// `av1_default_eob_multi32_cdfs` (libaom `token_cdfs.h`), luma plane, 2D tx +/// class: the end-of-block group of a 32-position transform -- the +/// `TX_4X8`/`TX_8X4` pair this decoder reaches through +/// [`crate::cdf_state::TxbSet::LumaRect4x8`] (lane-tx4x8). Q-context 2 +/// (`base_q_idx` 61..=120) is the unsuffixed name, as everywhere else here. +pub const EOB_PT_32_LUMA_Q0: [u16; 7] = [400, 520, 977, 2102, 6542, 32768, 0]; +/// [`EOB_PT_32_LUMA_Q0`]'s q-context 1 (`base_q_idx` 21..=60) sibling. +pub const EOB_PT_32_LUMA_Q1: [u16; 7] = [989, 1249, 2019, 4151, 10785, 32768, 0]; +/// [`EOB_PT_32_LUMA_Q0`]'s q-context 2 (`base_q_idx` 61..=120) sibling. +pub const EOB_PT_32_LUMA: [u16; 7] = [2515, 3003, 4452, 8162, 16041, 32768, 0]; +/// [`EOB_PT_32_LUMA_Q0`]'s q-context 3 (`base_q_idx` 121..=255) sibling. +pub const EOB_PT_32_LUMA_Q3: [u16; 7] = [4617, 5709, 8446, 13584, 23135, 32768, 0]; +/// [`EOB_PT_32_LUMA`]'s `TX_CLASS_HORIZ`/`TX_CLASS_VERT` sibling (the `[1]` +/// row of the same libaom table), read instead whenever the TU's `tx_type` +/// is `V_DCT`/`H_DCT` -- reachable at 4x8/8x4 because that size's intra +/// `tx_type` set is `EXT_TX_SET_DTT4_IDTX_1DDCT`, which carries both. +pub const EOB_PT_32_LUMA_CLASS1_Q0: [u16; 7] = [210, 405, 1315, 3326, 7537, 32768, 0]; +/// [`EOB_PT_32_LUMA_CLASS1_Q0`]'s q-context 1 sibling. +pub const EOB_PT_32_LUMA_CLASS1_Q1: [u16; 7] = [313, 441, 1099, 2917, 8562, 32768, 0]; +/// [`EOB_PT_32_LUMA_CLASS1_Q0`]'s q-context 2 sibling. +pub const EOB_PT_32_LUMA_CLASS1: [u16; 7] = [574, 821, 1836, 5089, 13128, 32768, 0]; +/// [`EOB_PT_32_LUMA_CLASS1_Q0`]'s q-context 3 sibling. +pub const EOB_PT_32_LUMA_CLASS1_Q3: [u16; 7] = [1156, 1702, 3675, 9274, 20539, 32768, 0]; + pub const EOB_PT_16_LUMA_CLASS1_Q0: [u16; 6] = [370, 671, 1883, 4471, 32768, 0]; pub const EOB_PT_16_LUMA_CLASS1_Q1: [u16; 6] = [513, 765, 1859, 6339, 32768, 0]; pub const EOB_PT_16_LUMA_CLASS1: [u16; 6] = [716, 1105, 2646, 10056, 32768, 0]; diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 97d113a9..3f53b485 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -172,6 +172,20 @@ pub(crate) enum TxbSet { /// [`ChromaRect16x8`](TxbSet::ChromaRect16x8) has to `Chroma16`, one size /// class down. ChromaRect8x4, + /// The luma 4x8/8x4 transform of a `PARTITION_VERT`/`HORZ` leaf under an + /// 8x8 block (lane-tx4x8), under this encoder's `reduced_tx_set`. + /// `get_txsize_entropy_ctx` ((`txsize_sqr_map` + `txsize_sqr_up_map` + 1) + /// >> 1) resolves `TX_4X8` to `TX_8X8`, so every coefficient table here is + /// [`Luma8`](TxbSet::Luma8)'s -- except `eob_pt`, a true 32-position + /// alphabet ([`crate::cdf::EOB_PT_32_LUMA`]), and `tx_type`, whose CDF row + /// is `txsize_sqr_map[TX_4X8]` = `TX_4X4` (libaom `read_tx_type`'s + /// `square_tx_size`), i.e. [`Luma4`](TxbSet::Luma4)'s own table. + LumaRect4x8, + /// [`LumaRect4x8`](TxbSet::LumaRect4x8)'s `reduced_tx_set: false` + /// counterpart: `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_8X8`, + /// `tx_size_sqr == TX_4X4`, intra returns `EXT_TX_SET_DTT4_IDTX_1DDCT`, + /// the same seven-symbol set (and same `TX_4X4` row) `Luma4Set1` reads. + LumaRect4x8Set1, } /// The tables one transform block is coded with, borrowed from the state for @@ -277,6 +291,11 @@ pub(crate) struct Cdfs { pub eob_pt_1024_luma_class1: [u16; 12], /// `eob_pt_1024_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. pub eob_pt_1024_chroma_class1: [u16; 12], + /// The end-of-block group of a 32-position (4x8/8x4) luma transform + /// (lane-tx4x8). + pub eob_pt_32_luma: [u16; 7], + /// `eob_pt_32_luma`'s class-1 sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_32_luma_class1: [u16; 7], /// The end-of-block offset bit of a 16x16 luma transform. pub eob_extra_luma_16: [[u16; 3]; 9], /// The same, for an 8x8 luma transform. @@ -701,6 +720,8 @@ impl Cdfs { reset1(&mut self.eob_pt_512_chroma_class1); reset1(&mut self.eob_pt_1024_luma_class1); reset1(&mut self.eob_pt_1024_chroma_class1); + reset1(&mut self.eob_pt_32_luma); + reset1(&mut self.eob_pt_32_luma_class1); reset2(&mut self.eob_extra_luma_16); reset2(&mut self.eob_extra_luma_8); reset2(&mut self.eob_extra_luma_4); @@ -917,6 +938,20 @@ impl Cdfs { cdf::EOB_PT_16_LUMA_CLASS1, cdf::EOB_PT_16_LUMA_CLASS1_Q3, ), + eob_pt_32_luma: pick( + q_ctx, + cdf::EOB_PT_32_LUMA_Q0, + cdf::EOB_PT_32_LUMA_Q1, + cdf::EOB_PT_32_LUMA, + cdf::EOB_PT_32_LUMA_Q3, + ), + eob_pt_32_luma_class1: pick( + q_ctx, + cdf::EOB_PT_32_LUMA_CLASS1_Q0, + cdf::EOB_PT_32_LUMA_CLASS1_Q1, + cdf::EOB_PT_32_LUMA_CLASS1, + cdf::EOB_PT_32_LUMA_CLASS1_Q3, + ), eob_pt_64_luma_class1: pick( q_ctx, cdf::EOB_PT_64_LUMA_CLASS1_Q0, @@ -1652,6 +1687,30 @@ impl Cdfs { tx_type: None, eob_pt_class1: Some(&mut self.eob_pt_128_chroma_class1), }, + TxbSet::LumaRect4x8 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_32_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_4[mode].as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_32_luma_class1), + }, + TxbSet::LumaRect4x8Set1 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_32_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_4_set1[mode].as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_32_luma_class1), + }, TxbSet::ChromaRect32x16 => TxbTables { side: 32, txb_skip: &mut self.txb_skip_chroma_32, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 14ea6e99..897b1831 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1713,6 +1713,54 @@ thread_local! { pub(crate) fn sub8_split_hits() -> usize { SUB8_SPLIT_HITS.with(|c| c.get()) } + +// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ` +// of an 8x8 block) this thread's decode reconstructed with REAL coefficients +// -- a skipped leaf exercises the prediction and the mi bookkeeping but never +// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate +// asserts on these two rather than a plain leaf count. +thread_local! { + static TX4X8_CODED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static TX8X4_CODED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's + /// two 4x4 transform units, predicted one after the other. A separate + /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so + /// the gate can prove THIS path fired. + static RECT8_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// 16x8/8x16 intra strips whose prediction actually read past the block's + /// own width (above-right) or height (below-left) -- the samples + /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/ + /// `has_bl_*` table row can corrupt (lane-tx4x8 r3). + static RECT_STRIP_REACH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Every 16x8/8x16 intra strip predicted, reaching or not -- the + /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of. + static RECT_STRIP_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT8_SPLIT_TX_HITS`]. +pub(crate) fn rect8_split_tx_hits() -> usize { + RECT8_SPLIT_TX_HITS.with(|c| c.get()) +} + +/// Current value of [`RECT_STRIP_PRED_HITS`]. +pub(crate) fn rect_strip_pred_hits() -> usize { + RECT_STRIP_PRED_HITS.with(|c| c.get()) +} + +/// Current value of [`RECT_STRIP_REACH_HITS`]. +pub(crate) fn rect_strip_reach_hits() -> usize { + RECT_STRIP_REACH_HITS.with(|c| c.get()) +} + +/// Current value of [`TX4X8_CODED_HITS`]. +pub(crate) fn tx4x8_coded_hits() -> usize { + TX4X8_CODED_HITS.with(|c| c.get()) +} + +/// Current value of [`TX8X4_CODED_HITS`]. +pub(crate) fn tx8x4_coded_hits() -> usize { + TX8X4_CODED_HITS.with(|c| c.get()) +} const SUB_MI: u32 = 4; const MI: usize = 4; const SB: usize = 64; @@ -1808,10 +1856,20 @@ fn default_scan(side: usize) -> Vec { /// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk /// transposed (column 0 down every row, then column 1, ...). fn class_scan_table(side: usize, class: TxClass) -> Vec { + class_scan_table_wh(side, side, class) +} + +/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against +/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/ +/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding +/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was +/// transcribed with -- `mrow` is the plain row-major raster in our indexing +/// and `mcol` its transpose, at rect sizes exactly as at square ones. +fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec { match class { - TxClass::Vert => (0..(side * side) as u16).collect(), - TxClass::Horiz => (0..side) - .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16)) + TxClass::Vert => (0..(w * h) as u16).collect(), + TxClass::Horiz => (0..w) + .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16)) .collect(), TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"), } @@ -2025,6 +2083,21 @@ const SCAN_16X32: [u16; 512] = [ 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511, ]; +/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major +/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which +/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from +/// the same source). +const SCAN_4X8: [u16; 32] = [ + 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, + 23, 26, 29, 27, 30, 31, +]; + +/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`]. +const SCAN_8X4: [u16; 32] = [ + 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7, + 29, 22, 15, 30, 23, 31, +]; + /// `Default_Scan_16x8`, this decoder's own row-major transcription (see /// [`SCAN_32X16`]'s doc comment). const SCAN_16X8: [u16; 128] = [ @@ -2086,26 +2159,6 @@ const SCAN_8X32: [u16; 256] = [ 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252, 239, 246, 253, 247, 254, 255, ]; -/// `Default_Scan_8x4` (lane-rectx, see [`SCAN_32X16`]'s doc comment for the -/// transposition rule this repo's `SCAN_WxH` names follow): this repo's -/// `(w=8, h=4)` reads libaom's own `default_scan_4x8` verbatim -- the same -/// axis swap [`SCAN_16X8`]/[`SCAN_8X16`] already carry one size class up -/// (repo `SCAN_16X8` == libaom `default_scan_8x16`, repo `SCAN_8X16` == -/// libaom `default_scan_16x8`), checked against `scan.c` before landing -/// rather than re-deriving the zigzag formula. -const SCAN_8X4: [u16; 32] = [ - 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7, - 29, 22, 15, 30, 23, 31, -]; - -/// `Default_Scan_4x8` (lane-rectx): this repo's `(w=4, h=8)` reads libaom's -/// own `default_scan_8x4` verbatim, the same transposition [`SCAN_8X4`]'s -/// doc comment explains. -const SCAN_4X8: [u16; 32] = [ - 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, - 23, 26, 29, 27, 30, 31, -]; - /// `Default_Scan_16x4`, this decoder's own row-major transcription of /// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA /// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level @@ -2144,30 +2197,63 @@ fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i /// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for /// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs /// [`decode_block_rect`] codes (see that function's own doc comment). -fn base_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize { - if row == 0 && col == 0 { +fn base_ctx_rect( + grid: &[i32], + w: usize, + h: usize, + row: usize, + col: usize, + class: TxClass, +) -> usize { + // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only + // the 2D class short-circuits the DC position. + if class == TxClass::TwoD && row == 0 && col == 0 { return 0; } - const OFFSETS: [(usize, usize); 5] = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]; - let mag: i32 = OFFSETS + let offsets: [(usize, usize); 5] = match class { + TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)], + TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)], + TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)], + }; + let mag: i32 = offsets .iter() .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3)) .sum(); let ctx = ((mag + 1) >> 1).min(4) as usize; - if w < h && row < 2 { - return ctx + 11; - } - if w > h && col < 2 { - return ctx + 16; + match class { + TxClass::TwoD => { + if w < h && row < 2 { + return ctx + 11; + } + if w > h && col < 2 { + return ctx + 16; + } + ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize + } + // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s + // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the + // position along one axis only). + TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), + TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), } - ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } /// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the /// neighbour-offset math itself is shape-independent, only the boundary /// clamp needs the real bound in each axis. -fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize { - let extra = neighbour_rect(grid, w, h, row + 1, col + 1).abs(); +fn br_ctx_rect( + grid: &[i32], + w: usize, + h: usize, + row: usize, + col: usize, + class: TxClass, +) -> usize { + let extra = match class { + TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(), + TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(), + TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(), + }; let mag = neighbour_rect(grid, w, h, row + 1, col).abs() + neighbour_rect(grid, w, h, row, col + 1).abs() + extra; @@ -2175,7 +2261,12 @@ fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usiz if row == 0 && col == 0 { return mag; } - if row < 2 && col < 2 { mag + 7 } else { mag + 14 } + let near_origin = match class { + TxClass::TwoD => row < 2 && col < 2, + TxClass::Horiz => col == 0, + TxClass::Vert => row == 0, + }; + if near_origin { mag + 7 } else { mag + 14 } } fn dc_vote(dc: Option) -> i32 { @@ -2530,30 +2621,28 @@ fn read_coeffs_rect( sign_ctx: usize, default_tx_type: TxType, ) -> Result<(Vec, TxType)> { - let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some(); + let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some(); let mut grid = vec![0i32; w * h]; let entry_rng = dec.debug_state().0; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); + if rect_trace { eprintln!( - "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}", - all_zero as i32 + "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}", + all_zero as i32, + dec.debug_state().0 ); } if all_zero { return Ok((grid, TxType::DctDct)); } - let trace = std::env::var_os("EC_TRACE_COEFF").is_some(); - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero=0 rng={rng}"); - } + // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is + // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including + // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and + // context offsets -- both of which now have rect forms + // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`). + // The rect sets that carry no symbol at all still pass `None` here. let mut tx_type = default_tx_type; if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { - // Mirrors [`read_coeffs`]'s own `tx_type` read: the CDF row's width - // names its set (lane-rectx, `TxbSet::LumaRect16x8` -- the one rect - // set here that carries a `tx_type` symbol at all). let len = tx_type_cdf.len(); let t = dec.symbol(tx_type_cdf); tx_type = match len { @@ -2563,21 +2652,25 @@ fn read_coeffs_rect( _ => TxType::from_symbol(t), } .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; + if rect_trace { + eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0); + } } - if TxClass::of(tx_type) != TxClass::TwoD { - return Err(unsupported( - "a non-2D tx class on a rectangular transform (never expected at this size)", - )); - } - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}"); + let class = TxClass::of(tx_type); + if class != TxClass::TwoD { + TX_CLASS1_HITS.with(|c| c.set(c.get() + 1)); } - let eob = read_eob(dec, coding, TxClass::TwoD); - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={rng}"); + let eob = read_eob(dec, coding, class); + if rect_trace { + eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0); } + let class_scan; + let scan: &[u16] = if class == TxClass::TwoD { + scan + } else { + class_scan = class_scan_table_wh(w, h, class); + &class_scan + }; let mut levels = vec![0i32; w * h]; for scan_idx in (0..eob).rev() { let pos = scan[scan_idx] as usize; @@ -2586,36 +2679,35 @@ fn read_coeffs_rect( let apos = col * h + row; let level = if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, w * h); - let l = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); + let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; + if rect_trace { eprintln!( - "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={} rng={rng}", - l - 1 + "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", + dec.debug_state().0 ); } - l + v } else { - let ctx = base_ctx_rect(&levels, w, h, row, col); - let l = dec.symbol(&mut coding.base[ctx]) as i32; - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); + let ctx = base_ctx_rect(&levels, w, h, row, col, class); + let v = dec.symbol(&mut coding.base[ctx]) as i32; + if rect_trace { eprintln!( - "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={l} rng={rng}" + "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", + dec.debug_state().0 ); } - l + v }; let level = if level > NUM_BASE_LEVELS { - let ctx = br_ctx_rect(&levels, w, h, row, col); + let ctx = br_ctx_rect(&levels, w, h, row, col, class); let mut level = level; let mut sent = 0; loop { let k = dec.symbol(&mut coding.br[ctx]) as i32; - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); + if rect_trace { eprintln!( - "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={rng}" + "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}", + dec.debug_state().0 ); } level += k; @@ -2629,12 +2721,12 @@ fn read_coeffs_rect( level }; levels[pos] = level; - if trace { + if rect_trace { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}"); } } - if ec_trace_coeff { + if rect_trace { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); } @@ -2648,7 +2740,7 @@ fn read_coeffs_rect( } else { dec.literal(1) == 1 }; - if trace { + if rect_trace { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative)); } @@ -6430,6 +6522,12 @@ impl PlaneBuf { }); let corner = (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); + if matches!((bw, bh), (16, 8) | (8, 16)) { + RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1)); + if across > own_across || down > own_down { + RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1)); + } + } (above, left, corner) } @@ -7803,6 +7901,327 @@ fn decode_leaf_split4( Ok((leaf_modes[2], leaf_modes[1])) } +/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two +/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape +/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for +/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no +/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at +/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for +/// every sub-block one mi wide or high but the last) -- differing only where +/// the shape does: +/// +/// * the transform is a true `TX_4X8`/`TX_8X4` +/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and +/// `av1_inv_txfm_shift_ls` row already cover this size pair); +/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares +/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type` +/// row -- see that variant's doc comment; +/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings +/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`; +/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows +/// ([`Reach::of_rect`]); +/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]` +/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a +/// `BLOCK_4X4` split writes. +/// +/// Filter intra on one of these leaves is refused by name: `predict_filter_intra` +/// is square-only in this decoder (the same refusal the 16x16-level rect +/// strips already carry). +#[allow(clippy::too_many_arguments)] +fn decode_leaf_rect8( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + outer_at: (usize, usize), + leaf_mi: (usize, usize), + vert: bool, + scan4: &[u16], + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + base_q_idx: u8, + enable_filter_intra: bool, + allow_intrabc: bool, + tx_select: bool, + reduced_tx_set: bool, +) -> Result<(usize, usize)> { + let (r, c) = outer_at; + let above_mode = neighbours.above_mode[c]; + let left_mode = neighbours.left_mode[r]; + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); + let (bw, bh) = if vert { (4, 8) } else { (8, 4) }; + let (w_mi, h_mi) = (bw / MI, bh / MI); + let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 }; + let mut leaf_modes = [0usize; 2]; + let mut leaf_skips = [false; 2]; + let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; + for i in 0..2usize { + let lmi = if vert { + (leaf_mi.0, leaf_mi.1 + i) + } else { + (leaf_mi.0 + i, leaf_mi.1) + }; + // Inside the pair the sibling is the neighbour on the split axis; + // outside it the mi-granular map, else the coarse 16x16 slot. + let leaf_above = if !vert && i == 1 { + leaf_modes[0] + } else { + neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode) + }; + let leaf_left = if vert && i == 1 { + leaf_modes[0] + } else { + neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode) + }; + let has_chroma = i == 1; + let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); + let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8( + dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, skip_ctx, + allow_intrabc, lmi.0, lmi.1, + )?; + if filter_intra.is_some() { + return Err(unsupported( + "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", + )); + } + // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4 + // leaf too, and is read for every intra block, skipped or not. Its + // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` -- + // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the + // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol + // `tx_size_cat2` the 32x16 strips read -- with the rect context + // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh). + // Missing this read consumed one symbol fewer than the encoder wrote + // and desynced the tile at the very first rect leaf (class + // `symbol-consumption-gap`). + let depth = if tx_select { + let ctx = tx_size_context_rect(neighbours, lmi, bw, bh); + dec.symbol(&mut cdfs.tx_size_cat0[ctx]) + } else { + 0 + }; + if depth != 0 { + TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); + RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + } + leaf_modes[i] = mode; + leaf_skips[i] = skip; + neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode); + let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); + } + let (px, py) = (lmi.1 * MI, lmi.0 * MI); + let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into + // two 4x4 transform units along its long axis, each predicted from + // the previous unit's reconstruction and reading its own `txb_skip` + // context -- `decode_leaf8`'s own depth-1 loop, two units instead of + // four. The per-TU path writes its own neighbour state, so the + // block-level write below is skipped for it. + let split = depth != 0; + if split { + let mut done = 0usize; + for tu in 0..2usize { + let tu_mi = if vert { + (lmi.0 + tu, lmi.1) + } else { + (lmi.0, lmi.1 + tu) + }; + let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); + let tu_around = neighbours.around_mi(tu_mi, 4)[0]; + let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height); + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); + if skip { + // A skipped leaf still predicts per transform unit: the + // second 4x4 takes its above/left edge from the first + // one's reconstruction, which is NOT what a single 4x8 + // prediction of the same mode produces. + let zeros = vec![0i32; 16]; + y.reconstruct( + tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None, None, + smooth_neighbor, + ); + neighbours.record_mi_luma(tu_mi, 4, &zeros); + continue; + } + let tu_grid = read_plane( + dec, + cdfs, + if reduced_tx_set { + TxbSet::Luma4 + } else { + TxbSet::Luma4Set1 + }, + scan4, + 0, + tu_around, + mode, + mode, + angle_delta_y, + tu_reach, + y, + tu_px, + tu_py, + 4, + TX4, + base_q_idx, + None, + None, + Some(tu_skip_ctx), + smooth_neighbor, + )?; + if tu_grid.iter().any(|&l| l != 0) { + done += 1; + } + neighbours.record_mi_luma(tu_mi, 4, &tu_grid); + } + if done > 0 { + if vert { + TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1)); + } else { + TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1)); + } + } + neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); + neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0); + if has_chroma { + last_uv = chroma; + } + continue; + } + let grid = if skip { + let zeros = vec![0i32; bw * bh]; + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, None, smooth_neighbor, + ); + zeros + } else { + // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's + // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx` + // at 0 -- see `decode_leaf_split4`'s own note. + let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; + let set = if reduced_tx_set { + TxbSet::LumaRect4x8 + } else { + TxbSet::LumaRect4x8Set1 + }; + let mut coding = cdfs.txb(set, mode); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + scan, + bw, + bh, + 0, + dc_sign_ctx(around.2), + TxType::DctDct, + )?; + if levels.iter().any(|&l| l != 0) { + if vert { + TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1)); + } else { + TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1)); + } + } + let residual = dequant_and_inverse_typed_wh( + &levels, + bw, + bh, + crate::decode::bit_depth(), + CURRENT_Q_IDX.with(|q| q.get()), + plane_q_delta(0).0, + plane_q_delta(0).1, + tx_type, + ); + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, None, smooth_neighbor, + ); + levels + }; + // Plane 0's per-TU coefficient context over this leaf's own mi span + // (`record_mi_luma`'s rect twin -- the chroma planes are written once + // for the whole 8x8 group below). + let state = neighbour_state(&grid); + for cell in 0..h_mi { + if lmi.0 + cell < neighbours.mi_rows { + neighbours.left[lmi.0 + cell][0] = state; + } + } + for cell in 0..w_mi { + if lmi.1 + cell < neighbours.mi_cols { + neighbours.above[lmi.1 + cell][0] = state; + } + } + neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); + let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) }; + neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0); + if has_chroma { + last_uv = chroma; + } + } + let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); + let (cpx, cpy) = (gpx / 2, gpy / 2); + let group_reach = Reach::of(8, gpx, gpy, y.width, y.height); + let (uv_mode, angle_delta_uv, alpha) = + last_uv.expect("i==1 always sets has_chroma, so chroma is always Some"); + let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; + neighbours.above_uv_mode[c] = uv_predict_mode; + neighbours.left_uv_mode[r] = uv_predict_mode; + neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); + let (u_grid, v_grid): (Vec, Vec) = if leaf_skips[1] { + u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv); + v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv); + (vec![0i32; 16], vec![0i32; 16]) + } else { + let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8)); + let chroma_around = neighbours.around_mi(leaf_mi, 8); + let ug = read_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, + angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, + )?; + let vg = read_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, + angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, + )?; + (ug, vg) + }; + // `update_partition_context` at the 8x8 level writes + // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8 + // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}` + // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which + // `partition_ctx_mi` reads back off these side values. + for cell in 0..2 { + neighbours.above_side_mi[leaf_mi.1 + cell] = bw; + neighbours.left_side_mi[leaf_mi.0 + cell] = bh; + } + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let bound_h = round_up_even(neighbours.mi_rows); + let bound_w = round_up_even(neighbours.mi_cols); + let u_state = neighbour_state(&u_grid); + let v_state = neighbour_state(&v_grid); + for cell in 0..2usize { + if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) { + neighbours.left[leaf_mi.0 + cell][1] = u_state; + neighbours.left[leaf_mi.0 + cell][2] = v_state; + } + if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) { + neighbours.above[leaf_mi.1 + cell][1] = u_state; + neighbours.above[leaf_mi.1 + cell][2] = v_state; + } + } + // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the + // bottom one (the second under HORZ, the left one under VERT), the one a + // neighbour to the right sees is the top-right (the second under VERT). + Ok(if vert { + (leaf_modes[0], leaf_modes[1]) + } else { + (leaf_modes[1], leaf_modes[0]) + }) +} + /// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary /// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2` /// (mod 8) reuse the same table. @@ -9965,10 +10384,28 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_intrabc, reduced_tx_set, )? + } else if part8 == PARTITION_HORZ + || part8 == PARTITION_VERT + { + decode_leaf_rect8( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + leaf_mi, + part8 == PARTITION_VERT, + &scan4, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_intrabc, + tx_select, + reduced_tx_set, + )? } else { - return Err(unsupported( - "a HORZ/VERT partition below 8x8 (this decoder's transform primitive is square-only; 4x8/8x4 need a real rectangular transform)", - )); + unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only"); }; neighbours.above_mode[sc] = saved_modes.0; neighbours.left_mode[sr] = saved_modes.1; @@ -10074,10 +10511,28 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_intrabc, reduced_tx_set, )? + } else if part8 == PARTITION_HORZ + || part8 == PARTITION_VERT + { + decode_leaf_rect8( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + leaf_mi, + part8 == PARTITION_VERT, + &scan4, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_intrabc, + tx_select, + reduced_tx_set, + )? } else { - return Err(unsupported( - "a HORZ/VERT partition below 8x8 (this decoder's transform primitive is square-only; 4x8/8x4 need a real rectangular transform)", - )); + unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only"); }; neighbours.above_mode[sc] = saved_modes.0; neighbours.left_mode[sr] = saved_modes.1; @@ -18810,3 +19265,91 @@ mod tests { } } } + +#[cfg(test)] +mod tx4x8_table_tests { + use super::*; + + /// Asymmetric gate on the two new scan tables (class + /// `reference-layout-not-spec`): a transposed pair of tables passes any + /// "is a permutation" check, so this pins the pair AGAINST each other -- + /// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and + /// both must be bijections of `0..32` in our own row-major indexing. + #[test] + fn the_rect_4x8_scans_are_each_other_transposed() { + let mut seen_a = [false; 32]; + let mut seen_b = [false; 32]; + for k in 0..32usize { + let a = SCAN_4X8[k] as usize; + let b = SCAN_8X4[k] as usize; + assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats"); + seen_a[a] = true; + seen_b[b] = true; + let (row, col) = (a / 4, a % 4); + assert_eq!(b, col * 8 + row, "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed"); + } + assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s)); + } + + /// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4` + /// (libaom `scan.c`), converted out of their column-major encoding by + /// `(p % h) * w + p / h` -- the head of each, pinned so the rect + /// `V_DCT`/`H_DCT` walk cannot silently transpose. + #[test] + fn the_rect_class1_scans_match_libaom() { + assert_eq!( + class_scan_table_wh(4, 8, TxClass::Vert), + (0..32u16).collect::>() + ); + assert_eq!( + &class_scan_table_wh(4, 8, TxClass::Horiz)[..8], + &[0u16, 4, 8, 12, 16, 20, 24, 28] + ); + assert_eq!( + class_scan_table_wh(8, 4, TxClass::Vert), + (0..32u16).collect::>() + ); + assert_eq!( + &class_scan_table_wh(8, 4, TxClass::Horiz)[..8], + &[0u16, 8, 16, 24, 1, 9, 17, 25] + ); + } + + /// The 32-position `eob_pt` alphabet: six symbols (one more than the + /// 16-position table, one fewer than the 64-position one), strictly + /// increasing, terminated at 32768 with the adaptation counter after it. + #[test] + fn the_32_position_eob_tables_are_well_formed() { + for table in [ + &cdf::EOB_PT_32_LUMA_Q0, + &cdf::EOB_PT_32_LUMA_Q1, + &cdf::EOB_PT_32_LUMA, + &cdf::EOB_PT_32_LUMA_Q3, + &cdf::EOB_PT_32_LUMA_CLASS1_Q0, + &cdf::EOB_PT_32_LUMA_CLASS1_Q1, + &cdf::EOB_PT_32_LUMA_CLASS1, + &cdf::EOB_PT_32_LUMA_CLASS1_Q3, + ] { + assert_eq!(table.len(), 7); + assert_eq!(table[5], 32768); + assert_eq!(table[6], 0); + for w in table[..6].windows(2) { + assert!(w[0] < w[1], "{table:?} is not increasing"); + } + } + } + + /// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4` + /// rows, not the 32x16 pair the two existing rect strips use: the two + /// shapes disagree at a position inside the superblock, which is what + /// makes this an asymmetric check rather than a tautology. + #[test] + fn the_sub8_rect_reach_tables_are_shape_specific() { + let a = Reach::of_rect(4, 8, 4, 8, 64, 64); + let b = Reach::of_rect(8, 4, 8, 4, 64, 64); + assert!( + a.above_right != b.above_right || a.below_left != b.below_left, + "4x8 and 8x4 reach identically at mirrored positions -- one table is unused" + ); + } +} diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index e9f0f1ab..918c5028 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1123,43 +1123,94 @@ impl Drop for VertAbGuard { } } -/// libaom `reconintra.c`'s `has_tr_*`/`has_bl_*` for the four rectangular -/// block sizes this decoder codes, transcribed verbatim (lane-rectx r4). -/// The 16x8/8x16 rows are what the 32x16/16x32 pair above cannot stand in -/// for: they are 16 bytes, not 4, and their bit pattern is a different -/// coding order entirely -- reading the 16x32 table for a 16x8 block gave -/// the wrong bottom-left availability and a directional (D203) strip whose -/// prediction diverged exactly where it starts reading below its own height. -/// `has_tr_vert_tables`/`has_bl_vert_tables` hold the SAME pointers as these -/// for every WH (no VERT_A/B ever produces one), -/// so the partition type does not select a different table at these sizes. -fn has_tr_rect_table(bw: usize, bh: usize) -> &'static [u8] { - match (bw, bh) { - (16, 8) => &[255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0], - (8, 16) => &[255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119], - (32, 16) => &[15, 5, 7, 5], - (16, 32) => &[255, 119, 127, 119], - (64, 32) => &[19], - // lane-tx64x16 r3: `has_tr_32x8` / `has_tr_8x32` - // (`reconintra.c:122-127`), the 4:1 strips of a 32x32-level - // `PARTITION_HORZ_4`/`VERT_4`. - (32, 8) => &[15, 0, 5, 0, 7, 0, 5, 0], - (8, 32) => &[255, 255, 127, 127, 255, 127, 127, 127], - _ => &[127], - } -} - -fn has_bl_rect_table(bw: usize, bh: usize) -> &'static [u8] { +/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this +/// decoder codes (libaom `reconintra.c`, generated from the oracle's source +/// so no byte is retyped). Each is indexed by +/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride +/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel +/// superblock grid; on this crate's 64-pixel superblock the highest index a +/// shape can reach stays inside its own table, so no wrap is involved. +/// +/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/ +/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed +/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at +/// 10 of the 21 reachable superblock positions for above-right and 7 for +/// below-left. +/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`). +const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119]; +/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`). +const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0]; +/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`). +const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0]; +/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`). +const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0]; +/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). +const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119]; +/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). +const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; +/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). +const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; +/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). +const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0]; +/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`). +const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; +/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`). +const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; +/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`). +const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; +/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`). +const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; +/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`). +const HAS_TR_32X64: [u8; 1] = [127]; +/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`). +const HAS_BL_32X64: [u8; 1] = [0]; +/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`). +const HAS_TR_64X32: [u8; 1] = [19]; +/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`). +const HAS_BL_64X32: [u8; 1] = [34]; +/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`). +const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127]; +/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`). +const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0]; +/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`). +const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0]; +/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`). +const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0]; +/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`). +const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; +/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`). +const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; +/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`). +const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; +/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`). +const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; +/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`). +const HAS_TR_16X64: [u8; 2] = [255, 127]; +/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`). +const HAS_BL_16X64: [u8; 2] = [0, 0]; +/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`). +const HAS_TR_64X16: [u8; 2] = [3, 1]; +/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`). +const HAS_BL_64X16: [u8; 2] = [42, 42]; + +/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape. +fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { match (bw, bh) { - (16, 8) => &[254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0], - (8, 16) => &[16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0], - (32, 16) => &[78, 14, 78, 14], - (16, 32) => &[16, 0, 16, 0], - (64, 32) => &[34], - // `has_bl_32x8` / `has_bl_8x32` (`reconintra.c:305-310`). - (32, 8) => &[238, 78, 238, 14, 238, 78, 238, 14], - (8, 32) => &[0, 1, 0, 0, 0, 1, 0, 0], - _ => &[0], + (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), + (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), + (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), + (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), + (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), + (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), + (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), + (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), + (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), + (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), + (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), + (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), + (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), + (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), + _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), } } @@ -1211,7 +1262,7 @@ impl Reach { if ((blk_col + 1) << bw_log2) >= SB_MI { return false; } - let table = has_tr_rect_table(bw, bh); + let table = rect_reach_tables(bw, bh).0; Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) } @@ -1245,7 +1296,7 @@ impl Reach { if ((blk_row + 1) << bh_log2) >= SB_MI { return false; } - let table = has_bl_rect_table(bw, bh); + let table = rect_reach_tables(bw, bh).1; Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) } @@ -3242,7 +3293,7 @@ mod tests { ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); for (name, table) in - [("has_tr", has_tr_rect_table(bw, bh)), ("has_bl", has_bl_rect_table(bw, bh))] + [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] { assert_eq!( table.len() * 8, @@ -3273,6 +3324,118 @@ mod tests { use std::io::Write; use std::process::{Command, Stdio}; + /// Every rectangular shape this decoder codes, at every position a block + /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`] + /// must answer exactly what libaom's `has_top_right`/`has_bottom_left` + /// (`reconintra.c`) answer, whose bodies are ported below. + /// + /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): + /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the + /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right) + /// and 7 (below-left) of the 21 reachable positions with no gate seeing + /// it. The per-shape `(len, byte sum)` fingerprints below come from the + /// oracle's own arrays, so a re-routed or truncated table fails here even + /// where the two rows happen to agree. + /// + /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/ + /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the + /// callers handle by predicting each transform unit as its own block. + /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's + /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is + /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL + /// (the horizontal shapes, which those partitions never produce). + #[test] + fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { + // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum). + const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ + (4, 8, 64, 9280, 64, 550), + (8, 4, 64, 3712, 64, 9630), + (8, 16, 16, 2352, 16, 134), + (16, 8, 16, 960, 16, 2400), + (16, 32, 4, 620, 4, 32), + (32, 16, 4, 32, 4, 184), + (32, 64, 1, 127, 1, 0), + (64, 32, 1, 19, 1, 34), + (4, 16, 32, 5472, 32, 14), + (16, 4, 32, 960, 32, 6464), + (8, 32, 8, 1400, 8, 2), + (32, 8, 8, 32, 8, 1136), + (16, 64, 2, 382, 2, 0), + (64, 16, 2, 4, 2, 84), + ]; + /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for + /// a block whose transform covers it whole (`row_off == col_off == 0`, + /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel + /// superblock (`sb_mi_size == 16`). + fn libaom_reach( + bw: usize, + bh: usize, + x: usize, + y: usize, + width: usize, + height: usize, + ) -> (bool, bool) { + let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); + let (_bw_unit, bh_unit) = (bw / 4, bh / 4); + let sb_mi_size = 16usize; + let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; + let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; + let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; + let (tr_table, bl_table) = rect_reach_tables(bw, bh); + let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; + // has_top_right: top_available && right_available, then row_off == 0. + let top_right = if y == 0 || x + bw >= width { + false + } else if blk_row_in_sb == 0 { + // (`col_off + tx_wide_unit < plane_bw_unit` above this is + // `bw_unit < bw_unit`, false for a whole-block transform.) + true + } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { + false + } else { + bit(tr_table) + }; + // has_bottom_left: bottom_available && left_available, col_off == 0. + let bottom_left = if x == 0 || y + bh >= height { + false + } else if blk_col_in_sb == 0 { + // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.) + (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size + } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { + false + } else { + bit(bl_table) + }; + (top_right, bottom_left) + } + for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { + let (tr, bl) = rect_reach_tables(bw, bh); + let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::(); + assert_eq!( + (tr.len(), sum(tr), bl.len(), sum(bl)), + (tr_len, tr_sum, bl_len, bl_sum), + "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" + ); + // Two superblocks across and down, so the superblock-relative + // position (and not the frame position) is what decides. + for sb_y in [0usize, 64] { + for sb_x in [0usize, 64] { + for y in (sb_y..sb_y + 64).step_by(bh) { + for x in (sb_x..sb_x + 64).step_by(bw) { + let got = Reach::of_rect(bw, bh, x, y, 256, 256); + let want = libaom_reach(bw, bh, x, y, 256, 256); + assert_eq!( + (got.above_right, got.below_left), + want, + "{bw}x{bh} at ({x}, {y})" + ); + } + } + } + } + } + } + /// Whether ffmpeg is on PATH. Absence normally SKIPs, but /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every /// aomenc gate decodes its stream through ffmpeg and is meaningless diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index ade37960..18e03151 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -284,10 +284,6 @@ const NEVER_ON_10BIT: &[(&str, &str)] = &[ "enable-tx-size-search", "hole at both depths, see the 8-bit list (11 of 15 pin =0)", ), - ( - "multi-tile", - "on in no 10-bit gate: all 15 leave --tile-columns/--tile-rows defaulted at 0, so every 10-bit stream is single-tile and no tile edge or per-tile CDF reset is checked at high bit depth", - ), ]; #[cfg(test)] diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index a6920105..edf63b19 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -25,7 +25,6 @@ #[cfg(test)] const CAPABILITY_CLAIMS: &[&str] = &[ "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)", - "a non-2D tx class on a rectangular transform (never expected at this size)", "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)", "a nonzero angle delta (this encoder never writes one)", ]; @@ -36,7 +35,6 @@ const REFUSALS: &[&str] = &[ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)", "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)", - "a HORZ/VERT partition below 8x8 (this decoder's transform primitive is square-only; 4x8/8x4 need a real rectangular transform)", "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 5e4b6a06..1257cef2 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -10647,6 +10647,449 @@ mod tests { } } + /// lane-tx4x8: `--enable-rect-partitions=1` with `--min-partition-size=4 + /// --max-partition-size=8` on fine-detail noisy gradients makes aomenc + /// pick `PARTITION_VERT`/`PARTITION_HORZ` at the 8x8 level -- two + /// `BLOCK_4X8`/`BLOCK_8X4` leaves, the last sub-8x8 shape this decoder + /// refused (it needed a real `TX_4X8`/`TX_8X4`: rect scan, 32-position + /// `eob_pt`, `TX_4X4` `tx_type` row over `TX_8X8` coefficient tables). + /// Both [`decode::tx4x8_coded_hits`] and [`decode::tx8x4_coded_hits`] are + /// hard-asserted per firing attempt so neither orientation can ride along + /// on the other ([[gate-blind-to-feature]]), and only leaves that coded + /// REAL coefficients count -- a skipped leaf never runs the transform. + /// Arms: 8-bit 16x16, an 8-bit `--tile-columns=1` 128x16 (the mi-granular + /// mode maps are per tile), and a 10-bit 16x16 -- 16-pixel fixtures, for + /// the reason the comment inside the loop gives. + #[test] + fn a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + let msg = format!("no aomenc at {}", aomenc_path().display()); + assert!( + std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), + "EC_AV1_REQUIRE_AOMENC is set but {msg}" + ); + eprintln!("SKIP {NAME}: {msg}"); + return; + } + // 16-pixel-tall/wide fixtures on purpose: at 64x64 EVERY attempt + // dies on a 16x16-LEVEL rect refusal belonging to other lanes + // ("a HORZ/VERT intra strip with a split transform", "a coded + // (non-skip) HORZ/VERT rect strip below 16x16", "a HORZ_A/HORZ_B/ + // VERT_A partition below 16x16") -- `--max-partition-size=8` does + // NOT stop aomenc coding a 16x16 as two 16x8 strips, measured + // 39/40 attempts refused. A 16x16 frame is one 16x16 block, so the + // encoder either splits it to 8x8s (this lane's path) or codes it + // whole; measured 12/12 attempts decoding, 3/12 with BOTH + // orientations coded. + for (width, height, tile_args, bit_depth) in [ + (16usize, 16usize, &[][..], 8u8), + (128usize, 16usize, &["--tile-columns=1"][..], 8u8), + (16usize, 16usize, &[][..], 10u8), + ] { + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + let mut split_tx = 0usize; + for attempt in 0..40u32 { + let seed = 300 + attempt; + let cq = 6 + (attempt % 4) * 2; + let pix_fmt = if bit_depth == 10 { + "yuv420p10le" + } else { + "yuv420p" + }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &format!("testsrc2=size={width}x{height}:rate=25"), + "-vf", + &format!("noise=alls=40:allf=t:all_seed={seed},format={pix_fmt}"), + "-strict", + "-1", + "-t", + "0.04", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &format!("--cq-level={cq}"), + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--min-partition-size=4", + "--max-partition-size=8", + // The tool under test: rect partitions ON, at a size + // where the only rect shapes are 4x8 and 8x4. + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-restoration=0", + "--enable-cdef=0", + "--loopfilter-control=0", + "--enable-ref-frame-mvs=0", + // Filter intra on a 4x8/8x4 leaf is refused by name + // (`predict_filter_intra` is square-only in this + // decoder, the same refusal the 16x16-level strips + // carry); with it on, that refusal -- not this + // lane's path -- is what most attempts hit. + "--enable-filter-intra=0", + "--limit=1", + "--obu", + "-o", + "-", + "-", + ]) + .args(if bit_depth == 10 { + &["--input-bit-depth=10", "--bit-depth=10"][..] + } else { + &[][..] + }) + .args(tile_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"); + if !out.status.success() { + refusals.push(format!( + "seed={seed} cq={cq}: aomenc itself refused the fixture" + )); + continue; + } + let stream = out.stdout; + let vert_before = decode::tx4x8_coded_hits(); + let horz_before = decode::tx8x4_coded_hits(); + let split_before = decode::rect8_split_tx_hits(); + let tiles_before = decode::tile_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.starts_with("unsupported: "), + "decode error that is not a named refusal \ + (seed={seed} cq={cq} depth={bit_depth} tiles={tile_args:?}): {msg}" + ); + refusals.push(format!("seed={seed} cq={cq}: {msg}")); + continue; + } + }; + assert!( + tile_args.is_empty() || decode::tile_hits() - tiles_before >= 2, + "tiles={tile_args:?} decoded only {} tile(s) (seed={seed} cq={cq})", + decode::tile_hits() - tiles_before + ); + let vert = decode::tx4x8_coded_hits() - vert_before; + let horz = decode::tx8x4_coded_hits() - horz_before; + if vert == 0 || horz == 0 { + refusals.push(format!( + "seed={seed} cq={cq}: decoded, but coded 4x8={vert} 8x4={horz} leaves" + )); + continue; + } + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, 1) + } else { + ffmpeg_decode_sequence(&stream, width, height, 1) + }; + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} tiles={tile_args:?})" + ); + assert_eq!( + frames[0].u, ffmpeg_frames[0].u, + "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" + ); + assert_eq!( + frames[0].v, ffmpeg_frames[0].v, + "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" + ); + fired_runs += 1; + split_tx += decode::rect8_split_tx_hits() - split_before; + if fired_runs >= 4 { + break; + } + } + assert!( + fired_runs >= 4, + "fewer than 4 firing+pixel-exact runs out of 40 attempts \ + ({width}x{height} depth={bit_depth} tiles={tile_args:?}):\n{}", + refusals.join("\n") + ); + // aomenc's default `--enable-tx-size-search=1` makes TX_MODE_SELECT + // the frame's tx mode, so every sub-8x8 rect leaf carries a + // `tx_depth` symbol; depth 1 (two 4x4 transform units predicted one + // after the other) is the half of that path a whole-leaf transform + // would silently get wrong, so the gate proves it fired. + assert!( + split_tx > 0, + "no sub-8x8 rect leaf used a split (depth-1) transform in the \ + {fired_runs} pixel-exact runs ({width}x{height} depth={bit_depth})" + ); + } + } + + /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): + /// a 16x8/8x16 intra strip whose DIRECTIONAL mode reads above-right or + /// below-left samples. Which of those the decoder may read is + /// `Reach::of_rect`'s answer, and until this round `rect_reach_tables` + /// had no 16x8 row at all -- every 16x8 strip read libaom's `has_tr_32x16` + /// row instead of `has_tr_16x8`, wrong at 10 of the 21 reachable + /// superblock positions for above-right and 7 for below-left. No gate saw + /// it: the sibling strip gate (`coded_rect_strip_below_16x16`) runs with + /// smooth/paeth/DC modes, which never read past the block, so the wrong + /// bit changed no pixel there. + /// + /// So this gate turns every non-directional intra tool OFF + /// (`--enable-smooth-intra=0 --enable-paeth-intra=0 + /// --enable-filter-intra=0`) at `--min-partition-size=8 + /// --max-partition-size=16 --enable-rect-partitions=1`, and counts, per + /// attempt, the 16x8/8x16 strips whose prediction actually reached past + /// their own width or height ([`decode::rect_strip_reach_hits`], recorded + /// in the predictor's edge fetch). An attempt only counts when that + /// counter moved AND the frame is pixel-exact against ffmpeg. + /// + /// BLOCKED, and `#[ignore]`d for it, not skipped from inside + /// ([[gate-skips-on-its-own-failure]]): the 16x16-level strip decoder + /// refuses every NON-SKIP 16x8/8x16 strip ("a coded (non-skip) HORZ/VERT + /// rect strip below 16x16", `decode.rs`), and that is what real streams + /// contain -- measured on this exact recipe, 38 of 40 attempts died on + /// that refusal and 2 on a sub-16x16 AB partition, at cq 30/45/58 and at + /// `--min-partition-size=16` (which yields no 16x8 at all, aomenc bounds a + /// rect shape by its smaller side). What unblocks it: the lane that ports + /// the coded 16x16-level strip; then drop this attribute. Until then the + /// table routing is pinned by the domain test + /// `encode::tests::every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock` + /// against libaom's own `has_tr_*`/`has_bl_*` arrays. + #[test] + #[ignore = "the coded 16x8/8x16 strip is a live refusal; see the doc above"] + fn a_directional_16x8_strip_reads_the_right_above_right_samples() { + const NAME: &str = "a_directional_16x8_strip_reads_the_right_above_right_samples"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + let msg = format!("no aomenc at {}", aomenc_path().display()); + assert!( + std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), + "EC_AV1_REQUIRE_AOMENC is set but {msg}" + ); + eprintln!("SKIP {NAME}: {msg}"); + return; + } + // 64x16, not 64x64: a 16-tall frame is a single row of 16x16 blocks, + // so a HORZ arm is a 16x8 strip at column 0..3 of the superblock -- + // exactly the positions whose `has_tr_16x8`/`has_bl_16x8` bit the old + // routing got wrong -- while the frame is too short for aomenc to + // build the deep sub-16x16 partitions other lanes still refuse. It + // must also be WIDER than one block: at width 16 the block is the + // frame, and `x + bw < width` kills above-right before any table. + for (width, height, bit_depth) in [(64usize, 16usize, 8u8), (64, 16, 10u8)] { + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + let mut reach_hits = 0usize; + for attempt in 0..40u32 { + let seed = 700 + attempt; + // Coarse quantisers on lightly-dithered content: fine detail + // at low cq makes aomenc build the sub-16x16 partitions other + // lanes refuse, and 40/40 attempts died there. + let cq = 45 + (attempt % 4); + let half = height / 2; + let pix_fmt = if bit_depth == 10 { + "yuv420p10le" + } else { + "yuv420p" + }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &format!("testsrc2=size={width}x{half}:rate=25"), + "-f", + "lavfi", + "-i", + &format!("color=c=gray:s={width}x{half}:rate=25"), + "-filter_complex", + &format!( + "[0]noise=alls=8:allf=t:all_seed={seed}[t];[t][1]vstack,\ + format={pix_fmt}" + ), + "-strict", + "-1", + "-t", + "0.04", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &format!("--cq-level={cq}"), + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + // The tool under test: 16x8/8x16 strips, predicted by + // a mode that reads beyond the block. + // aomenc bounds a RECT shape by its smaller side, so + // `--min-partition-size=16` yields no 16x8 at all + // (measured: 0 strips in 40 attempts); 8 is the + // smallest value that lets a 16x16 split HORZ/VERT. + "--min-partition-size=8", + "--max-partition-size=16", + // Largest transform per block: a split (depth-1) rect + // strip is a named refusal of another lane, and it + // ate every attempt while it was on. + "--enable-tx-size-search=0", + "--enable-rect-partitions=1", + "--enable-directional-intra=1", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-filter-intra=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-restoration=0", + "--enable-cdef=0", + "--loopfilter-control=0", + "--enable-ref-frame-mvs=0", + "--limit=1", + "--obu", + "-o", + "-", + "-", + ]) + .args(if bit_depth == 10 { + &["--input-bit-depth=10", "--bit-depth=10"][..] + } else { + &[][..] + }) + .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"); + if !out.status.success() { + refusals.push(format!( + "seed={seed} cq={cq}: aomenc itself refused the fixture" + )); + continue; + } + let stream = out.stdout; + let reach_before = decode::rect_strip_reach_hits(); + let pred_before = decode::rect_strip_pred_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.starts_with("unsupported: "), + "decode error that is not a named refusal \ + (seed={seed} cq={cq} depth={bit_depth}): {msg}" + ); + refusals.push(format!("seed={seed} cq={cq}: {msg}")); + continue; + } + }; + let reached = decode::rect_strip_reach_hits() - reach_before; + let predicted = decode::rect_strip_pred_hits() - pred_before; + if predicted == 0 { + refusals.push(format!( + "seed={seed} cq={cq}: decoded, but no 16x8/8x16 strip in the frame" + )); + continue; + } + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, 1) + } else { + ffmpeg_decode_sequence(&stream, width, height, 1) + }; + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth}, {predicted} strips, \ + {reached} of them reaching)" + ); + assert_eq!( + frames[0].u, ffmpeg_frames[0].u, + "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" + ); + assert_eq!( + frames[0].v, ffmpeg_frames[0].v, + "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})" + ); + fired_runs += 1; + reach_hits += reached; + if fired_runs >= 4 { + break; + } + } + assert!( + fired_runs >= 4, + "fewer than 4 firing+pixel-exact runs out of 40 attempts \ + ({width}x{height} depth={bit_depth}, {reach_hits} reaching strips):\n{}", + refusals.join("\n") + ); + } + } + /// lane-av1golden7 r9's decisive fixture: a real aomenc stream (seed 59, /// `--tune-content=film`, GOLDEN_FRAME firing downstream) whose frame-0 /// *intra keyframe* mismatched ffmpeg on 3855/4096 luma pixels -- traced diff --git a/lanes/tx4x8-r1.report.md b/lanes/tx4x8-r1.report.md new file mode 100644 index 00000000..49e185ac --- /dev/null +++ b/lanes/tx4x8-r1.report.md @@ -0,0 +1,92 @@ +# lane-tx4x8 round 1 — TX_4X8/TX_8X4 end to end (gate RED, first divergence not yet isolated) + +Branch `lane-tx4x8` off `lane-sub8` b500160. NOT rebased onto main (charter order). + +## What changed + +* `crates/ec-av1/src/cdf.rs` — `EOB_PT_32_LUMA{,_Q0,_Q1,_Q3}` + `_CLASS1` siblings, + transcribed from `av1_default_eob_multi32_cdfs` (`token_cdfs.h:792`), luma plane, both + tx-class rows. Format cross-checked against the already-pinned `EOB_PT_16_LUMA_CLASS1_Q0`. +* `crates/ec-av1/src/cdf_state.rs` — `eob_pt_32_luma{,_class1}` state + q-ctx `pick` + counter + reset; `TxbSet::LumaRect4x8`/`LumaRect4x8Set1`. Derivation: `get_txsize_entropy_ctx(TX_4X8)` + = `(txsize_sqr_map=TX_4X4 + txsize_sqr_up_map=TX_8X8 + 1) >> 1` = **TX_8X8**, so every + coefficient table is `Luma8`'s; `read_tx_type`'s CDF row is `txsize_sqr_map[TX_4X8]` = + **TX_4X4**, so the `tx_type` table is `Luma4`/`Luma4Set1`'s; `eob_pt` is the true + 32-position table (`txsize_log2_minus4[TX_4X8] == 1` -> `eob_flag_cdf32`). + (class `table-indexed-by-raw-size`: three different size keys in one variant.) +* `crates/ec-av1/src/decode.rs` — + - `SCAN_4X8`/`SCAN_8X4` (libaom `default_scan_4x8`/`8x4`), `class_scan_table_wh` + (`mrow`/`mcol` at rect sizes). Conversion `(p % h) * w + p / h` **re-proved first** by + regenerating the committed `SCAN_16X8`/`SCAN_8X16` from the same source (heads matched). + - `base_ctx_rect`/`br_ctx_rect` gained a `TxClass` (the 1D-class arms are shape-independent + in libaom's `get_nz_map_ctx_from_stats`; no new `av1_nz_map_ctx_offset_*` table is needed — + the `w 11+ctx` / `w>h -> 16+ctx` rule already in `base_ctx_rect` IS that table). + - `read_coeffs_rect` now reads a real `tx_type` symbol and honours `V_DCT`/`H_DCT` + (rect class scan + class contexts + `eob_pt_class1`). Two capability-claim refusals + deleted. + - `decode_leaf_rect8` — the `PARTITION_HORZ`/`VERT` leaf of an 8x8: two `BLOCK_8X4`/`4X8` + sub-blocks, mode reads via `read_intra_mode_sub8`, chroma once on the last sub-block at the + group's 4x4 unit, `dequant_and_inverse_typed_wh` (the rect transform primitive, its + `abs(rect_type)==1` `NewInvSqrt2` scale and `av1_inv_txfm_shift_ls[TX_4X8]` row, already + existed and needed no change), `Reach::of_rect`, `fill_lf_grid_rect(bw, bh)` for the + deblock grid, `partition_context_lookup[BLOCK_4X8] = {31,30}` / `[BLOCK_8X4] = {30,31}`. + Wired at BOTH sub-8x8 partition sites; the leftover `else` is now `unreachable!` + (`partition_w8` is a 4-symbol CDF). + - counters `tx4x8_coded_hits`/`tx8x4_coded_hits` (leaves with REAL coefficients only). + - 4 new table tests (transposed-pair scan gate, class-1 scan pins, eob table shape, + shape-specific reach). +* `crates/ec-av1/src/encode.rs` — `has_tr_4x8`/`has_tr_8x4`/`has_bl_4x8`/`has_bl_8x4` + transcribed verbatim; `rect_reach_tables(bw, bh)` replaces the `bw == 16` two-way pick. +* `crates/ec-av1/src/refusal_inventory.rs` — three refusals removed: the 4x8/8x4 partition + refusal and the two rect `tx_type`/`tx class` capability claims. +* `crates/ec-av1/src/stream.rs` — gate + `a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact`, three arms + (8-bit 16x16, 8-bit 128x16 `--tile-columns=1`, 10-bit 16x16), `--enable-rect-partitions=1 + --min-partition-size=4 --max-partition-size=8`, per-attempt hard assert that BOTH + `tx4x8_coded_hits` and `tx8x4_coded_hits` moved, named refusals only, no SKIP on error. + +## Gate: RED + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib sub8_rect_leaf` +-> `luma vs ffmpeg (seed=303 cq=12 depth=8 tiles=[])`, mismatch from sample 0 of a 16x16 +frame; ours is near-flat (126..142), ffmpeg's is full-range (0..229). The decode does not +error, so this is wrong coefficients/reconstruction (or an entropy divergence inside the +first rect leaf), not a refusal. + +EVIDENCE: cargo test output above | 40 attempts x 3 arms, aomenc --enable-rect-partitions=1 +--min-partition-size=4 --max-partition-size=8 --enable-filter-intra=0 on testsrc2+noise 16x16 | +first firing attempt (seed 303) mismatches luma at index 0; 291 other lib tests unaffected at +the time of the run. + +EVIDENCE: probe sweep with examples/decode_probe + EC_AV1_TRACE=1 | 12 seeds x 16x16, 12 x +32x32, --enable-filter-intra=0 | 16x16: 12/12 decode without any refusal, 3/12 code BOTH +orientations, 9/12 at least one; 32x32: 1/12 (11 die on 16x16-LEVEL rect refusals owned by +other lanes) — this is why the gate uses 16x16/128x16 fixtures. + +## Recipe findings (cite before reusing) + +* `--max-partition-size=8` does NOT stop aomenc coding a 16x16 block as two 16x8 strips: at + 64x64, 39/40 attempts refuse on 16x16-level rect gaps ("a HORZ/VERT intra strip with a split + transform", "a coded (non-skip) HORZ/VERT rect strip below 16x16", "a HORZ_A/HORZ_B/VERT_A + partition below 16x16"). Only a 16-pixel frame dimension isolates the 8x8 level. +* With `--enable-filter-intra=1`, most attempts die on the pre-existing square-only filter-intra + refusal, which `decode_leaf_rect8` re-raises by name for a 4x8 leaf. +* A probe sweep whose binary path was wrong reported "OK, 0 hits" for every cell + (class `stale-output-faked-measurement`): always `ls -l` the probe binary in the lane's own + `CARGO_TARGET_DIR` first. The first sweep in this round was invalid for exactly that reason. + +## Residue + +* fix-now (next round): the pixel mismatch. Nothing in the ladder below was disproved this + round, ranked by suspicion: + 1. an entropy divergence at the FIRST rect leaf (range ladder vs instrumented aomdec, + `EC_TRACE_COEFF`, on the pinned seed-303 stream) — ours decoding a near-flat frame is + consistent with an `eob`/`all_zero` read off the wrong table; + 2. `TxbSet::LumaRect4x8`'s three-way table split (coeff tables TX_8X8 / tx_type row TX_4X4 / + eob 32) — verify each against `read_coeffs_txb` live, not against my derivation; + 3. `dequant_wh` / the rect transform at (4,8) — never exercised below 16x8 before this lane; + 4. `Reach::of_rect` at 4x8/8x4 (localized errors only — would not explain sample 0). +* deferred: `--tile-columns=1` arm result — not separable while arm 1 is red — unblocked by + the fix above. +* deferred: filter intra on a 4x8/8x4 leaf — `predict_filter_intra` is square-only — unblocked + by a rect filter-intra predictor (same refusal the 16x16-level strips carry). diff --git a/lanes/tx4x8-r2.report.md b/lanes/tx4x8-r2.report.md new file mode 100644 index 00000000..4ab0f7a9 --- /dev/null +++ b/lanes/tx4x8-r2.report.md @@ -0,0 +1,79 @@ +# lane-tx4x8 round 2 — the RED gate's root cause: a tx_depth symbol never read + +Branch `lane-tx4x8`, commit `3677783` off r1's `efed7ee` (not rebased onto main, charter order). + +## Root cause + +`decode_leaf_rect8` (decode.rs:6081) read `skip`/`y_mode`/`uv_mode` and went straight to the +leaf's coefficients. libaom's `av1_read_tx_size` writes a `tx_depth` symbol for every intra +block with `block_signals_txsize(bsize)` — true for `BLOCK_4X8`/`BLOCK_8X4` — whenever the +frame's tx mode is `TX_MODE_SELECT`, which aomenc's **default** `--enable-tx-size-search=1` +selects and no gate recipe turns off. We consumed one symbol fewer than the encoder wrote, so +the tile desynced at the very first rect leaf and every later symbol read garbage that +decoded as near-zero residual (hence "near-flat 126..142 from sample 0, no decode error"). +Class `symbol-consumption-gap`; the 16x16-level strip path (decode.rs:3473) already carries a +comment about being bitten by exactly this. + +Decisive measurement (range ladder, not tell()): our post-`y_mode` range equalled the +oracle's (38104), but the oracle then entered its first coefficient read at rng=46600 — one +symbol's narrowing + renorm that we had not performed. + +## What changed (`crates/ec-av1/src/`) + +* `decode.rs:6081` `decode_leaf_rect8` — new `tx_select` parameter (threaded at both call + sites, decode.rs:8019 / 8146). Per sub-block, after the mode read and the filter-intra + refusal: `tx_size_cat0[tx_size_context_rect(lmi, bw, bh)]`. + `bsize_to_tx_size_cat(BLOCK_4X8) == 0` because `sub_tx_size_map[TX_4X8] == TX_4X4` is a + single step — the same 2-symbol category an 8x8 uses, **not** the 3-symbol `tx_size_cat2` + the 32x16 strips read (class `table-indexed-by-raw-size` avoided). +* `decode.rs` same function — depth 1 ported, not refused: two 4x4 transform units along the + leaf's long axis (`decode_leaf8`'s own depth-1 loop with two units instead of four), each + predicted from the previous unit's reconstruction, each with its own + `luma_skip_ctx`/`around_mi`/`TxbSet::Luma4(Set1)`. **Skipped** leaves take the per-unit path + too: a skipped 4x8 predicted in one shot is a different picture from two chained 4x4 + predictions. `fill_lf_grid_rect` records tx 4x4 in that case so the next block's + `tx_size_context` reads the coded size. +* `decode.rs:944` — `RECT8_SPLIT_TX_HITS` + `rect8_split_tx_hits()`; separate from + `TX_DEPTH_HITS`, which every square path also bumps. +* `decode.rs` `read_coeffs_rect` — `read_coeffs`'s `EC_TRACE_COEFF` range ladder + (`all_zero`/`tx_type`/`eob`/`base_eob`/`base`/`br`) in the oracle's own tag format. This was + the missing instrument: r1 could not compare rect coefficients element by element at all. +* `stream.rs:7429` gate — per-arm hard assert `split_tx > 0` on top of the existing + 4x8/8x4 coded-leaf asserts. + +No refusal string added or removed this round (`refusal_inventory` / `gate_coverage` +unchanged; r1 already removed the three this lane owns). The 16x16-level +"a HORZ/VERT intra strip with a split transform" refusal stays — it guards the 32x16 strips, +a different path. + +## Gate: GREEN (3 arms) + +`EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tx4x8 cargo test -p ec-av1 --lib sub8_rect_leaf` +-> `test result: ok. 1 passed; 0 failed` (32.5s), arms 16x16 8-bit / 128x16 8-bit +`--tile-columns=1` / 16x16 10-bit, each with >=4 firing pixel-exact runs and >=1 split-tx leaf. + +EVIDENCE: /tmp/.../scratchpad/s303a.obu (sha256 272ff85db3409432619b5e7ca8fefdde50616c08b4576b1e37823e2cd7912e95, regenerated twice, identical) | aomenc seed=303 cq=12 16x16 testsrc2+noise with the gate's own flags; `decode_probe s303a.obu ours.yuv` vs `ffmpeg -i s303a.obu -f rawvideo ref.yuv` | `cmp` byte-identical 384/384 bytes (was: mismatch at sample 0, ours 126 vs ref 76) + +EVIDENCE: EC_TRACE_COEFF ladder, ours vs instrumented aomdec, first rect leaf of s303a.obu | `EC_TRACE_COEFF=1 decode_probe` vs `EC_TRACE_COEFF=1 EC_TRACE_MODE=1 aomdec` | before: first `all_zero` rng 36990 vs oracle 45231 (diverged at the first coefficient symbol); after: 45231 / 54240 / eob=30 / 62552 / 63488 / 59248 / 46438 / 45648 / 49904 / 35324 / 32812 — every element equal. Positions differ only by the known layout convention (oracle prints `scan[c]` in an 8-wide grid, ours in a 4-wide one: oracle 30/15/22/29 = ours 27/29/26/23 transposed — the same coefficients). + +EVIDENCE: $HOME/.cache/tx4x8-suite.log | `EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tx4x8 cargo test -p ec-av1 --lib -j3` (full lib suite, aomenc required so an absent oracle fails) | `test result: ok. 274 passed; 0 failed; 22 ignored; 0 measured; 0 filtered out; finished in 768.55s` -- every sibling gate (sub8, tiny sweep, coded_rect_strip_below_16x16, refusal_inventory, gate_coverage) is in that run and green + +## Film probe (charter recipe, `ffmpeg -t 0.4 -c:v copy -f obu`) + +* ReelB (2160p 10-bit): `REFUSED: filter intra on a HORZ/VERT strip (this decoder + predicts square-only)`. +* ReelC (1080p 10-bit): `REFUSED: a 32x32 partition type this decoder does not code (value=4)` + (HORZ_A/HORZ_B/VERT_A). + +Measured only AFTER the fix — r1 recorded no before-value for these extracts, so no +"advanced from X to Y" claim is made. + +## Residue + +* deferred: rect filter-intra prediction (`predict_filter_intra` is square-only) — blocks the + ReelB head — unblocked by a rect filter-intra predictor, which the 16x16-level strips + need identically; one lane should own both. +* deferred: 32-level `PARTITION_HORZ_A/B/VERT_A` (ReelC's stop) — other lane's cluster. +* accepted: `read_coeffs_rect`'s trace prints `pos` in our own row-major-by-`w` layout, which + is the transpose of the oracle's for rect sizes. Documented here rather than "fixed", because + changing it would make our trace disagree with our own `read_coeffs`. diff --git a/lanes/tx4x8-r3.report.md b/lanes/tx4x8-r3.report.md new file mode 100644 index 00000000..5391e29c --- /dev/null +++ b/lanes/tx4x8-r3.report.md @@ -0,0 +1,116 @@ +# lane-tx4x8 r3 -- every rect shape gets its own has_tr/has_bl row + +## Root cause (verifier's finding, confirmed) + +`encode.rs` `rect_reach_tables(bw, bh)` had rows for 4x8, 8x4 and 16x32 only and +a `_` arm that routed **every other rectangular shape** to libaom's +`has_tr_32x16`/`has_bl_32x16`. 16x8 strips are live (`decode_leaf_rect`, +`decode.rs`), and neither the old `HAS_TOP_RIGHT_RECT[bw == 16]` selection nor +the r2 `_` arm matches `has_tr_16x8`/`has_bl_16x8` (`reconintra.c:96` / `:282`, +16 bytes each): over the 21 reachable superblock positions, has_tr was wrong at +14 (old) / 10 (r2) and has_bl at 14 / 7. Class: +[[enumerate-table-domain]] + [[tool-disabled-in-every-gate]]. + +## Fix + +* `encode.rs`: all 14 rect shapes this decoder codes or will code (4x8, 8x4, + 8x16, 16x8, 16x32, 32x16, 32x64, 64x32, 4x16, 16x4, 8x32, 32x8, 16x64, 64x16) + now have their own `HAS_TR_*`/`HAS_BL_*` const, **generated** from + `~/.cache/aom-oracle/src/av1/common/reconintra.c` (no byte retyped), and + `rect_reach_tables` is an exhaustive match ending in + `unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block")`. +* Index rule verified per shape: libaom's + `(blk_row_in_sb << (5 - bw_in_mi_log2)) + blk_col_in_sb` == row stride + `128 / bw` == the existing `Reach::table_stride(bw)`. For a 64-pixel + superblock the largest index any shape can produce is + `(64/bh - 1) * (128/bw) + (64/bw - 1)`, which is inside every one of the 14 + oracle tables -- so the `% (table.len() * 8)` wrap the rect path used to + apply is not just unnecessary, it was masking exactly this kind of + mis-routing; it is gone (the square path keeps its own). + +## Check 1 -- domain test (runnable, green) + +`encode::tests::every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock`: +for all 14 shapes, at every position a block of that shape can sit in a 64x64 +superblock (and in a second superblock at (64,64), so SB-relative position is +what decides), `Reach::of_rect` == a port of libaom's `has_top_right` / +`has_bottom_left` bodies incl. every early exit (top/right/bottom/left +availability, `blk_row_in_sb == 0`, rightmost column, leftmost column's +`row_off_in_sb + count < sb_height_unit`, bottom row). Each shape's table is +additionally pinned by a `(len, byte sum)` fingerprint taken from the oracle's +arrays, so a re-routed or truncated row fails even where two rows agree. + +Not covered, stated rather than implied: chroma `ss_x`/`ss_y` and sub-block +transforms (`row_off`/`col_off` > 0) -- `of_rect` takes neither parameter +(callers predict each transform unit as its own block); `PARTITION_VERT_A/B` +needs no arm because libaom's `has_tr_vert_tables` entry for every *rect* bsize +is either the plain table (4x8, 8x16, 16x32, 32x64) or NULL. + + cd /home/user/Documents/Code/Rust/edith_codecs-tx4x8 + CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tx4x8 EC_NOMEMGUARD=1 \ + cargo test -p ec-av1 --lib -j3 every_rect_shape + +EVIDENCE: $HOME/.cache/tx4x8-suite-r3.log | cargo test -p ec-av1 --lib every_rect_shape | 1 passed, 0 failed + +MUTATION (the check that says the test has teeth): restoring r2's routing for +one shape -- `(16, 8) => (&HAS_TR_32X16, &HAS_BL_32X16)` -- fails it: + + assertion `left == right` failed: rect_reach_tables(16, 8) is not libaom's has_tr_16x8/has_bl_16x8 + left: (4, 32, 4, 184) + right: (16, 960, 16, 2400) + +## Check 2 -- the asymmetric strip stream gate: BLOCKED, `#[ignore]`d + +`stream::tests::a_directional_16x8_strip_reads_the_right_above_right_samples` +is written in full (directional-only intra: `--enable-smooth-intra=0 +--enable-paeth-intra=0 --enable-filter-intra=0 --enable-directional-intra=1 +--enable-rect-partitions=1 --enable-ab-partitions=0`, 64x16 fixture whose +bottom half is flat so a HORZ arm can be a skip strip, 8-bit and 10-bit arms, +per-attempt counters `decode::rect_strip_pred_hits` / `rect_strip_reach_hits` +recorded in the predictor's edge fetch, pixel-exact vs ffmpeg) but it cannot +pass today and is `#[ignore]`d with the reason in its doc rather than skipping +from inside ([[gate-skips-on-its-own-failure]]). + +Why: the 16x16-level strip decoder refuses every **non-skip** 16x8/8x16 strip +("a coded (non-skip) HORZ/VERT rect strip below 16x16"), which is what real +streams contain. Measured on this recipe, per 40 attempts: + +| recipe | outcome | +| --- | --- | +| `--min-partition-size=16 --max-partition-size=16` | 40/40 decode, **0** 16x8/8x16 strips (aomenc bounds a rect shape by its smaller side, so 16x8 is never searched) | +| `--min-partition-size=8`, cq 8..20, noise 30, 64x64 | 40/40 refused (split-transform strip / non-skip strip / sub-16x16 AB) | +| `--min-partition-size=8 --enable-tx-size-search=0`, cq 30/45/55/62, noise 4 and 15, 64x16 | 0 firing; at cq 45 with the half-flat fixture: **38/40 "coded (non-skip) rect strip below 16x16"**, 2/40 sub-16x16 AB | + +MUTATION for this gate is therefore not reportable at stream level: with the +old `_` routing the gate fails for the same reason it fails with the fix (no +attempt gets past the refusal). The mutation evidence for the fix is the +domain-test one above. + +deferred: the stream-level pixel gate for 16x8/8x16 reach -- blocked by the +live "coded (non-skip) HORZ/VERT rect strip below 16x16" refusal -- unblocked +by the lane that ports the coded 16x16-level strip; then delete the +`#[ignore]` attribute (nothing else in the test changes). + +## Also + +* `stream.rs` doc of the sub-8x8 rect gate said "Arms: 8-bit 64x64, ... 128x64, + ... 10-bit 64x64"; the arms are 16x16 / 128x16 / 16x16. Fixed. +* New counters `rect_strip_pred_hits` / `rect_strip_reach_hits` in `decode.rs` + (bumped in `Plane::edges_rect`) are the instrument the blocked gate needs the + day the refusal lifts. + +## Suite + + CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tx4x8 EC_NOMEMGUARD=1 \ + EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 -j3 + +275 passed, 0 failed, 23 ignored (r2: 274 / 0 / 22 -- +1 = the domain test, ++1 ignored = the blocked gate). Log: `$HOME/.cache/tx4x8-suite-r3.log`. + +## Merge note + +This round deletes `HAS_TOP_RIGHT_RECT` / `HAS_BOTTOM_LEFT_RECT` (the 2-row +arrays lane-tx64x16 r3 extends to 4 rows with its own 32x8/8x32 entries). On a +merge, keep this branch's per-shape consts -- `HAS_TR_32X8` / `HAS_BL_32X8` / +`HAS_TR_8X32` / `HAS_BL_8X32` are already here, byte-identical to the oracle -- +and drop the array form together with `Reach::rect_table`.