diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index bee8f0f7..168c208c 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -40,6 +40,8 @@ fn main() { "inter_ab16: horz_a={} horz_b={} vert_a={} vert_b={}", ab[0], ab[1], ab[2], ab[3] ); + let (h4, v4, pairs, sub8) = ec_av1::decode::inter16_rect4_counters(); + println!("inter16_1to4: horz4={h4} vert4={v4} chroma_pairs={pairs} sub8_pieces={sub8}"); let ir = ec_av1::stream::inter_rect_counters(); println!( "inter_rect: 32x8={} 8x32={} 64x32={} 32x64={} 64x16={} 16x64={}", diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 7eef9418..0a4a36ae 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -230,6 +230,19 @@ pub(crate) enum TxbSet { /// counterpart: `EXT_TX_SET_DTT4_IDTX_1DDCT`, the seven-symbol `TX_4X4` /// row [`LumaRect4x8Set1`](TxbSet::LumaRect4x8Set1) reads. LumaRect16x4Set1, + /// [`LumaRect16x4`](TxbSet::LumaRect16x4)'s INTER counterpart + /// (lane-inter16ab r2): the same `Luma8` coefficient tables (64 coded + /// positions, `get_txsize_entropy_ctx(TX_16X4)` = TX_8X8), with the + /// INTER `tx_type` table at `txsize_sqr_map[TX_16X4]` = TX_4X4. + /// `av1_get_ext_tx_set_type` (av1/common/idct.c): `tx_size_sqr_up` is + /// TX_16X16 (not > TX_32X32) and `use_reduced_set` picks + /// `EXT_TX_SET_DCT_IDTX` -- three symbols, `inter_tx_type_4`. + LumaRect16x4Inter, + /// [`LumaRect16x4Inter`](TxbSet::LumaRect16x4Inter)'s + /// `reduced_tx_set: false` counterpart: `tx_size_sqr` is TX_4X4, not + /// TX_16X16, so `av1_get_ext_tx_set_type` returns `EXT_TX_SET_ALL16` -- + /// sixteen symbols, `inter_tx_type_4_set1`. + LumaRect16x4Inter1, } /// The tables one transform block is coded with, borrowed from the state for @@ -1851,6 +1864,30 @@ impl Cdfs { 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::LumaRect16x4Inter => 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.inter_tx_type_4.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_64_luma_class1), + }, + TxbSet::LumaRect16x4Inter1 => 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.inter_tx_type_4_set1.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 ad69ab3d..b415a3e6 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2201,6 +2201,64 @@ pub fn ab16_inter_hits_by_arm() -> [usize; 4] { AB16_INTER_HITS.with(std::cell::Cell::get) } +// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4 +// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS` +// counts the odd strips that close a 4:2:0 chroma pair +// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row), +// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from +// the PREVIOUS strip's own mv/ref/filters -- libaom +// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached +// through `is_sub8x8_inter` (same file, :54). +thread_local! { + static INTER16_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER16_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER16_CHROMA_PAIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER16_SUB8_PIECE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16 +/// strips, chroma pairs closed, chroma pairs built from two different +/// strips' motion vectors)`. +pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) { + ( + INTER16_HORZ4_HITS.with(std::cell::Cell::get), + INTER16_VERT4_HITS.with(std::cell::Cell::get), + INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get), + INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get), + ) +} + +/// One 16x4 / 4x16 inter strip's chroma situation, handed to +/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom +/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites +/// that all mean "an ordinary block, chroma of its own". +#[derive(Clone, Copy)] +struct InterStripChroma { + /// `is_chroma_reference` for this strip: false on strips 0 and 2, which + /// read and reconstruct NO chroma at all. + has_chroma: bool, + /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`. + horz: bool, + /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s + /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`, + /// i.e. the origin of the 8x4 (4x8) chroma transform. + pair_mi: (usize, usize), + /// The previous (even) strip's single-reference MC parameters, `None` + /// when it was intra or compound -- `is_sub8x8_inter` then returns false + /// and the whole chroma block is predicted from THIS strip's mv. + prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>, +} + +thread_local! { + static INTER_STRIP_CHROMA: std::cell::Cell> = + const { std::cell::Cell::new(None) }; + /// The single-reference MC parameters of the inter block that decoded + /// last -- read by the next 1:4 strip to build its pair's chroma. + static INTER_LAST_MC: std::cell::Cell< + Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>, + > = const { std::cell::Cell::new(None) }; +} + fn bump_ab16_inter(arm: usize) { AB16_INTER_HITS.with(|c| { let mut v = c.get(); @@ -11455,6 +11513,10 @@ fn rect_inter_residual_supported(w: usize, h: usize) -> bool { (w, h), // 2:1 strips whose transform is coded in full (lane-inter4). (32, 16) | (16, 32) | (16, 8) | (8, 16) + // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16 + // codes all 64 of its positions, and its chroma pair is an 8x4 / + // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4). + | (16, 4) | (4, 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 @@ -11477,6 +11539,13 @@ fn rect_inter_residual_supported(w: usize, h: usize) -> bool { fn rect_inter_luma_set(w: usize, h: usize) -> TxbSet { match (w, h) { (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter, + (16, 4) | (4, 16) => { + if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) { + TxbSet::LumaRect16x4Inter + } else { + TxbSet::LumaRect16x4Inter1 + } + } (16, 8) | (8, 16) => { if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) { TxbSet::LumaRect16x8Inter @@ -11553,6 +11622,8 @@ fn rect_scan(w: usize, h: usize) -> &'static [u16] { (16, 32) => &SCAN_16X32, (16, 8) => &SCAN_16X8, (8, 16) => &SCAN_8X16, + (16, 4) => &SCAN_16X4, + (4, 16) => &SCAN_4X16, (8, 4) => &SCAN_8X4, (4, 8) => &SCAN_4X8, (32, 8) => &SCAN_32X8, @@ -11633,6 +11704,14 @@ fn read_block_tx_size_rect( "a split transform on a 1:4 inter strip with a 64-px axis", )); } + // lane-inter16ab r2: same shape one size class down -- + // `sub_tx_size_map[TX_16X4]` is TX_8X4, still rectangular, so the square + // recursion below would code the wrong tree. + if tx_w.max(tx_h) == 16 && tx_w.min(tx_h) == 4 { + return Err(unsupported( + "a split transform on a 16x16-level 1:4 inter strip (sub_tx_size_map[TX_16X4] is the rectangular TX_8X4)", + )); + } 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)); @@ -16100,9 +16179,27 @@ fn decode_inter_block( // exactly what it read before. let (rmi, cmi) = at; let (px, py) = (at.1 * MI, at.0 * MI); - let (cpx, cpy) = (px / 2, py / 2); + // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's + // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd + // strip (`is_chroma_reference`); every other block keeps its own. + let strip_chroma = INTER_STRIP_CHROMA.with(std::cell::Cell::take); + INTER_LAST_MC.with(|c| c.set(None)); + let has_chroma = strip_chroma.is_none_or(|s| s.has_chroma); + let (cpx, cpy) = match strip_chroma { + Some(s) if s.has_chroma => (s.pair_mi.1 * MI / 2, s.pair_mi.0 * MI / 2), + _ => (px / 2, py / 2), + }; let chroma_side = side / 2; - let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2); + let (write_chroma_w, write_chroma_h) = match strip_chroma { + Some(s) if s.has_chroma => { + if s.horz { + (8, 4) + } else { + (4, 8) + } + } + _ => (write_w / 2, write_h / 2), + }; if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( @@ -16126,7 +16223,12 @@ fn decode_inter_block( let (seg_mi_r, seg_mi_c) = (rmi, cmi); let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4); inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true); - let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; + // libaom `read_skip_mode` (decodemv.c): `if (!is_comp_ref_allowed(bsize)) + // return 0` -- a 16x4 / 4x16 strip (min(bw, bh) == 4, blockd.h:65) reads + // no `skip_mode` symbol at all. + let comp_allowed = write_w.min(write_h) >= 8; + let skip_mode = + skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() { eprintln!( "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}", @@ -16238,7 +16340,12 @@ fn decode_inter_block( ); } let is_compound = - skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr)); + skip_mode + || (reference_select + // `is_comp_ref_allowed` (blockd.h:65) gates the + // `comp_mode` read exactly as it gates `skip_mode`. + && comp_allowed + && read_comp_mode(dec, cdfs, above_nbr, left_nbr)); if is_compound { let (ref0, ref1) = if skip_mode { (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8) @@ -17495,6 +17602,9 @@ fn decode_inter_block( // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied). let motion_mode_eligible = switchable_motion_mode && !skip_mode + // `is_motion_variation_allowed_bsize` (blockd.h:1455): + // min(bw, bh) >= 8, false for a 16x4 / 4x16 strip. + && write_w.min(write_h) >= 8 && interintra_mode.is_none() && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty() || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1) @@ -17803,6 +17913,11 @@ fn decode_inter_block( } } + // lane-inter16ab r2: `is_sub8x8_inter`'s neighbour walk reads the + // PREVIOUS strip's `mv`/`ref_frame`/`interp_filters` + // (reconinter_template.inc:75-82); record them for the next 1:4 + // strip, which is the only reader. + INTER_LAST_MC.with(|c| c.set(Some((ref_frame, mv, h_filter, v_filter)))); let mut pred_y = vec![0u16; side * side]; let mut pred_u = vec![0u16; chroma_side * chroma_side]; let mut pred_v = vec![0u16; chroma_side * chroma_side]; @@ -17964,6 +18079,46 @@ fn decode_inter_block( interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v); } + // lane-inter16ab r2: libaom `build_inter_predictors_sub8x8` + // (reconinter_template.inc:87-160). A 4:2:0 chroma block under a + // 16x4 (4x16) luma pair covers TWO luma blocks, so it is built in + // `b4_w x b4_h` = 8x2 (2x8) pieces, each from its own strip's + // mv/ref/filters. The bottom (right) piece is this strip's own mv + // over its own rows, which the whole-block prediction above + // already wrote there (MC is position-invariant for a fixed mv), + // so only the FIRST piece has to be rebuilt -- and only when + // `is_sub8x8_inter` holds, i.e. the previous strip was itself a + // single-reference inter block (`prev`), else libaom falls + // through to the ordinary whole-block predictor. + if let Some(s) = strip_chroma.filter(|s| s.has_chroma) + && let Some((prev_ref, prev_mv, prev_h, prev_v)) = s.prev + && luma_scale == mc::REF_NO_SCALE + { + let (piece_w, piece_h) = if s.horz { (8usize, 2usize) } else { (2usize, 8usize) }; + let (_, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?; + for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] { + let mut piece = vec![0u16; piece_w * piece_h]; + mc::predict_with_filters( + &src.data, + src.width, + src.true_width, + src.true_height, + mv_to_q4(cpx, prev_mv.1, false), + mv_to_q4(cpy, prev_mv.0, false), + piece_w, + piece_h, + prev_h, + prev_v, + &mut piece, + ); + for row in 0..piece_h { + dst[row * chroma_side..row * chroma_side + piece_w] + .copy_from_slice(&piece[row * piece_w..(row + 1) * piece_w]); + } + } + INTER16_SUB8_PIECE_HITS.with(|c| c.set(c.get() + 1)); + } + // lane-inter4 r2: a rectangular strip's transform tree starts from // its own rect `max_txsize_rect_lookup` entry, not a square one. let rect_tu = (write_w, write_h) != (side, side); @@ -18000,24 +18155,26 @@ fn decode_inter_block( &pred_y, &vec![0i32; side * side], ); - u.reconstruct_mc_rect( - cpx, - cpy, - chroma_side, - write_chroma_w, - write_chroma_h, - &pred_u, - &vec![0i32; chroma_side * chroma_side], - ); - v.reconstruct_mc_rect( - cpx, - cpy, - chroma_side, - write_chroma_w, - write_chroma_h, - &pred_v, - &vec![0i32; chroma_side * chroma_side], - ); + if has_chroma { + u.reconstruct_mc_rect( + cpx, + cpy, + chroma_side, + write_chroma_w, + write_chroma_h, + &pred_u, + &vec![0i32; chroma_side * chroma_side], + ); + v.reconstruct_mc_rect( + cpx, + cpy, + chroma_side, + write_chroma_w, + write_chroma_h, + &pred_v, + &vec![0i32; chroma_side * chroma_side], + ); + } luma_grid = vec![0i32; side * side]; u_grid = vec![0i32; chroma_side * chroma_side]; v_grid = vec![0i32; chroma_side * chroma_side]; @@ -18030,6 +18187,18 @@ fn decode_inter_block( } else { neighbours.around_mi(at, side) }; + // lane-inter16ab r2: the pair's chroma transform sits at the + // EVEN strip's mi origin and spans both strips, so its + // above/left coefficient context is the pair's, not this + // strip's row. + let around_c = match strip_chroma { + Some(s) if s.has_chroma => neighbours.around_mi_rect( + s.pair_mi, + if s.horz { 16 } else { 8 }, + if s.horz { 8 } else { 16 }, + ), + _ => around, + }; let luma_tx_type; if let Some(leaves) = vartx_leaves.clone() { // spec 5.11.17's transform tree, leaf by leaf in the order @@ -18115,7 +18284,16 @@ fn decode_inter_block( None, )?; } - if rect_tu { + if !has_chroma { + // `is_chroma_reference` is false for this strip: libaom's + // plane loop (decodeframe.c + // `predict_and_reconstruct_intra_block`/ + // `reconstruct_inter_block`'s `for (plane...)` guarded by + // `xd->is_chroma_ref`) codes NO chroma transform here, so + // neither symbol nor context exists. + u_grid = vec![0i32; chroma_side * chroma_side]; + v_grid = vec![0i32; chroma_side * chroma_side]; + } else if rect_tu { // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a // 2:1 strip is the strip's own rect chroma size (16x8 / // 8x16), one unit for the whole block, and it codes no @@ -18129,7 +18307,7 @@ fn decode_inter_block( (uw, uh), chroma_side, 1, - around[1], + around_c[1], mode_for_tx, u, cpx, @@ -18150,7 +18328,7 @@ fn decode_inter_block( (uw, uh), chroma_side, 2, - around[2], + around_c[2], mode_for_tx, v, cpx, @@ -18210,6 +18388,16 @@ fn decode_inter_block( // skip path above (which only needed a clipped write of an // already-square-predicted buffer). Named refusal instead of a // silently wrong square-shaped intra prediction. + // lane-inter16ab r2: `decode_intra_rect_in_inter` has no chroma-pair + // path (it predicts and codes chroma at the strip's own halved + // footprint), so an INTRA 16x4 / 4x16 strip inside a 1:4 partition is + // refused by name rather than decoded with a 8x2 chroma transform + // libaom never coded. + if write_w.min(write_h) < 8 { + return Err(unsupported( + "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)", + )); + } if write_w != side || write_h != side { // lane-intrarect r1: the strip decodes through its own rect // machinery ([`decode_intra_rect_in_inter`] -> the key-frame @@ -18606,6 +18794,14 @@ fn decode_inter_block( rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } + // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH + // strips (mirroring the intra `decode_rect4_16` path), and the even + // strip's own record wrote empty chroma state over those cells -- this + // rewrite is what libaom's single `av1_set_contexts` call for the 8x4 + // (4x8) chroma unit leaves behind. + let pair_chroma = strip_chroma + .filter(|s| s.has_chroma) + .map(|s| (s, neighbour_state(&u_grid), neighbour_state(&v_grid))); if vartx_leaves.is_some() { // Plane 0 is already correct per transform unit // ([`Neighbours::record_mi_luma`] above); this writes everything else @@ -18622,6 +18818,32 @@ fn decode_inter_block( &[luma_grid, u_grid, v_grid], ); } + if let Some((s, u_state, v_state)) = pair_chroma { + let (pw, ph) = if s.horz { (16usize, 8usize) } else { (8, 16) }; + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let (bound_h, bound_w) = ( + round_up_even(neighbours.mi_rows), + round_up_even(neighbours.mi_cols), + ); + for cell in 0..(ph / MI) { + if s.pair_mi.0 + cell < bound_h + && let Some(slot) = neighbours.left.get_mut(s.pair_mi.0 + cell) + { + slot[1] = u_state; + slot[2] = v_state; + } + } + for cell in 0..(pw / MI) { + if s.pair_mi.1 + cell < bound_w + && let Some(slot) = neighbours.above.get_mut(s.pair_mi.1 + cell) + { + slot[1] = u_state; + slot[2] = v_state; + } + } + neighbours.record_uv_mode_mi(s.pair_mi.0, s.pair_mi.1, pw / MI, ph / MI, uv_predict_mode); + INTER16_CHROMA_PAIR_HITS.with(|c| c.set(c.get() + 1)); + } neighbours.record_inter_rect_mi( at, write_w / MI, @@ -21368,9 +21590,96 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( inter_leaf8!(at16, br); } } + } else if part16 == PARTITION_HORZ_4 + || part16 == PARTITION_VERT_4 + { + // lane-inter16ab r2: four 16x4 (4x16) INTER + // strips. libaom `decode_partition` + // (decodeframe.c, PARTITION_HORZ_4/VERT_4) + // walks them top to bottom (left to right) + // with its own `i > 0` frame-edge break. + // + // Each strip is >= 8 in one dimension only, + // so `is_comp_ref_allowed`, + // `is_motion_variation_allowed_bsize` + // (blockd.h:65/1455, min(bw, bh) >= 8) and + // `is_interintra_allowed_bsize` (BLOCK_8X8.. + // BLOCK_32X32 in enum order, which excludes + // BLOCK_16X4 = 17) are all false: no + // skip_mode, no comp_mode, no OBMC/warp and + // no interintra symbol is read -- gated in + // `decode_inter_block` off `write_w`/ + // `write_h`. + // + // CHROMA is the pair's: + // `is_chroma_reference` + // (av1_common_int.h:1454) is false on the + // even strips, and the odd one codes one 8x4 + // (4x8) chroma transform at the pair's + // origin, built from BOTH strips' motion + // (`is_sub8x8_inter`). + let horz = part16 == PARTITION_HORZ_4; + let (mi_row0, mi_col0) = sub16_to_mi(at16); + let (bw, bh) = if horz { (16usize, 4usize) } else { (4usize, 16usize) }; + for i in 0..4usize { + let at_mi = if horz { + (mi_row0 + i, mi_col0) + } else { + (mi_row0, mi_col0 + i) + }; + if i > 0 + && (at_mi.0 >= mi_rows as usize + || at_mi.1 >= mi_cols as usize) + { + break; + } + let strip_has_chroma = i % 2 == 1; + let pair_mi = if !strip_has_chroma { + at_mi + } else if horz { + (at_mi.0 - 1, at_mi.1) + } else { + (at_mi.0, at_mi.1 - 1) + }; + INTER_STRIP_CHROMA.with(|c| { + c.set(Some(InterStripChroma { + has_chroma: strip_has_chroma, + horz, + pair_mi, + prev: if strip_has_chroma { + INTER_LAST_MC.with(std::cell::Cell::get) + } else { + None + }, + })) + }); + inter_piece!( + at_mi, + SUB, + TxbSet::Luma16, + if reduced_tx_set { + TxbSet::Luma16Inter + } else { + TxbSet::Luma16InterSet1 + }, + TxbSet::Chroma8, + TX16, + TX8, + &scan16, + &scan8, + 1, + bw, + bh + ); + if horz { + INTER16_HORZ4_HITS.with(|c| c.set(c.get() + 1)); + } else { + INTER16_VERT4_HITS.with(|c| c.set(c.get() + 1)); + } + } } else if part16 != PARTITION_SPLIT { return Err(unsupported( - "an inter 16x16-level 1:4 partition (HORZ_4/VERT_4 -- four 16x4 or 4x16 inter strips; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT, SPLIT or AB)", + "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", )); } else { if has_cols16 && has_rows16 { diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 8e2ef78e..3fc3ecc6 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -67,14 +67,20 @@ const REFUSALS: &[&str] = &[ "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 transform units", "an inter frame with no key frame before it", "an inter SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B; this decoder's inter tile path codes a superblock as NONE, SPLIT, HORZ, VERT, HORZ_4 or VERT_4)", - // lane-inter16ab r1 lifted the AB half (HORZ_A/HORZ_B/VERT_A/VERT_B at - // the 16x16 level of an inter frame: two 8x8 inter leaves plus one true - // 16x8/8x16 inter strip, gate - // `a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact`). - // What is left is the 1:4 pair, whose 16x4/4x16 strips need the sub-8 - // inter chroma-pair path (odd-strip `is_chroma_reference`, chroma built - // from BOTH strips' MVs) that no inter block writer has yet. - "an inter 16x16-level 1:4 partition (HORZ_4/VERT_4 -- four 16x4 or 4x16 inter strips; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT, SPLIT or AB)", + // lane-inter16ab r1 lifted the AB half and r2 the 1:4 half (four 16x4 / + // 4x16 inter strips, their 8x4/4x8 chroma pair built from BOTH strips' + // motion vectors -- gate + // `a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact`). + // Two narrower refusals are what is left of that shape: + "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", + // r2 residue: `vartx_leaves` is a list of SQUARE units, and + // `sub_tx_size_map[TX_16X4]` is the rectangular TX_8X4 -- the split tree + // and its per-unit residual reader both need rect leaves. + "a split transform on a 16x16-level 1:4 inter strip (sub_tx_size_map[TX_16X4] is the rectangular TX_8X4)", + // r2 residue: `decode_intra_rect_in_inter` codes chroma at the strip's own + // halved footprint, which for a 16x4 strip is an 8x2 transform libaom + // never wrote (its chroma is the PAIR's 8x4, coded by the odd strip). + "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)", "an intra mode this decoder does not code (round 2)", // lane-intrarect r1 lifted the whole-shape refusal that stood here (the // inter path's intra arm now routes 2:1 strips through `decode_rect_split`); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index f6f6f2ef..dbd2babb 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -7697,6 +7697,244 @@ mod tests { } + + #[test] + // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame -- + // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter + // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is + // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped, + // out-of-scope mismatches fail the gate, and EACH of the four arms must + // have fired on a pixel-exact attempt (RD picking only HORZ_A is not + // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach + // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips); + // the last two counters are the chroma half of the claim -- the odd + // strip's `is_chroma_reference` pair and the pairs whose chroma was built + // from two different strips' motion vectors + // (`build_inter_predictors_sub8x8`). + fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + // Per arm, over both bit depths: how many pixel-exact attempts fired + // it at least once. + let mut arms_total = [0u32; 4]; + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = + (0u32, 0u32, 0u32, 0u32); + let mut arms_proved = [0u32; 4]; + for attempt in 0..32u32 { + // Two sources (structure along X vs along Y -- an AB + // partition needs an L/T-shaped feature, so both orientations + // are swept), four quantisers, two motion steps, two tiling + // arms. r1 measured (sweep script in the report): a 16-attempt + // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A + // at 8 bits, so the quantiser axis is four wide here; cq 46 on + // the X-structured source is deliberately NOT in the list -- + // that stream's decode-order frame 4 desyncs on a defect this + // lane does not own (aomdec's own EC_PART trace reads ZERO + // AB partitions at BLOCK_16X16 anywhere in it, so the AB + // counters it raises are read out of an already-diverged + // stream; see lanes/inter16ab-r1.report.md). + let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; + // The 10-bit arm swaps cq 40 for 28 on the same sources: at + // cq 40 the X-structured 10-bit stream mismatches ffmpeg with + // ZERO 16-level AB partitions in it (another shape's defect, + // measured r1 -- the gate's own `oos_mismatch` counter is + // what found it, and it is reported, not silenced). + let cq = if bit_depth == 10 { + [18, 22, 34, 28][(attempt / 2 % 4) as usize] + } else { + [18, 22, 34, 40][(attempt / 2 % 4) as usize] + }; + let natural = attempt / 8 % 2 == 1; + let group = attempt / 16; + // r1: a `--tile-columns=1` arm of this same sweep PANICS in + // `mc::from_switchable_symbol` (a 4th symbol out of a + // 3-symbol alphabet = someone else's desync, the signature + // the ledger already pins for the below-8x8 inter leaf), not + // in anything this lane added -- so the tiled arm is left out + // rather than turned into a SKIP or a weakened assert. + // Reported as residue in lanes/inter16ab-r1.report.md. + let tile_cols = "0"; + let sp = 3 + (group % 2) * 5; + let duration = frame_count as f64 / 25.0; + // Continuous-tone translating texture with a second, coarser + // component on the cross axis: aomenc's RD picks an AB + // partition where one 16x16 quadrant differs from its three + // siblings, which the two sinusoids at different periods + // produce all over the frame. + let lum = if natural { + format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)") + } else { + format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)") + }; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='{lum}',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let cq_arg = format!("--cq-level={cq}"); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let tx_arg = format!("--enable-tx-size-search={tx_search}"); + let tile_arg = format!("--tile-columns={tile_cols}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg, + // Per-arm overrides go LAST: aomenc keeps the last + // occurrence of a repeated --enable-* flag. + &tx_arg, + "--enable-rect-partitions=1", "--enable-ab-partitions=1", + "--enable-1to4-partitions=1", "--min-partition-size=4", + "--max-partition-size=16", + "--obu", "-o", "-", "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::inter16_rect4_counters(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let after = decode::inter16_rect4_counters(); + // [16x4 strips, 4x16 strips, chroma pairs closed, chroma + // pairs built from two strips' motion vectors]. + let fired = [ + after.0 - before.0, + after.1 - before.1, + after.2 - before.2, + after.3 - before.3, + ]; + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if fired[0] + fired[1] == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + 16-level inter AB partition -- another shape's defect" + ); + } + continue; + } + if mismatched { + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + let bad: Vec = + (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect(); + if !bad.is_empty() { + eprintln!( + "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ + pixels differ, first at ({}, {}), max |delta| {}", + bad.len(), + bad[0] % width, + bad[0] / width, + bad.iter() + .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) + .max() + .unwrap_or(0) + ); + } + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"); + } + for a in 0..4 { + if fired[a] > 0 { + arms_proved[a] += 1; + arms_total[a] += 1; + } + } + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying a 16-level inter 1:4 partition, per-arm attempts \ + HORZ_4/VERT_4/chroma-pair/sub8x8-chroma={arms_proved:?}, {out_of_scope} attempts carried \ + none ({oos_mismatch} of them mismatched)" + ); + assert_eq!( + oos_mismatch, 0, + "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \ + but mismatched ffmpeg -- a defect of another shape, not a pass" + ); + } + assert!( + arms_total.iter().all(|&n| n > 0), + "{NAME}: a 16-level inter 1:4 arm never fired on a pixel-exact attempt \ + (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs={arms_total:?}) -- an arm at 0 is \ + unproven; the last two are the odd-strip `is_chroma_reference` pair and the \ + `build_inter_predictors_sub8x8` two-mv chroma build" + ); + } + + #[test] fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() { if !have_ffmpeg() { diff --git a/lanes/COMMON-20260901.md b/lanes/COMMON-20260901.md index 07c3a305..517ff4f0 100644 --- a/lanes/COMMON-20260901.md +++ b/lanes/COMMON-20260901.md @@ -100,3 +100,9 @@ If you ran it: extract your own hunks, `git checkout -- crates/`, re-apply. never two suites per lane; film extracts ≤2 s; a watchdog (`ec-memwatch` user unit, log `$HOME/.cache/ec-memwatch.log`) SIGKILLs any codec/test process above 6 GiB RSS or the largest one when MemAvailable < 3 GiB — a killed run means YOUR command exceeded the budget: bound it, do not retry as-is. + +## WORKTREE SETUP (2026-09-02, three lanes lost a round to this) +A new worktree needs the TOP-LEVEL fixtures symlink: `ln -s /home/user/Documents/Code/Rust/edith_codecs/fixtures /fixtures`. +Without it exactly one gate fails: a_real_aomenc_stream_with_film_grain_decodes_pixel_exact with Os NotFound — it is NOT a decode defect. +New files under crates/ec-av1/fixtures/ need `git add -f` (bare `fixtures` in .gitignore); verify with `git ls-files`. +Commit-msg hook rejects film titles / home paths: describe streams by codec/resolution/bit depth. diff --git a/lanes/inter16ab-r2.report.md b/lanes/inter16ab-r2.report.md new file mode 100644 index 00000000..6e064368 --- /dev/null +++ b/lanes/inter16ab-r2.report.md @@ -0,0 +1,85 @@ +# lane-inter16ab r2 — 16x16-level 1:4 partitions in inter frames + +## Verdict: RED. The whole path is implemented and decodes, but one gate attempt +## (8-bit, attempt 5, cq 34, X-structured source) desyncs in its LAST frame. +The refusal is lifted and the gate is committed FAILING — not ignored, not weakened. +This branch must not merge into main until the residue below is closed. + +## What changed (all in `crates/ec-av1/`) +- `src/decode.rs:2207` — `InterStripChroma` + `INTER_STRIP_CHROMA` / `INTER_LAST_MC` + thread-locals (the one-shot `REDUCED_TX_SET_INTER` idiom, chosen over threading two + more parameters through `decode_inter_block`'s 23 call sites) and the four counters + `inter16_rect4_counters() -> (16x4 strips, 4x16 strips, chroma pairs, sub8x8 chroma pairs)`. +- `src/decode.rs` `decode_inter_block` entry — `has_chroma` (libaom `is_chroma_reference`, + av1_common_int.h:1454: `bh == 1 mi` ⇒ odd `mi_row`), and the chroma origin/extent + overridden to the PAIR's (8x4 / 4x8 at the even strip's mi origin — + `setup_pred_plane`'s `mi_row -= 1`). +- same fn — `is_comp_ref_allowed` / `is_motion_variation_allowed_bsize` + (blockd.h:65 / :1455, `min(bw,bh) >= 8`) now gate `skip_mode`, `comp_mode` and + `motion_mode`: a 16x4 strip reads none of those symbols. `is_interintra_allowed_bsize` + already excluded it (aspect 4:1). +- same fn — `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160): the pair's + chroma is built in `b4_w x b4_h` = 8x2 (2x8) pieces; the second piece is this strip's own + mv (already written by the whole-block predictor, MC being position-invariant for a fixed + mv), so only the FIRST piece is rebuilt, from the previous strip's mv/ref/filters, and only + when `is_sub8x8_inter` holds (previous strip single-ref inter — `INTER_LAST_MC`). +- same fn — chroma residual read/reconstruct/record all gated on `has_chroma`; the pair's + chroma coefficient context is read at `around_mi_rect(pair_mi, 16, 8)` and written back over + the pair's mi span (mirrors the intra `decode_rect4_16`). +- `src/decode.rs` `rect_scan` / `rect_inter_residual_supported` / `rect_inter_luma_set` — + (16,4)|(4,16): `SCAN_16X4`/`SCAN_4X16`, and the new `TxbSet::LumaRect16x4Inter{,1}` + (`Luma8` coefficient tables — `get_txsize_entropy_ctx(TX_16X4)` = TX_8X8, 64 positions, + `eob_pt_64` — with the INTER tx_type table at `txsize_sqr_map[TX_16X4]` = TX_4X4; + `av1_get_ext_tx_set_type` (blockd.h:1097-1106) gives EXT_TX_SET_ALL16 unreduced since + `tx_size_sqr != TX_16X16`, EXT_TX_SET_DCT_IDTX reduced). +- `src/cdf_state.rs:233,1854` — the two new `TxbSet` variants and their tables. +- `src/decode.rs` 16x16 partition chain — the `PARTITION_HORZ_4`/`_VERT_4` arm: four strips in + libaom `decode_partition` order with its own `i > 0` frame-edge break, each carrying its + `InterStripChroma`. +- `src/refusal_inventory.rs:70` — the combined 1:4 refusal is GONE; three narrower ones stand: + the partition-value catch-all, a split transform on a 16x4 strip, an intra 16x4 strip. +- `src/stream.rs` — gate + `a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact` + (r1's gate shape with `--enable-1to4-partitions=1 --min-partition-size=4`). +- `examples/decode_probe.rs:43` — prints `inter16_1to4: horz4= vert4= chroma_pairs= sub8_pieces=`. + +## Gate result — RED +`EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-inter16ab cargo test -p ec-av1 --lib a_real_aomenc_inter_sequence_with_16x16_level_1to4 -- --nocapture` + +EVIDENCE: gate stdout (suite log `$HOME/.cache/inter16ab-suite-r2.log`) | 192x128, 6 frames, real aomenc `--enable-1to4-partitions=1 --min-partition-size=4 --max-partition-size=16 --cpu-used=0`, every decode-order frame compared Y/U/V vs ffmpeg | 8-bit attempts 0..4: 2 named refusals ("an inter partition below 8x8" — `--min-partition-size=4` also lets aomenc split to sub-8 leaves, a different lane's refusal), earlier attempts pixel-exact; attempt 5 (cq 34, X-structured source, tx-size-search 1) fires arms [horz4=8, vert4=0, chroma_pairs=4, sub8x8_pairs=4] and MISMATCHES in decode-order frame 5 only: 8683 luma pixels, first at (96, 59), max |delta| 107. Frames 0-4 of that attempt are pixel-exact. + +Reading of the failure: frames 0-4 exact, then ~35% of the last frame wrong from a mid-frame +raster position = an ENTROPY DESYNC at one 16x16-level 1:4 block, not a prediction/filter +drift. `av1_get_ext_tx_set_type` was checked against the oracle source and the tables above are +right, so the leading suspect is the mv-stack at `BLOCK_16X4` (`bw4=4, bh4=1`): a wrong stack +size changes the `drl_idx` symbol count and desyncs at that block. NOT confirmed — no range +ladder was run this round (tool budget). + +## Film probe — moved one refusal deeper +`ffmpeg -ss 900 -t 2 -i -c:v copy -an -f obu` → `decode_probe`: +- before r2: `REFUSED: an inter 16x16-level 1:4 partition (HORZ_4/VERT_4 …)` +- after r2: `REFUSED: a split transform on a 16x16-level 1:4 inter strip + (sub_tx_size_map[TX_16X4] is the rectangular TX_8X4)` +1 frame completed (`EC_AV1_FINAL_DUMP` file count) in both. So the partition, the strips and +the chroma pair are past; the film now needs rect var-tx leaves. + +## Residue +- fix-now (next round, this lane): the attempt-5 desync above. Method: dump that attempt's + stream (add an env-gated write to the gate), run the instrumented aomdec `EC_TRACE=1` and + compare the msac RANGE element by element from the first 1:4 block of decode-order frame 5. + First check `find_mv_stack`'s row/col scan and weights for `bw4=4, bh4=1` (class + `scan-weights-cross-axis`). +- deferred: a SPLIT luma transform on a 16x4 strip — `vartx_leaves` is a list of SQUARE units + and `sub_tx_size_map[TX_16X4]` is the rectangular TX_8X4 (then TX_4X4). Unblocked by making + `vartx_leaves` carry `(row, col, w, h)` and routing each leaf through + `read_inter_plane_rect`. This is what BOTH films now stop at. +- deferred: an INTRA 16x4/4x16 strip inside a 1:4 partition — `decode_intra_rect_in_inter` + codes chroma at the strip's own halved footprint (an 8x2 transform libaom never wrote). + Unblocked by giving that path the same pair treatment. +- deferred: `git merge --no-commit main` (main is at 85887c7, this branch's base is 18bf7dc). + Not run: the suite was already in flight in this worktree and a merge under it is exactly the + self-inflicted flake COMMON warns about. The merge is owed before any merge to main. +- accepted: the gate keeps `--tile-columns=0` (r1's `--tile-columns=1` panic in + `mc::from_switchable_symbol` is the below-8x8 inter leaf desync, not this shape). No new + per-mi neighbour map was added — the pair chroma write reuses the existing `above`/`left` + bands and never crosses the 16x16 block, so no tile-edge guard is in question.