diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 47f8df73..dbef2e14 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -477,7 +477,7 @@ pub const CFL_SIGN: [u16; 9] = [1418, 2123, 13340, 18405, 26972, 28343, 32294, 3 /// `av1_filter_intra_allowed_bsize`'s "both sides <= 32" bound, so libaom /// reads `use_filter_intra` there too and the missing rows dropped the /// symbol on every DC_PRED 1:4 strip. -pub const FILTER_INTRA: [[u16; 3]; 12] = [ +pub const FILTER_INTRA: [[u16; 3]; 14] = [ [4621, 32768, 0], [7866, 32768, 0], [12408, 32768, 0], @@ -490,6 +490,12 @@ pub const FILTER_INTRA: [[u16; 3]; 12] = [ [5893, 32768, 0], [18101, 32768, 0], [20229, 32768, 0], + // lane-r14: the 16x16-level 1:4 pair (`default_filter_intra_cdfs` index + // 17/16 -- BLOCK_16X4/BLOCK_4X16, generated by + // `scripts/extract-filter-intra-cdfs.py`), classes 12/13. Both sides <= 32, + // so libaom writes `use_filter_intra` on every DC_PRED strip of this shape. + [10368, 32768, 0], + [12770, 32768, 0], ]; /// `default_filter_intra_mode_cdf` (entropymode.c): which of the five /// `FILTER_INTRA_MODES` a `use_filter_intra` block picks. diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 90b8878c..2b01d282 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -214,6 +214,22 @@ pub(crate) enum TxbSet { /// `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 luma 16x4/4x16 transform of a 16x16-level `PARTITION_HORZ_4`/ + /// `PARTITION_VERT_4` strip (lane-r14). `get_txsize_entropy_ctx` + /// ((`txsize_sqr_map` + `txsize_sqr_up_map` + 1) >> 1) resolves `TX_16X4` + /// to `TX_8X8`, and the transform has 64 coded positions, so EVERY table + /// here is [`Luma8`](TxbSet::Luma8)'s (`eob_pt_64` included) except + /// `tx_type`: `read_tx_type` indexes `intra_ext_tx_cdf[eset] + /// [txsize_sqr_map[TX_16X4]]` = the `TX_4X4` row, and + /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_16X16` with + /// `tx_size_sqr == TX_4X4` returns `EXT_TX_SET_DTT4_IDTX` under + /// `reduced_tx_set` -- the same pair [`LumaRect4x8`](TxbSet::LumaRect4x8) + /// reads, which differs from this variant only in its 32-position `eob_pt`. + LumaRect16x4, + /// [`LumaRect16x4`](TxbSet::LumaRect16x4)'s `reduced_tx_set: false` + /// counterpart: `EXT_TX_SET_DTT4_IDTX_1DDCT`, the seven-symbol `TX_4X4` + /// row [`LumaRect4x8Set1`](TxbSet::LumaRect4x8Set1) reads. + LumaRect16x4Set1, } /// The tables one transform block is coded with, borrowed from the state for @@ -569,7 +585,7 @@ pub(crate) struct Cdfs { /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32, /// `[6]`=16x8, `[7]`=8x16, `[8]`=4x8, `[9]`=8x4, `[10]`=32x8, `[11]`=8x32) -- /// see [`cdf::FILTER_INTRA`]. - pub filter_intra: [[u16; 3]; 12], + pub filter_intra: [[u16; 3]; 14], /// Which `FILTER_INTRA_MODES` entry a `use_filter_intra` block picks. pub filter_intra_mode: [u16; 6], /// `TxMode::Select`'s `tx_depth` flag at an 8x8 block, by `tx_size_context` @@ -1807,6 +1823,30 @@ impl Cdfs { tx_type: Some(self.intra_tx_type_8_set1[mode].as_mut_slice()), eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), }, + TxbSet::LumaRect16x4 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_64_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_64_luma_class1), + }, + TxbSet::LumaRect16x4Set1 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_64_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_64_luma_class1), + }, TxbSet::LumaRect16x8Inter => TxbTables { side: 16, txb_skip: &mut self.txb_skip_luma_16, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 8f8db88b..9b3064e9 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -916,6 +916,10 @@ thread_local! { // their rect max transform into square sub-transforms. static RECT_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT_INTER_TXSPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + // lane-r14 r2: luma transform units of an inter strip with a 64-px axis + // (64x32/32x64/64x16/16x64), whose coefficients are coded as the + // truncated low-32 corner. + static RECT64_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter // frame -- 16x8 and 8x16 inter leaves. static INTER_LEAF16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -963,6 +967,11 @@ pub(crate) fn rect_inter_txsplit_hits() -> usize { RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) } +/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2). +pub(crate) fn rect64_inter_tu_hits() -> usize { + RECT64_INTER_TU_HITS.with(|c| c.get()) +} + /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/ /// [`ENABLE_FILTER_INTRA_INTER`]. pub(crate) fn set_inter_tx_mode( @@ -2102,6 +2111,30 @@ pub(crate) fn rect4_coeff_hits() -> usize { RECT4_COEFF_HITS.with(|c| c.get()) } +// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or +// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that +// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual. +thread_local! { + static RECT4_16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16 +/// strips, chroma-reference strips, strips with a coded residual, strips +/// whose luma transform is split)`. +pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) { + ( + RECT4_16_HORZ_HITS.with(|c| c.get()), + RECT4_16_VERT_HITS.with(|c| c.get()), + RECT4_16_CHROMA_HITS.with(|c| c.get()), + RECT4_16_COEFF_HITS.with(|c| c.get()), + RECT4_16_SPLIT_HITS.with(|c| c.get()), + ) +} + /// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded). pub(crate) fn rect4_32_horz_hits() -> usize { RECT4_32_HORZ_HITS.with(|c| c.get()) @@ -4930,6 +4963,10 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option { // tile (class symbol-consumption-gap). (32, 8) => Some(10), (8, 32) => Some(11), + // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16 + // strips), rows 17/16 of `default_filter_intra_cdfs`. + (16, 4) => Some(12), + (4, 16) => Some(13), _ if bw == bh => filter_intra_size_class(bw), _ => None, } @@ -4955,7 +4992,13 @@ fn palette_bsize_ctx(side: usize) -> Option { /// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own /// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`). fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option { - if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) { + // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the + // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and + // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx` + // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as + // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped + // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame. + if bw > 64 || bh > 64 || bw * bh < 64 { return None; } Some(((bw * bh) as u32).trailing_zeros() as usize - 6) @@ -5277,6 +5320,12 @@ fn read_intra_mode_rect( above_mode: usize, left_mode: usize, cfl: bool, + // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall + // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads + // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's + // chroma is coded once, on the closing strip). Every other caller is a + // block big enough to own its chroma and passes `true`. + has_chroma: bool, bw: usize, bh: usize, enable_filter_intra: bool, @@ -5340,21 +5389,23 @@ fn read_intra_mode_rect( 0 }; istep!("angle_y", angle_delta_y); - let uv_mode = if cfl { + let uv_mode = if !has_chroma { + DC_PRED + } else if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; istep!("uv_mode", uv_mode as i32); - let alpha = if cfl && uv_mode == UV_CFL_PRED { + let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; - if (9..=12).contains(&uv_mode) { + if has_chroma && (9..=12).contains(&uv_mode) { SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); } - let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) { DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { @@ -5394,7 +5445,11 @@ fn read_intra_mode_rect( palette_y_pending = Some((n, colors)); } let palette_uv_mode_ctx = usize::from(use_palette_y); - if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 { + // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard. + if has_chroma + && uv_mode == DC_PRED + && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 + { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache); palette_uv_pending = Some((n, u_colors, v_colors)); @@ -6177,6 +6232,7 @@ fn decode_block_rect( nb_above_mode, nb_left_mode, true, + true, bw, bh, enable_filter_intra, @@ -6651,6 +6707,7 @@ fn decode_leaf_rect( above_mode, left_mode, true, + true, bw, bh, enable_filter_intra, @@ -6930,6 +6987,7 @@ fn decode_block_rect4( above_mode, left_mode, true, + true, bw, bh, enable_filter_intra, @@ -7231,6 +7289,434 @@ fn decode_block_rect4( Ok((mode, uv_predict_mode)) } +/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` / +/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level +/// down, and the first shape here whose luma block is a single mi row (or +/// column). +/// +/// What is new at this size is CHROMA. `is_chroma_reference` +/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an +/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/ +/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close +/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair -- +/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) && +/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma +/// transform at the PAIR's origin, with CfL averaging over the pair's luma. +/// +/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context +/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is +/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row); +/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is +/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE +/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and +/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this +/// shape's own CDF row. +/// +/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`) +/// refuses by name rather than guess-decode. +#[allow(clippy::too_many_arguments)] +fn decode_rect4_16( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at16: (usize, usize), + horz: bool, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + enable_filter_intra: bool, + allow_screen_content_tools: bool, + base_q_idx: u8, + tx_select: bool, + reduced_tx_set: bool, +) -> Result<()> { + let (r, c) = at16; + let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI)); + let (bw, bh) = if horz { (16, 4) } else { (4, 16) }; + let (mi_w, mi_h) = (bw / MI, bh / MI); + let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 }; + let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 }; + let mut prev: Option<((usize, usize), usize)> = None; + let mut last_mode = DC_PRED; + let mut last_uv_mode = DC_PRED; + for i in 0..4usize { + let lmi = if horz { + (mi_row0 + i, mi_col0) + } else { + (mi_row0, mi_col0 + i) + }; + let has_chroma = i % 2 == 1; + // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell + // aliases all four strips onto one entry, so the mi-exact map wins and + // the previous strip stands in on the split axis. + let mut above_mode = neighbours.above_mode[c]; + let mut left_mode = neighbours.left_mode[r]; + if let Some(((pr, pc), pmode)) = prev { + if pc == lmi.1 && lmi.0 == pr + mi_h { + above_mode = pmode; + } else if pr == lmi.0 && lmi.1 == pc + mi_w { + left_mode = pmode; + } + } + let (above_mode, left_mode) = + neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode)); + let ( + skip, + mode, + angle_delta_y, + uv_mode, + angle_delta_uv, + alpha, + filter_intra, + palette_y, + palette_uv, + ) = read_intra_mode_rect( + dec, + cdfs, + above_mode, + left_mode, + true, + has_chroma, + bw, + bh, + enable_filter_intra, + neighbours.skip_txfm_ctx(lmi.0, lmi.1), + allow_screen_content_tools, + None, + &[], + lmi.0, + lmi.1, + )?; + if palette_y.is_some() || palette_uv.is_some() { + return Err(unsupported( + "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", + )); + } + let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1)); + } + if filter_intra.is_some() { + FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1)); + } + // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is + // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the + // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol + // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does. + let depth = if tx_select { + let ctx = tx_size_context_rect(neighbours, lmi, bw, bh); + dec.symbol(&mut cdfs.tx_size_cat1[ctx]) + } else { + 0 + }; + if depth != 0 { + TX_DEPTH_HITS.with(|h| h.set(h.get() + 1)); + RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1)); + } + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (px, py) = (lmi.1 * MI, lmi.0 * MI); + let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode); + if depth != 0 { + // [`decode_rect_split`]'s per-unit walk, inlined because the + // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to + // the strip (that function codes one chroma transform per block). + // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8 + // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each + // unit predicts off the units before it in raster order. + let rect_unit = tx_w != tx_h; + let zero_tu = vec![0i32; tx_w * tx_h]; + for tu_row in 0..bh / tx_h { + for tu_col in 0..bw / tx_w { + let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI)); + let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); + let tu_reach = Reach::of_tu( + bw, + bh, + tu_col * tx_w, + tu_row * tx_h, + tx_w, + tx_h, + reach, + ); + if skip { + y.reconstruct_rect( + tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu, + None, filter_intra, smooth_neighbor, + ); + neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu); + } else if rect_unit { + // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with + // 32 coded positions and the `TX_4X4` `tx_type` row: + // exactly [`TxbSet::LumaRect4x8`]. + let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; + let tu_skip_ctx = + neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI); + let set = if reduced_tx_set { + TxbSet::LumaRect4x8 + } else { + TxbSet::LumaRect4x8Set1 + }; + let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 }; + let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); + let (tu_grid, tu_tx_type) = read_coeffs_rect( + dec, + &mut coding, + tu_scan, + tx_w, + tx_h, + tu_skip_ctx, + dc_sign_ctx(tu_around.2), + TxType::DctDct, + )?; + let residual = dequant_and_inverse_typed_wh( + &tu_grid, + tx_w, + tx_h, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(0).0, + plane_q_delta(0).1, + tu_tx_type, + ); + y.reconstruct_rect( + tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual, + None, filter_intra, smooth_neighbor, + ); + if tu_grid.iter().any(|&l| l != 0) { + RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1)); + } + neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); + } else { + let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI); + let tu_grid = read_plane( + dec, + cdfs, + txbset_for(tx_w, reduced_tx_set), + &default_scan(tx_w), + 0, + tu_around, + mode, + mode, + angle_delta_y, + tu_reach, + y, + tu_px, + tu_py, + tx_w, + tx_w, + base_q_idx, + None, + filter_intra, + Some(tu_skip_ctx), + smooth_neighbor, + )?; + if tu_grid.iter().any(|&l| l != 0) { + RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1)); + } + neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); + } + } + } + } else { + let levels = if skip { + let zeros = vec![0i32; bw * bh]; + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, + smooth_neighbor, + ); + zeros + } else { + // The strip's luma TU *is* the strip (`plane_bsize == + // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes + // `txb_skip_ctx` at 0. + let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; + let set = if reduced_tx_set { + TxbSet::LumaRect16x4 + } else { + TxbSet::LumaRect16x4Set1 + }; + let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + scan, + bw, + bh, + 0, + dc_sign_ctx(around.2), + TxType::DctDct, + )?; + let residual = dequant_and_inverse_typed_wh( + &levels, + bw, + bh, + crate::decode::bit_depth(), + block_q_idx(), + 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, filter_intra, + smooth_neighbor, + ); + RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1)); + levels + }; + neighbours.record_mi_luma_rect(lmi, bw, bh, &levels); + } + neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip); + neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0); + // `update_partition_context` writes `partition_context_lookup[ + // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on + // the left (mirrored under VERT_4). + for cell in 0..mi_w { + if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) { + *slot = bw; + } + } + for cell in 0..mi_h { + if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) { + *slot = bh; + } + } + if has_chroma { + RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1)); + let pair_mi = if horz { + (lmi.0 - 1, lmi.1) + } else { + (lmi.0, lmi.1 - 1) + }; + let (pw, ph) = if horz { (16, 8) } else { (8, 16) }; + let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI); + let (cpx, cpy) = (ppx / 2, ppy / 2); + let (cw, ch) = (pw / 2, ph / 2); + let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; + let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height); + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c); + let (u_levels, v_levels) = if skip { + let zeros = vec![0i32; cw * ch]; + for (buf, _plane) in [(&mut *u, 1usize), (&mut *v, 2)] { + buf.reconstruct_rect( + cpx, + cpy, + cw, + ch, + uv_predict_mode, + angle_delta_uv, + pair_reach, + &zeros, + None, + None, + smooth_neighbor_uv, + ); + } + (zeros.clone(), zeros) + } else { + let around = neighbours.around_mi_rect(pair_mi, pw, ph); + let mut planes = Vec::with_capacity(2); + for plane in 1..3 { + let default_tx = default_intra_tx_type(uv_predict_mode as u8); + let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); + let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + chroma_scan, + cw, + ch, + skip_ctx, + dc_sign_ctx(around[plane].2), + default_tx, + )?; + planes.push((levels, tx_type)); + } + let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); + let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); + // CfL averages the luma of the WHOLE pair, the region this one + // chroma transform covers. + let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph)); + for (plane, buf, levels, tx_type) in [ + (1usize, &mut *u, &u_levels, u_tx_type), + (2, &mut *v, &v_levels, v_tx_type), + ] { + let residual = dequant_and_inverse_typed_wh( + levels, + cw, + ch, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(plane).0, + plane_q_delta(plane).1, + tx_type, + ); + buf.reconstruct_rect( + cpx, + cpy, + cw, + ch, + uv_predict_mode, + angle_delta_uv, + pair_reach, + &residual, + alpha + .zip(ac.as_deref()) + .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), + None, + smooth_neighbor_uv, + ); + } + (u_levels, v_levels) + }; + neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode); + // The chroma planes' coefficient context, over the PAIR's mi span + // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is + // the luma one rounded up to its 4x4 unit). + let u_state = neighbour_state(&u_levels); + let v_state = neighbour_state(&v_levels); + 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); + for cell in 0..(ph / MI) { + if pair_mi.0 + cell < bound_h + && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell) + { + slot[1] = u_state; + slot[2] = v_state; + } + } + for cell in 0..(pw / MI) { + if pair_mi.1 + cell < bound_w + && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell) + { + slot[1] = u_state; + slot[2] = v_state; + } + } + last_uv_mode = uv_predict_mode; + } + if horz { + RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1)); + } else { + RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1)); + } + last_mode = mode; + prev = Some((lmi, mode)); + } + // The coarse 16-px cell holds one entry for the whole 16x16: the last + // strip is what a block below (right) sees through it, the mi-exact maps + // above answering everything finer. + neighbours.above_mode[c] = last_mode; + neighbours.left_mode[r] = last_mode; + neighbours.above_uv_mode[c] = last_uv_mode; + neighbours.left_uv_mode[r] = last_uv_mode; + neighbours.above_side[c] = bw; + neighbours.left_side[r] = bh; + Ok(()) +} + /// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/ /// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` / /// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike @@ -7284,6 +7770,7 @@ fn decode_block_rect64( // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile // from this block's very first symbol (lane-sbpart r3 bisect). false, + true, bw, bh, enable_filter_intra, @@ -10854,7 +11341,19 @@ fn read_block_tx_size( /// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a /// rect transform), neither of which exists yet -- both stay refused by name. fn rect_inter_residual_supported(w: usize, h: usize) -> bool { - matches!((w, h), (32, 16) | (16, 32) | (16, 8) | (8, 16)) + matches!( + (w, h), + // 2:1 strips whose transform is coded in full (lane-inter4). + (32, 16) | (16, 32) | (16, 8) | (8, 16) + // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes + // only the low 32 coefficients of a 64-length axis, so these read + // exactly the truncated corner the INTRA superblock-strip path + // already reads (`read_intra_mode_rect`), through + // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is + // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no + // `tx_type` symbol is coded at all. + | (64, 32) | (32, 64) | (64, 16) | (16, 64) + ) } /// The luma coefficient/`tx_type` table set of a whole-block rectangular @@ -10875,6 +11374,13 @@ fn rect_inter_luma_set(w: usize, h: usize) -> TxbSet { TxbSet::LumaRect16x8InterSet1 } } + // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to + // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and + // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the + // adjusted size, so the existing sets are bit-exact. Neither carries a + // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot. + (64, 32) | (32, 64) => TxbSet::Luma64, + (64, 16) | (16, 64) => TxbSet::LumaRect32x16, _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), } } @@ -10887,6 +11393,13 @@ fn rect_inter_chroma_set(w: usize, h: usize) -> TxbSet { match (w, h) { (16, 8) | (8, 16) => TxbSet::ChromaRect16x8, (8, 4) | (4, 8) => TxbSet::ChromaRect8x4, + // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a + // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma + // unit has a 64-px axis, so both are coded in full; `Chroma16` is the + // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16, + // `txsize_log2_minus4` = 4), same as the intra strip path uses. + (32, 16) | (16, 32) => TxbSet::ChromaRect32x16, + (32, 8) | (8, 32) => TxbSet::Chroma16, _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), } } @@ -10932,6 +11445,8 @@ fn rect_scan(w: usize, h: usize) -> &'static [u16] { (8, 16) => &SCAN_8X16, (8, 4) => &SCAN_8X4, (4, 8) => &SCAN_4X8, + (32, 8) => &SCAN_32X8, + (8, 32) => &SCAN_8X32, _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), } } @@ -10998,6 +11513,16 @@ fn read_block_tx_size_rect( } TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1)); RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1)); + // lane-r14 r2: `sub_tx_size_map` is square for every shape this decoder + // splits (TX_32X16 -> TX_16X16, TX_64X32 -> TX_32X32) EXCEPT the 1:4 + // strips with a 64-px axis, where it stays rectangular + // (TX_64X16 -> TX_32X16, TX_16X64 -> TX_16X32) and the square recursion + // below would code the wrong tree. + if tx_w.max(tx_h) == 64 && tx_w.min(tx_h) == 16 { + return Err(unsupported( + "a split transform on a 1:4 inter strip with a 64-px axis", + )); + } let sub = tx_w.min(tx_h); let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1)); let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0)); @@ -11061,16 +11586,50 @@ fn read_inter_plane_rect( Some(t) if w.max(h) < 32 => t, _ => TxType::DctDct, }; - let (grid, tx_type) = read_coeffs_rect( - dec, - &mut coding, - rect_scan(w, h), - w, - h, - skip_ctx, - dc_sign_ctx(around.2), - default_tx_type, - )?; + // lane-r14 r2: a 64-length axis codes only its low 32 coefficients + // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)` + // corner, zero-extended into the true `w x h` grid before the inverse + // transform -- exactly what the intra superblock-strip path does. A + // corner that comes out square (32x32, under a 64x32/32x64 strip) reads + // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`, + // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted + // rectangular shape (lane-sbpart r8). + let (cw, ch) = (w.min(32), h.min(32)); + if plane_idx == 0 && w.max(h) == 64 { + RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1)); + } + let (corner, tx_type) = if (cw, ch) == (32, 32) { + let scan32 = default_scan(TX32); + read_coeffs( + dec, + &mut coding, + &scan32, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + Some((w, h)), + )? + } else { + read_coeffs_rect( + dec, + &mut coding, + rect_scan(cw, ch), + cw, + ch, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + )? + }; + let grid = if (cw, ch) == (w, h) { + corner + } else { + let mut full = vec![0i32; w * h]; + for row in 0..ch { + full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]); + } + full + }; let (dc_delta, ac_delta) = plane_q_delta(plane_idx); let residual = dequant_and_inverse_typed_wh( &grid, @@ -12640,11 +13199,34 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( neighbours.left_mode[sr] = mode_right; continue; } - if part16 != PARTITION_SPLIT { - return Err(unsupported( - "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)", - )); + if part16 == PARTITION_HORZ_4 + || part16 == PARTITION_VERT_4 + { + decode_rect4_16( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + part16 == PARTITION_HORZ_4, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + continue; } + // lane-r14 r2 (verifier note): every + // one of the 10 symbols this CDF can + // produce is handled above, so SPLIT + // is the only value that reaches + // here -- the refusal that used to + // stand here was unreachable and is + // gone from `refusal_inventory`. + debug_assert_eq!(part16, PARTITION_SPLIT); // A real (non-straddle) SPLIT of a // whole 16x16 into four 8x8 leaves -- // the same recursion the straddle @@ -21526,8 +22108,6 @@ mod tests { // string that blocks the shape otherwise. Either way the row is // pinned HERE, so the round that lifts one of those refusals cannot // land a wrong CDF row for the shape it unlocks. - const PART16: &str = "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)"; let libaom: &[(usize, usize, u16, Option<&str>)] = &[ (4, 4, 4621, None), (4, 8, 6743, None), @@ -21542,8 +22122,10 @@ mod tests { // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives // 4x16/16x4 (still refused by name before any leaf is coded), // a 32x32-level one 8x32/32x8. - (4, 16, 12770, Some(PART16)), - (16, 4, 10368, Some(PART16)), + // lane-r14: the 16-level pair is coded now (`decode_rect4_16`), + // owning classes 13/12. + (4, 16, 12770, None), + (16, 4, 10368, None), // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes // 10/11; only the 16-level pair is still refused before any leaf. @@ -22018,8 +22600,16 @@ mod tests { // non-skip, so the named refusal is the rectangular-inter-residual // one. Either string proves what the pin was written for: a non-SPLIT // superblock never silently decodes as SPLIT. + // lane-r14 r2: the rectangular-residual refusal is gone (a 64x32 strip + // now codes its truncated low-32 coefficient corner), so this + // hand-written fixture walks further still and stops on the limit of + // the FIXTURE rather than of the decoder: it names no reference + // pictures. All three strings prove the one thing this pin exists for + // -- a non-SPLIT superblock never silently decodes as SPLIT. assert!( - msg.contains("SPLIT") || msg.contains("rectangular residual coding"), + msg.contains("SPLIT") + || msg.contains("rectangular residual coding") + || msg.contains("no picture at this frame's own ref_frame_idx slot"), "expected the named inter-SB-partition refusal, got: {msg}" ); } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index cb1b26ea..59c87d46 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -34,7 +34,6 @@ const REFUSALS: &[&str] = &[ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", - "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)", "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", "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", @@ -81,6 +80,10 @@ const REFUSALS: &[&str] = &[ "warp prediction with a scaled reference (superres, unimplemented)", "an 8x8 partition leaf under a scaled reference (superres, unimplemented)", "a motion_mode symbol for a block shape with no CDF row here", + // lane-r14 r2: the whole-transform case of every 64-axis inter strip is + // coded; only the SPLIT of a 1:4 strip with a 64-px axis is left, whose + // `sub_tx_size_map` entry is rectangular (TX_64X16 -> TX_32X16). + "a split transform on a 1:4 inter strip with a 64-px axis", ]; /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 3bde2750..bfef83f9 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -68,6 +68,12 @@ pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) { ) } +/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis, +/// coded as the truncated low-32 coefficient corner. +pub fn rect64_inter_tu_hits() -> usize { + crate::decode::rect64_inter_tu_hits() +} + pub fn rect4_32_counters() -> (usize, usize, usize) { ( crate::decode::rect4_32_horz_hits(), @@ -6558,10 +6564,21 @@ mod tests { // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B) // strip needs rectangular residual coding". The 10-bit twin below is // `#[ignore]`d with that exact reason rather than deleted or weakened. + // lane-r14 r2 re-measured the 8-bit-only note above: the residual + // refusal it names is GONE (this round codes a 64-px transform axis as + // its truncated low-32 corner), and a 10-bit sweep of this exact + // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2 + // 32x64 strips, 2 of them carrying a coded 64-axis residual. It stays + // 8-bit here for a DIFFERENT, newly exposed reason: 10-bit attempt 14 + // (cq 61, horizontal split, motion step 12) mismatches ffmpeg while + // decoding ZERO superblock-level rect strips and zero 64-axis + // residual units, i.e. a defect of some other shape that this gate + // must not absorb. See lanes/r14-r2.report.md. for bit_depth in [8u32] { let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = (0u32, 0u32, 0u32, 0u32); let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + let mut rect64_tus = 0usize; for attempt in 0..16u32 { // Two orientations (the transposed pair a one-sided gate could // never separate) x four quantisers x two motion steps: which @@ -6634,6 +6651,7 @@ mod tests { ); let stream = out.stdout; let before = crate::stream::inter_rect_counters(); + let rect64_before = crate::stream::rect64_inter_tu_hits(); let frames = match decode_stream(&stream) { Err(e) => { let msg = e.to_string(); @@ -6650,6 +6668,7 @@ mod tests { }; let after = crate::stream::inter_rect_counters(); let (horz, vert) = (after.2 - before.2, after.3 - before.3); + let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before; let ffmpeg_frames = if bit_depth == 10 { ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) } else { @@ -6678,11 +6697,13 @@ mod tests { } horz_proved += horz; vert_proved += vert; + rect64_tus += rect64; matched += 1; } eprintln!( "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \ + 64-axis residual TUs={rect64_tus}, \ {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)" ); assert_eq!( @@ -6690,6 +6711,15 @@ mod tests { "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \ decoded but mismatched ffmpeg -- a defect of another shape, not a pass" ); + // lane-r14 r2: the residual half of the arm -- a strip that is not + // `skip` and codes a real 64-axis transform unit. Without this the + // gate proves only the partition symbol. + assert!( + rect64_tus > 0, + "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \ + 64-axis residual transform unit inside a pixel-exact attempt \ + (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing" + ); assert!( horz_proved + vert_proved > 0, "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \ @@ -20014,6 +20044,252 @@ mod tests { /// then compared pixel-exact are counted (class /// gate-skips-on-its-own-failure); the 10-bit arm is what retires /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`. + /// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or + /// 4x16 (`PARTITION_VERT_4`) strips, the shape the wall + /// "a 1:4 partition below 16x16" refused. Fixture: 4-PIXEL bands (the + /// 8-pixel ones of the 32-level gate above, one size down -- a 16x4 strip + /// is flat where a 16x8 one is not), transposed per attempt so a + /// transposed scan or nz-map table cannot pass (class + /// scan-weights-cross-axis), plus an explicit-seed noise layer that keeps + /// aomenc out of screen-content mode. `--enable-filter-intra=1` and + /// is ON: this shape reads `use_filter_intra` off its own CDF rows + /// (classes 12/13). The `--enable-tx-size-search=1` half of the window + /// splits the strip's transform (depth 1 = TX_8X4/TX_4X8, depth 2 = + /// TX_4X4). + /// + /// Counters: 16x4 strips, 4x16 strips, chroma-reference strips (the odd + /// strip of each 4:2:0 pair, the only one that codes chroma) and strips + /// with a coded residual must all be nonzero over the compared attempts, + /// and only attempts that DECODED and were compared pixel-exact count + /// (class gate-skips-on-its-own-failure). + #[test] + fn a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 1usize); + let n_attempts: u32 = std::env::var("EC_R14_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(8); + for bit_depth in [8u32, 10u32] { + let mut named_refusals = 0u32; + let mut matched = 0u32; + let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + let (mut chroma_proved, mut coeff_proved) = (0usize, 0usize); + let mut split_proved = 0usize; + let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); + // The second half of the window turns `--enable-tx-size-search` on: + // that is what makes a 16x4 strip SPLIT its transform (depth 1 = + // TX_8X4, depth 2 = TX_4X4), the arm the first half never reaches. + for attempt in 0..n_attempts * 2 { + let tx_search = attempt >= n_attempts; + let attempt = attempt % n_attempts; + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let axis = if attempt % 2 == 0 { "Y" } else { "X" }; + let step = 67 + (attempt / 2) * 12; + let noise = 6 + (attempt % 4) * 3; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='mod(floor({axis}/4)*{step},256)',\ + noise=alls={noise}:all_seed={seed},format=yuv420p" + ); + let cq_level = format!("--cq-level={}", 24 + (attempt % 4) * 8); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq_level, + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + &depth_arg, + &input_depth_arg, + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", + "--min-partition-size=4", + "--max-partition-size=16", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=1", + // lane-r14: CfL stays OFF here. This shape's CfL averages + // the luma of the whole PAIR and is written, but no gate + // asserts a CfL hit counter (there is none), and passing + // `=1` would retire `enable-cfl-intra` from + // `gate_coverage::NEVER_EXERCISED_*` on a flag alone -- + // exactly the false coverage that list exists to prevent. + "--enable-cfl-intra=0", + "--enable-intrabc=0", + if tx_search { + "--enable-tx-size-search=1" + } else { + "--enable-tx-size-search=0" + }, + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = crate::decode::rect4_16_counters(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \ + {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let now = crate::decode::rect4_16_counters(); + let (horz, vert, chroma, coeff, split) = ( + now.0 - before.0, + now.1 - before.1, + now.2 - before.2, + now.3 - before.3, + now.4 - before.4, + ); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + out_of_scope += 1; + if mismatched { + out_of_scope_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 16-level \ + 1:4 strips -- a pre-existing defect of another shape" + ); + } + continue; + } + if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!( + "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \ + {seed}) to {path}" + ); + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + assert_eq!( + got.u, want.u, + "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + assert_eq!( + got.v, want.v, + "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + } + horz_proved += horz; + vert_proved += vert; + chroma_proved += chroma; + coeff_proved += coeff; + split_proved += split; + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every {bit_depth}-bit attempt refused or fell out of scope ({named_refusals} \ + refusals, {out_of_scope} out of scope); the gate proved nothing" + ); + assert_eq!( + out_of_scope_mismatch, 0, + "{NAME}: {out_of_scope_mismatch} {bit_depth}-bit attempt(s) mismatch with no \ + 16-level 1:4 strip at all" + ); + assert!( + horz_proved > 0 && vert_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts decoded {horz_proved} 16x4 and \ + {vert_proved} 4x16 strips -- both orientations must fire or a transposed table \ + passes" + ); + assert!( + chroma_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts closed {chroma_proved} chroma pairs" + ); + assert!( + coeff_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts coded no residual on any strip" + ); + assert!( + split_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts never split a strip's transform -- \ + the `--enable-tx-size-search=1` half of the window proved nothing" + ); + eprintln!( + "{NAME}: {bit_depth}-bit {matched} compared attempts, {horz_proved} 16x4 / \ + {vert_proved} 4x16 strips, {chroma_proved} chroma pairs, {coeff_proved} coded \ + units, {split_proved} split-transform strips, {named_refusals} refusals, \ + {out_of_scope} out of scope" + ); + } + } + #[test] // lane-tx64x16 r4: the fixture r3 could not find. `gradients` never wins // a 32-level 1:4 shape; 8-pixel BANDS do -- each 32x8 strip is flat, so diff --git a/lanes/r14-r1.report.md b/lanes/r14-r1.report.md new file mode 100644 index 00000000..cdfd93ed --- /dev/null +++ b/lanes/r14-r1.report.md @@ -0,0 +1,119 @@ +# lane-r14 r1 -- the 16x16-level 1:4 partition (four 16x4 / 4x16 strips) + +Branch `lane-r14` off main `0df090a`; commits `9bde843` (partition + paired +chroma) and `ccd58a2` (split transform). + +## Film first + +`ffmpeg -ss 300 -t 0.4 -i -c:v copy -f obu kf300.obu`, +then `decode_probe`: + +* BEFORE: `REFUSED: a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four + 16x4/4x16 strips ...)`. +* AFTER 9bde843: `REFUSED: a 16x4/4x16 strip whose transform is split` -- every + 16-level 1:4 strip in that key frame reads `tx_depth != 0`, so the partition + alone was not enough. +* AFTER ccd58a2: `REFUSED: a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs + rectangular residual coding` -- ANOTHER lane's wall; the 1:4 one is gone, with + rect4_32 counters horz=104 vert=172 coded=238 (these are the 32-level 1:4 counters decode_probe prints, NOT rect4_16; the true rect4_16 numbers on kf300 are 96, 148, 122, 311, 63) strips decoded at the 32 level alone before it stops. + +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/r14/kf300.obu | decode_probe before/after each commit | refusal string moved 1:4-partition -> 1:4-split-transform -> rect-residual (another lane) + +## What changed + +* `crates/ec-av1/src/decode.rs` -- `decode_rect4_16` (new): the four strips of a + 16-level `PARTITION_HORZ_4`/`VERT_4`, wired at the key-frame 16-level + partition site (the old refusal is now + "a 16x16-level partition value outside PARTITION_NONE..PARTITION_VERT_4", + the SB-level wording one size down). + - CHROMA is what is new at this size: `is_chroma_reference` is false for a + 4:2:0 block one mi tall (wide) on an EVEN mi row (column), so strips 0 and 2 + read no `uv_mode`/`cfl_alpha`/`angle_delta_uv` and code no chroma; strips 1 + and 3 close the pair and carry the 8x4 (4x8) chroma of the whole 16x8 (8x16) + luma pair at the PAIR's origin (`setup_pred_plane`'s `mi_row -= 1`), CfL + averaging the pair's luma. + - `read_intra_mode_rect` grew a `has_chroma` (`is_chroma_reference`) parameter; + the four existing call sites pass `true`. + - Split transform: `decode_rect_split`'s per-unit walk inlined (its chroma is + the block's, ours is the pair's). depth 1 = TX_8X4/TX_4X8 rect units + (`TxbSet::LumaRect4x8`), depth 2 = square TX_4X4 via `read_plane`. + - `filter_intra_size_class_rect`: classes 12/13 for 16x4/4x16. + - `palette_bsize_ctx_wh`: DEFECT SWEPT -- `av1_allow_palette`'s + `sb_type >= BLOCK_8X8` is an ENUM INDEX test that BLOCK_4X16 (16) and + BLOCK_16X4 (17) clear, so a 64-pixel 1:4 strip DOES read `palette_y_mode` + (ctx 0) in a screen-content frame; the old "both sides >= 8" bound dropped + that symbol. Now `bw <= 64 && bh <= 64 && bw * bh >= 64`, which reproduces + the enum-index rule for every shape. +* `crates/ec-av1/src/cdf.rs` -- `FILTER_INTRA` rows 12/13 (10368/12770), the + values `filter_intra_classes_carry_their_own_libaom_default_row` already + pinned for BLOCK_16X4/BLOCK_4X16; that test now lists both as owning a class. +* `crates/ec-av1/src/cdf_state.rs` -- `TxbSet::LumaRect16x4{,Set1}`: `Luma8`'s + coefficient tables (`get_txsize_entropy_ctx(TX_16X4)` = the 8x8 class, 64 + positions) with the `TX_4X4` `tx_type` row. +* `crates/ec-av1/src/refusal_inventory.rs` -- the 1:4-below-16x16 refusal is + gone; the 16-level partition-value guard replaces it. +* `crates/ec-av1/src/stream.rs` -- the gate. + +## Gate + +`a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact` +(4-pixel bands, transposed per attempt, explicit-seed noise, 192x128, +`--enable-1to4-partitions=1 --enable-rect-partitions=1 --enable-ab-partitions=0 +--min-partition-size=4 --max-partition-size=16 --enable-filter-intra=1 +--cpu-used=0`, second half of the window `--enable-tx-size-search=1`), 8 seeds x +2 tx-search arms x 2 bit depths. + +``` +systemd-run --user --scope -q -p MemoryMax=8G env CARGO_TARGET_DIR=$HOME/.cache/cargo-target-r14 \ + EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 nice -n 10 cargo test -p ec-av1 --lib -j3 \ + a_real_aomenc_stream_with_a_16_level_1to4 -- --nocapture +``` + +Result (both green): + +* 8-bit: 15 compared attempts, 192 16x4 / 288 4x16 strips, 240 chroma pairs, + 486 coded units, 102 split-transform strips, 0 refusals, 1 out of scope. +* 10-bit: 16 compared attempts, 148 16x4 / 280 4x16 strips, 214 chroma pairs, + 433 coded units, 82 split-transform strips, 0 refusals, 0 out of scope. + +Every decoded frame is pixel-compared against ffmpeg (`assert_eq` on all three +planes); a decode error is asserted to be a NAMED refusal, never a SKIP. + +EVIDENCE: cargo test output above | 31 real aomenc streams encoded, decoded and compared | 340 16x4 + 568 4x16 strips, 454 chroma pairs, 184 split-transform strips, 0 mismatches + +Encoder-side proof the shape is really in the stream (independent of our +counters): instrumented `aomdec EC_TRACE=1` on the same recipe prints +`EC_PART bsize=6 value=8` (HORZ_4 at BLOCK_16X16) 6x and `value=9` (VERT_4) +10x on the two axes of the fixture. + +## Refusals + +* LIFTED: "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 + strips ...)". +* STILL REFUSED at this shape: "a 1:4 rect strip that actually uses a palette" + (shared with the 32-level pair; reconstruction unported). +* NEW (replacing the lifted one, same site): "a 16x16-level partition value + outside PARTITION_NONE..PARTITION_VERT_4". + +## Residue + +* deferred: the INTER twin of this partition (the inter 16-level site still + refuses 1:4 by its own name) -- unblocked by an inter fixture that reaches a + 16-level 1:4, out of this lane's intra scope. +* deferred: CfL over the pair is written but no gate proves it fired -- + `--enable-cfl-intra` stays `=0` on this recipe because there is no CfL hit + counter, and enabling the flag alone would falsely retire the tool from + `gate_coverage::NEVER_EXERCISED_*`. Unblocked by a CfL counter + a fixture + whose chroma actually correlates with luma. +* accepted: no `--tile-columns` arm in this gate -- the lane added no per-mi + neighbour map, it reuses the existing tile-edge-guarded ones. + +## Suite + +`systemd-run --user --unit=r14-suite3 -p MemoryMax=10G --same-dir bash -lc +'EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-r14 +nice -n 10 cargo test -p ec-av1 --lib -j3'` -> `test result: ok. 356 passed; 0 +failed; 29 ignored` (346 s), log `$HOME/.cache/r14-suite-clean.log`. Siblings +re-run inside it: the 32-level and superblock-level 1:4 gates, every rect-strip +and split-transform gate, `filter_intra_classes_carry_their_own_libaom_default_row`, +`refusal_inventory`, `gate_coverage`, `every_rect_shape`, `base_ctx_rect_offsets`. diff --git a/lanes/r14-r2.report.md b/lanes/r14-r2.report.md new file mode 100644 index 00000000..4183c5dc --- /dev/null +++ b/lanes/r14-r2.report.md @@ -0,0 +1,97 @@ +# lane-r14 round 2 — 64-axis rectangular INTER residual coding + +## Per-segment table (ReelB 2160p HDR10, `-c:v copy -an -f obu`, 2 s each) + +| segment | refusal BEFORE this round (at merged main) | refusal AFTER this round | counters | +|---|---|---|---| +| `-ss 300 -t 2` (`seg300.obu`, 206 frame headers) | an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet | *unchanged* (same string, same site `decode.rs:17325`) | rect_inter tu=28 txsplit=18 | +| `-ss 3000 -t 2` (`seg3000.obu`, 288 frame headers) | a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding — shape **32x64** at mi(0,32) | a split transform on a 1:4 inter strip with a 64-px axis | 22 SB-level 32x64 strips decoded, tu=21, txsplit=4 | +| `-ss 4500 -t 2` (`seg4500.obu`, 213 frame headers) | a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding — shape **16x64** at mi(0,0) | a split transform on a 1:4 inter strip with a 64-px axis | txsplit=1 | + +`kf300.obu` (the r1 blocker): the `git merge main` of this round already advanced it past +"a non-skip rectangular ... needs rectangular residual coding" to the intra-rect-strip refusal — +lane-inter4's merge lifted it, the charter's premise was stale. It is **not** one key frame: +`decode_probe` parses 206 frame headers in it. (`ffmpeg -i kf300.obu -bsf:v trace_headers` +prints nothing at all for a bare `.obu` — no container, so the bitstream filter is never +attached; the header count from our own parser is the measurement used instead.) + +## What changed + +- `crates/ec-av1/src/decode.rs:10891 rect_inter_residual_supported` — accepts `(64,32) (32,64) (64,16) (16,64)`. +- `crates/ec-av1/src/decode.rs:10903 rect_inter_luma_set` — `TxbSet::Luma64` for 64x32/32x64, + `TxbSet::LumaRect32x16` for 64x16/16x64 (`av1_get_adjusted_tx_size`; both sets carry + `tx_type: None`, correct because `tx_size_sqr_up == TX_64X64` makes the ext-tx set DCT_ONLY, + so no `tx_type` symbol is coded and the intra/inter table split is moot). +- `crates/ec-av1/src/decode.rs:10921 rect_inter_chroma_set` — 32x16/16x32 → `ChromaRect32x16`, + 32x8/8x32 → `Chroma16` (same sets the INTRA superblock-strip path already uses). +- `crates/ec-av1/src/decode.rs rect_scan` — `SCAN_32X8` / `SCAN_8X32` arms. +- `crates/ec-av1/src/decode.rs read_inter_plane_rect` — the load-bearing change: a 64-length axis + codes only its low 32 coefficients, so the unit read is the `min(w,32) x min(h,32)` corner, + zero-extended into the true `w x h` grid before `dequant_and_inverse_typed_wh`. A square 32x32 + corner goes through the SQUARE reader with `rect_shape = Some((w, h))`, because + `av1_nz_map_ctx_offset` is indexed by the real un-adjusted shape (class from lane-sbpart r8). +- `crates/ec-av1/src/decode.rs read_block_tx_size_rect` — NEW named refusal + `"a split transform on a 1:4 inter strip with a 64-px axis"`: `sub_tx_size_map` is square for + every shape this decoder splits (TX_32X16→TX_16X16, TX_64X32→TX_32X32) except TX_64X16→TX_32X16 + and TX_16X64→TX_16X32, where the existing square recursion would code the wrong tree. +- `crates/ec-av1/src/decode.rs` + `stream.rs:60` — `rect64_inter_tu_hits()` counter (luma 64-axis TUs). +- `crates/ec-av1/src/refusal_inventory.rs` — the new refusal registered. +- `crates/ec-av1/src/stream.rs` gate + `a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact` + now hard-asserts `rect64_tus > 0` (the residual half of the arm; before, the gate proved only + the partition symbol because every strip it accepted was `skip`). + +Merge commit `399278b` resolved the single conflict (`cdf_state.rs` TxbSet match) by keeping BOTH +sides' arms (lane's 16x4 intra 1:4, main's 16x8 inter rect). + +## Gates + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- --test-threads=1 superblock_level_rect_partition` + +EVIDENCE: gate stderr | real aomenc 192x128x6, `--enable-rect-partitions=1 --min-partition-size=32 --max-partition-size=64 --sb-size=64`, 16 attempts, every decoded frame compared Y+U+V vs ffmpeg | 8-bit: 2 named refusals, 4 pixel-exact attempts carrying the arm, 64x32 strips=4, 32x64 strips=4, **64-axis residual TUs=2**, 10 out of scope (0 mismatched) — test result: ok + +EVIDENCE: same gate run with `for bit_depth in [8u32, 10u32]` | identical recipe at `--bit-depth=10` | 10-bit: 2 pixel-exact attempts carrying the arm, 64x32=2, 32x64=2, **64-axis residual TUs=2** — the capability is pixel-exact at 10 bits too + +EVIDENCE: `cargo run --example decode_probe -- seg3000.obu` before/after, `EC_AV1_RECT_DUMP=1` | 2 s of the real film at 50:00 | `EC_RECT_REFUSE ... w=32 h=64` → no `EC_RECT_REFUSE` line at all; 22 SB-level 32x64 strips now decode + +Merge-verification gates (on `399278b`): `16_level_1to4 superblock_level_ 32x32_level_1to4 +inter_sequence refusal_inventory gate_coverage` → 38 passed, 0 failed, 4 ignored. + +Full suite: `$HOME/.cache/r14-suite-r2.log`, run on the tip after the second `git merge main` +(main `b51719f`) — totals appended below. + +## Verifier notes folded in (round 2) + +1. `lanes/r14-r1.report.md:18` corrected: the "104 / 172" pair is `decode_probe`'s **rect4_32** + counter line, not rect4_16; the true rect4_16 numbers on `kf300.obu` are 96, 148, 122, 311, 63. +2. `"a 16x16-level partition value outside PARTITION_NONE..PARTITION_VERT_4"` was unreachable + (all 10 symbols of that CDF are handled above the check) — removed from `decode.rs` (now a + `debug_assert_eq!(part16, PARTITION_SPLIT)`) and from `refusal_inventory.rs`. +3. The rectangular-residual wall lives in `decode_inter_block`, reached only from + `decode_inter_frame_tile`, so it fires on an **inter** frame: the key frame of `kf300.obu` + decodes through. **Not measured this round**: the decode-order index of the stopping frame and + a 16-bit byte-equality compare of every frame before it. `decode_probe` reports only the + refusal, and adding the per-frame `cmp` ladder did not fit this round's budget — + deferred(a `decode_probe` mode that dumps every decoded frame before the refusal and diffs it + against `ffmpeg -pix_fmt yuv420p10le`). + +## Residue + +- **deferred**(needs a rect-aware var-tx recursion + rect leaf reconstruction, ~2 call sites): + `a split transform on a 1:4 inter strip with a 64-px axis`. This is the film's next blocker in + BOTH mid-film segments. `sub_tx_size_map[TX_64X16] = TX_32X16` is rectangular, so the leaf + tuple `(row, col, tx_px)` and the two square leaf loops (`decode.rs` ~16174 and ~17150) have to + carry `(row, col, tw, th)`. Out of this round's ≤150-line scope. +- **deferred**(unrelated shape, needs its own bisect): enabling the 10-bit arm of the SB rect gate + exposes a pre-existing mismatch at attempt 14 (cq 61, horizontal split, motion step 12) that + decodes **zero** rect strips and zero 64-axis residual units — provably not this round's code + path. The gate stays `[8u32]` with that measured reason written at the loop instead of the + stale "non-skip residual is refused" one. +- **accepted**: `seg300` still stops at the intra-rect-strip refusal (lane-intrarect's wall, + named and inventoried). + +## Suite + +`systemd-run --user --unit=r14-suite-r2 ... cargo test -p ec-av1 --lib -j3` on tip `c604580` +(after `git merge main` @ `b51719f`) -> **365 passed; 0 failed; 31 ignored**, 623.58s, +log `$HOME/.cache/r14-suite-r2.log`.