diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index a097ea79..94135f3a 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -4616,6 +4616,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 330dcad8..7e6139e8 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -117,6 +117,20 @@ pub(crate) enum TxbSet { /// different existing sets is why this variant exists at all rather than /// reusing [`LumaRect32x16`](TxbSet::LumaRect32x16)'s chroma sibling. ChromaRect32x16, + /// 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 @@ -200,6 +214,11 @@ pub(crate) struct Cdfs { pub eob_pt_16_luma_class1: [u16; 6], /// `eob_pt_64_luma`'s class-1 sibling (r5), see `eob_pt_16_luma_class1`. pub eob_pt_64_luma_class1: [u16; 8], + /// 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. @@ -592,6 +611,8 @@ impl Cdfs { reset1(&mut self.eob_pt_16_luma); reset1(&mut self.eob_pt_16_luma_class1); reset1(&mut self.eob_pt_64_luma_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); @@ -798,6 +819,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, @@ -1409,6 +1444,30 @@ impl Cdfs { tx_type: None, eob_pt_class1: None, }, + 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 bb550953..c0bd8c73 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -935,6 +935,26 @@ 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) }; +} + +/// 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; @@ -1030,10 +1050,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"), } @@ -1229,6 +1259,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] = [ @@ -1268,30 +1313,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; @@ -1299,7 +1377,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 { @@ -1635,18 +1718,36 @@ fn read_coeffs_rect( if all_zero { return Ok((grid, TxType::DctDct)); } - if coding.tx_type.is_some() { - return Err(unsupported( - "a tx_type symbol on a rectangular transform (never expected at this size)", - )); + // 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() { + let len = tx_type_cdf.len(); + let t = dec.symbol(tx_type_cdf); + tx_type = match len { + 17 => TxType::from_symbol_all16(t), + 13 => TxType::from_symbol_set2_12(t), + 8 => TxType::from_symbol_set1(t), + _ => TxType::from_symbol(t), + } + .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; } - let tx_type = default_tx_type; - if TxClass::of(tx_type) != TxClass::TwoD { - return Err(unsupported( - "a non-2D tx class on a rectangular transform (never expected at this size)", - )); + 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); + let eob = read_eob(dec, coding, class); + 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; @@ -1655,11 +1756,11 @@ fn read_coeffs_rect( let ctx = eob_coeff_ctx(scan_idx, w * h); dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1 } else { - let ctx = base_ctx_rect(&levels, w, h, row, col); + let ctx = base_ctx_rect(&levels, w, h, row, col, class); dec.symbol(&mut coding.base[ctx]) as i32 }; 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 { @@ -5916,6 +6017,228 @@ 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, + 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)", + )); + } + 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); + 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); + neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, bw as u8, bh as u8, 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. @@ -7629,10 +7952,27 @@ 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, + 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; @@ -7738,10 +8078,27 @@ 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, + 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; @@ -14809,3 +15166,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 b61d88ba..a1817eab 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1078,6 +1078,45 @@ const HAS_TOP_RIGHT_RECT: [&[u8]; 2] = [&[15, 5, 7, 5], &[255, 119, 127, 119]]; /// `has_bl_32x16`/`has_bl_16x32`, same source, same order. const HAS_BOTTOM_LEFT_RECT: [&[u8]; 2] = [&[78, 14, 78, 14], &[16, 0, 16, 0]]; +/// `has_tr_4x8` (libaom `reconintra.c`), transcribed verbatim -- lane-tx4x8's +/// `PARTITION_VERT` leaf of an 8x8 block. Row stride is +/// [`Reach::table_stride`]`(4)` = 32 bits, as for every other entry of +/// libaom's own `has_tr_tables`. +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_tr_8x4`, same source -- the `PARTITION_HORZ` leaf. +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_4x8`, same source. +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_bl_8x4`, same source. +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, +]; + +/// 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) { + (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), + (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), + (16, 32) => (HAS_TOP_RIGHT_RECT[1], HAS_BOTTOM_LEFT_RECT[1]), + _ => (HAS_TOP_RIGHT_RECT[0], HAS_BOTTOM_LEFT_RECT[0]), + } +} + impl Reach { /// What a block of `side` samples at `(x, y)` may read past its own edges, /// in a frame of `width` by `height`. @@ -1124,7 +1163,7 @@ impl Reach { if col + 1 == per_col { return false; } - let table = HAS_TOP_RIGHT_RECT[usize::from(bw == 16)]; + let table = rect_reach_tables(bw, bh).0; Self::bit(table, (row * Self::table_stride(bw) + col) % (table.len() * 8)) } @@ -1136,7 +1175,7 @@ impl Reach { if row + 1 == per_row { return false; } - let table = HAS_BOTTOM_LEFT_RECT[usize::from(bw == 16)]; + let table = rect_reach_tables(bw, bh).1; Self::bit(table, (row * Self::table_stride(bw) + col) % (table.len() * 8)) } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index afdef531..955b6f1e 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -25,10 +25,8 @@ #[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)", - "a tx_type symbol on a rectangular transform (never expected at this size)", ]; #[cfg(test)] @@ -37,7 +35,6 @@ const REFUSALS: &[&str] = &[ "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)", "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 de1331c0..c0129c8c 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -7413,6 +7413,207 @@ 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 64x64, an 8-bit `--tile-columns=1` 128x64 (the mi-granular + /// mode maps are per tile), and a 10-bit 64x64. + #[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; + 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 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; + 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") + ); + } + } + /// 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).