diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index a0667b0b..92c83905 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -31,6 +31,13 @@ fn main() { let report = || { let (h, v, c) = ec_av1::stream::rect4_32_counters(); println!("rect4_32: horz={h} vert={v} coded={c}"); + let (rtu, rsplit, robmc) = ec_av1::stream::rect_inter_tu_counters(); + println!("rect_inter: tu={rtu} txsplit={rsplit} obmc_leaf={robmc}"); + let ir = ec_av1::stream::inter_rect_counters(); + println!( + "inter_rect: 32x8={} 8x32={} 64x32={} 32x64={} 64x16={} 16x64={}", + ir.0, ir.1, ir.2, ir.3, ir.4, ir.5 + ); }; // lane-tiles: the tiling a real stream actually uses is a decision input // (every gate in `stream.rs` picks its own `--tile-columns`), so report it @@ -76,6 +83,19 @@ fn main() { // Optional second arg, or EC_PROBE_OUT=: dump the decoded // planes as raw yuv420p so a pixel diff against `ffmpeg -i s.obu // -f rawvideo` needs no test harness. + // 10-bit streams: EC_PROBE_OUT16 dumps the planes as little-endian + // u16 (yuv420p10le), the only form a pixel diff against + // `ffmpeg -pix_fmt yuv420p10le` can use (lane-band63). + if let Ok(out) = std::env::var("EC_PROBE_OUT16") { + let mut buf: Vec = Vec::new(); + for f in &frames { + for p in [&f.y, &f.u, &f.v] { + buf.extend(p.iter().flat_map(|&s| s.to_le_bytes())); + } + } + std::fs::write(&out, &buf).expect("writing raw planes"); + println!("wrote {} bytes of yuv420p10le to {out}", buf.len()); + } let out = std::env::args().nth(2).or_else(|| std::env::var("EC_PROBE_OUT").ok()); if let Some(out) = out { // 8-bit only: planes are u16, take the low byte. diff --git a/crates/ec-av1/fixtures/reelb_head_key_frame.obu b/crates/ec-av1/fixtures/reelb_head_key_frame.obu new file mode 100644 index 0000000000000000000000000000000000000000..ecc409b000d6550743e1c768e075b23186e41c08 GIT binary patch literal 147 zcmV;E0Brvf016KP003g^zw$Zv^PwUEDS#>l0R!g%dVne#0_gYEq$Xw$Tu=>E zIRFFb000000)R4F5CDe&fB*mh03grHo2NmWeoqO5rDriCF8GQw;s}Qn= 1` /// under `allow_warped_motion`) -- lane-warp round 1. -pub const MOTION_MODE: [[u16; 4]; 6] = [ +pub const MOTION_MODE: [[u16; 4]; 14] = [ [7651, 24760, 32768, 0], [19419, 26810, 32768, 0], [26260, 29116, 32768, 0], @@ -1666,6 +1680,18 @@ pub const MOTION_MODE: [[u16; 4]; 6] = [ // lane-rect r2: BLOCK_16X32 / BLOCK_32X16 rows (indices 7/8). [5123, 23606, 32768, 0], [11606, 24308, 32768, 0], + // lane-inter4 r1: BLOCK_32X64 / 64X32 / 8X32 / 32X8 / 16X64 / 64X16 rows + // (libaom `default_motion_mode_cdf` indices 10, 11, 18, 19, 20, 21). + [20360, 28062, 32768, 0], + [21679, 26830, 32768, 0], + [28799, 31390, 32768, 0], + [26431, 30774, 32768, 0], + [28973, 31594, 32768, 0], + [29742, 31203, 32768, 0], + // lane-inter4 r3: BLOCK_8X16 / BLOCK_16X8 rows (libaom + // `default_motion_mode_cdf` indices 4 and 5). + [4738, 24765, 32768, 0], + [5391, 25528, 32768, 0], ]; /// `default_interintra_cdf` (spec 9.4): `interintra`, indexed by diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index e9c1ad99..47035982 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -119,6 +119,16 @@ pub(crate) enum TxbSet { /// [`LumaRect32x16`](TxbSet::LumaRect32x16) has none). LumaRect32x8, LumaRect32x16, + /// lane-inter4 r2: [`LumaRect32x16`](TxbSet::LumaRect32x16)'s INTER twin -- + /// same coefficient tables (`get_txsize_entropy_ctx` reduces TX_32X16 and + /// TX_16X32 alike to the 32x32 set, 512-coefficient `eob_pt`), but an + /// inter block DOES code a `tx_type` symbol here: `av1_get_ext_tx_set_type` + /// with `tx_size_sqr_up == TX_32X32` and `is_inter` returns + /// `EXT_TX_SET_DCT_IDTX` (2 symbols), whose CDF is + /// `default_inter_ext_tx_cdf[3][txsize_sqr_map[TX_32X16] == TX_16X16]`, + /// i.e. exactly [`INTER_TX_TYPE_SET3_16`](crate::cdf::INTER_TX_TYPE_SET3_16) + /// -- the same table the square `Luma16Inter` set reads. + LumaRect32x16Inter, /// The chroma 16x8/8x16 transform under the same strip (lane-rectwire): /// [`Chroma16`](TxbSet::Chroma16)'s tables except `eob_pt`, which reads /// the true 128-position [`crate::cdf::EOB_PT_128_CHROMA`] instead of @@ -165,6 +175,24 @@ pub(crate) enum TxbSet { /// 16x16 row's five-symbol reduced CDF here and desynced on the very /// first coded rect leaf. LumaRect16x8Set1, + /// lane-inter4 r3: [`LumaRect16x8`](TxbSet::LumaRect16x8)'s INTER twin -- + /// the same coefficient tables (`get_txsize_entropy_ctx` reduces TX_16X8 + /// and TX_8X16 alike to the 16x16 set, 128-position `eob_pt`), with the + /// inter `tx_type` alphabet in place of the intra one. Under + /// `reduced_tx_set` `av1_get_ext_tx_set_type` (`tx_size_sqr_up == + /// TX_16X16`, `is_inter`) returns `EXT_TX_SET_DCT_IDTX` (2 symbols), + /// whose CDF row is `default_inter_ext_tx_cdf[1][txsize_sqr_map[TX_16X8] + /// == TX_8X8]`, i.e. [`INTER_TX_TYPE_SET3_8`](crate::cdf::INTER_TX_TYPE_SET3_8) + /// -- the same table the square `Luma8Inter` set reads. + LumaRect16x8Inter, + /// [`LumaRect16x8Inter`](TxbSet::LumaRect16x8Inter)'s `reduced_tx_set: + /// false` counterpart: `tx_size_sqr` is `TX_8X8` here (NOT the + /// `txsize_sqr_up_map` `TX_16X16` the coefficient tables use), so + /// `av1_ext_tx_set_lookup[is_inter=1][tx_size_sqr == TX_16X16 -> 0]` is + /// `EXT_TX_SET_ALL16` -- sixteen symbols, `default_inter_ext_tx_cdf[1] + /// [TX_8X8]`, i.e. [`INTER_TX_TYPE_SET1_8`](crate::cdf::INTER_TX_TYPE_SET1_8), + /// the table [`Luma8InterSet1`](TxbSet::Luma8InterSet1) also reads. + LumaRect16x8InterSet1, /// The chroma 8x4/4x8 transform under the same leaf (lane-rectx): /// [`Chroma8`](TxbSet::Chroma8)'s tables except `eob_pt`, which reads the /// true 32-position [`crate::cdf::EOB_PT_32_CHROMA`] instead of @@ -475,13 +503,13 @@ pub(crate) struct Cdfs { /// `BLOCK_8X8`, 1 = `BLOCK_16X16`, 2 = `BLOCK_32X32`, 3 = `BLOCK_64X64` /// (`default_obmc_cdf`'s own `BLOCK_SIZES_ALL` indices 3/6/9/12 -- /// this decoder only ever codes those four square sizes). - pub obmc: [[u16; 3]; 6], + pub obmc: [[u16; 3]; 14], /// `motion_mode` (spec 5.11.24's `read_motion_mode`), the 3-symbol /// `SIMPLE_TRANSLATION`/`OBMC_CAUSAL`/`WARPED_CAUSAL` alphabet read /// instead of [`Self::obmc`] whenever `motion_mode_allowed` resolves to /// `WARPED_CAUSAL`-eligible -- same square-bsize indexing as `obmc`. /// lane-warp round 1. - pub motion_mode: [[u16; 4]; 6], + pub motion_mode: [[u16; 4]; 14], /// `interintra`, indexed by `size_group_lookup[bsize]` -- see /// `cdf::INTERINTRA`'s own doc. pub interintra: [[u16; 3]; 4], @@ -1687,6 +1715,18 @@ impl Cdfs { tx_type: None, eob_pt_class1: Some(&mut self.eob_pt_256_luma_class1), }, + TxbSet::LumaRect32x16Inter => TxbTables { + side: 32, + txb_skip: &mut self.txb_skip_luma_32, + eob_pt: &mut self.eob_pt_512_luma, + eob_extra: &mut self.eob_extra_luma_32, + base: &mut self.base_luma_32, + base_eob: &mut self.base_eob_luma_32, + br: &mut self.br_luma_32, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_16.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_512_luma_class1), + }, TxbSet::LumaRect32x16 => TxbTables { side: 32, txb_skip: &mut self.txb_skip_luma_32, @@ -1771,6 +1811,30 @@ impl Cdfs { tx_type: Some(self.intra_tx_type_8_set1[mode].as_mut_slice()), eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), }, + TxbSet::LumaRect16x8Inter => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_128_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_8.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), + }, + TxbSet::LumaRect16x8InterSet1 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_128_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_8_set1.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), + }, TxbSet::ChromaRect8x4 => TxbTables { side: 8, txb_skip: &mut self.txb_skip_chroma_8, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3b4649b4..990cdc73 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -142,6 +142,27 @@ pub(crate) fn intra_in_inter_filter_intra_hits() -> usize { INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get()) } +// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a +// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both +// arms refused a nonzero luma delta before this round, and no inter gate +// enabled `--enable-angle-delta` (aomenc's own default is 1). +thread_local! { + static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; + static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`]. +pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize { + INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get()) +} + +/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`]. +pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize { + INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get()) +} + // lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into // [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a // frame-level flag through the recursive block decode -- `0` (the default) @@ -955,6 +976,15 @@ pub(crate) fn tx_depth_hits() -> usize { thread_local! { static TXFM_SPLIT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; static TXFM_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + // lane-inter4 r2: rectangular INTER residual coding -- how many rect + // strips coded one whole-block rect transform unit, and how many split + // their rect max transform into square sub-transforms. + static RECT_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT_INTER_TXSPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter + // frame -- 16x8 and 8x16 inter leaves. + static INTER_LEAF16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_LEAF16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits, // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] -- // `decode_inter_block` already carries forty parameters and both are @@ -978,6 +1008,26 @@ pub(crate) fn txfm_split_hits() -> usize { TXFM_SPLIT_HITS.with(|c| c.get()) } +/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3). +pub(crate) fn inter_leaf16_horz_hits() -> usize { + INTER_LEAF16_HORZ_HITS.with(|c| c.get()) +} + +/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3). +pub(crate) fn inter_leaf16_vert_hits() -> usize { + INTER_LEAF16_VERT_HITS.with(|c| c.get()) +} + +/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2). +pub(crate) fn rect_inter_tu_hits() -> usize { + RECT_INTER_TU_HITS.with(|c| c.get()) +} + +/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2). +pub(crate) fn rect_inter_txsplit_hits() -> usize { + RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) +} + /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/ /// [`ENABLE_FILTER_INTRA_INTER`]. pub(crate) fn set_inter_tx_mode( @@ -1059,6 +1109,21 @@ pub(crate) fn horz_vert_intra_hits() -> usize { HORZ_VERT_INTRA_HITS.with(|c| c.get()) } +// How many blocks were decoded as a frame-edge rect strip -- the single +// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge +// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose +// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter +// paths share the counter. +thread_local! { + static EDGE_RECT_STRIP_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`EDGE_RECT_STRIP_HITS`]. +pub(crate) fn edge_rect_strip_hits() -> usize { + EDGE_RECT_STRIP_HITS.with(|c| c.get()) +} + // How many HORZ/VERT intra strips resolved a SPLIT luma transform // (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- // the case every rect path here refused by name before, and the first @@ -1745,6 +1810,19 @@ pub(crate) fn wii_hits() -> usize { WII_HITS.with(|c| c.get()) } +// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC +// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the +// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented +// aomdec, neighbour list included). +thread_local! { + static OBMC_RECT_LEAF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`OBMC_RECT_LEAF_HITS`]. +pub(crate) fn obmc_rect_leaf_hits() -> usize { + OBMC_RECT_LEAF_HITS.with(|c| c.get()) +} + /// Current value of [`OBMC_HITS_8`]. pub(crate) fn obmc_hits_8() -> usize { OBMC_HITS_8.with(|c| c.get()) @@ -1979,6 +2057,17 @@ pub(crate) fn sb_rect4_vert_hits() -> usize { thread_local! { static RECT4_32_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT4_32_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-inter4 r1: the INTER-frame twins of the two counters above -- + /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` / + /// `PARTITION_VERT_4`. + static RECT4_32_HORZ_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_32_VERT_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT` + /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64). + static INTER_SB_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_SB_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_SB_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER_SB_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// How many 32x32-level 1:4 strips actually read coefficients (non-skip): @@ -2027,6 +2116,36 @@ pub(crate) fn rect4_32_vert_hits() -> usize { RECT4_32_VERT_HITS.with(|c| c.get()) } +/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded). +pub(crate) fn rect4_32_horz_inter_hits() -> usize { + RECT4_32_HORZ_INTER_HITS.with(|c| c.get()) +} + +/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded). +pub(crate) fn rect4_32_vert_inter_hits() -> usize { + RECT4_32_VERT_INTER_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded). +pub(crate) fn inter_sb_horz_hits() -> usize { + INTER_SB_HORZ_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded). +pub(crate) fn inter_sb_vert_hits() -> usize { + INTER_SB_VERT_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded). +pub(crate) fn inter_sb_horz4_hits() -> usize { + INTER_SB_HORZ4_HITS.with(|c| c.get()) +} + +/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded). +pub(crate) fn inter_sb_vert4_hits() -> usize { + INTER_SB_VERT4_HITS.with(|c| c.get()) +} + // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not @@ -2156,25 +2275,67 @@ pub(crate) fn build_motion_field( mi_cols: usize, mi_rows: usize, order_hint: u32, + order_hint_bits: u32, ref_order_hints: [u32; 7], ) -> crate::motion_field::MotionField { let mut field = - crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints); + crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false); + // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference + // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other + // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block + // referencing one stores only its OTHER side's mv. With + // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and + // nothing is skipped. + let other_side = |rf: i8| -> bool { + if order_hint_bits == 0 { + return false; + } + let oh = ref_order_hints[(rf - LAST_FRAME) as usize]; + crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0 + || oh == order_hint + }; + // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is + // capped at 12 bits per component; a longer one is not stored at all. + const REFMVS_LIMIT: i32 = (1 << 12) - 1; for row in 0..mi_rows { for col in 0..mi_cols { - if let Some(info) = grid.get(row, col) - && info.is_inter - && info.ref_frame > 0 - { - field.set( - row, - col, - crate::motion_field::SavedMv { - mv: info.mv, - ref_frame: info.ref_frame, - }, - ); + let Some(info) = grid.get(row, col) else { + continue; + }; + // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and + // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`), + // so an intra block -- or an inter block whose every slot is on the + // other side / over the limit -- wipes what an earlier block wrote + // into the same 8x8 cell (only reachable from sub-8x8 leaves, which + // share a cell). + if !info.is_inter { + field.set(row, col, None); + continue; + } + // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST + // qualifying one wins -- a compound block stores its second + // reference's mv, never its first (unless the second is on the + // other side or over the limit). Storing slot 0 unconditionally + // put the wrong (mv, ref_frame_offset) pair in every compound + // block's cell, which a later frame's temporal candidate then + // projected with the wrong reference distance. + let mut saved: Option = None; + for (rf, mv) in [ + (info.ref_frame, Some(info.mv)), + (info.ref_frame1.unwrap_or(0), info.mv1), + ] { + let (Some(mv), true) = (mv, rf > 0) else { + continue; + }; + if other_side(rf) { + continue; + } + if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT { + continue; + } + saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf }); } + field.set(row, col, saved); } } field @@ -4476,20 +4637,46 @@ impl Neighbours { uv_mode: usize, grids: &[Vec; 3], ) { - let (r, c) = at; + self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids); + } + + /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a + /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the + /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed + /// by the enclosing cell (a sub-16 extent writes none of them, exactly as + /// the [`SUB`]-unit path does). + fn record_rect_mi( + &mut self, + at_mi: (usize, usize), + w: usize, + h: usize, + mode: usize, + uv_mode: usize, + grids: &[Vec; 3], + ) { + let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI)); + // lane-inter4 r2: a strip whose own footprint runs past the frame's + // last 16-px column/row stamps only the cells that exist (libaom's + // arrays are padded past the frame and those cells are never read). for cell in 0..w / SUB { + if c + cell >= self.above_mode.len() { + break; + } self.above_mode[c + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h / SUB { + if r + cell >= self.left_mode.len() { + break; + } self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; } - self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode); - self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode); - self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids); + self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode); + self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode); + self.record_mi_rect(at_mi, w, h, grids); } /// The coefficient-context half of [`Self::record`], taking the block's @@ -4513,10 +4700,14 @@ impl Neighbours { let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); let (w_mi, h_mi) = (w / MI, h / MI); for cell in 0..h_mi { - self.left_side_mi[mi_r + cell] = h; + if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) { + *slot = h; + } } for cell in 0..w_mi { - self.above_side_mi[mi_c + cell] = w; + if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) { + *slot = w; + } } // A chroma 4x4 unit straddling the true luma edge is still whole in // chroma's own halved grid, so libaom rounds the luma bound up to the @@ -4647,23 +4838,34 @@ impl Neighbours { let (mi_r, mi_c) = at_mi; let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); for cell in 0..w.div_ceil(SUB) { + if c + cell >= self.above_mode.len() { + break; + } self.above_mode[c + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h.div_ceil(SUB) { + if r + cell >= self.left_mode.len() { + break; + } self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; } + let (w_mi, h_mi) = (w / MI, h / MI); self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode); self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode); for cell in 0..h_mi { - self.left_side_mi[mi_r + cell] = h; + if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) { + *slot = h; + } } for cell in 0..w_mi { - self.above_side_mi[mi_c + cell] = w; + if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) { + *slot = w; + } } let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); @@ -10013,8 +10215,25 @@ fn read_tx_size( /// the two neighbour terms (whether the transform last written above/left of /// this unit is narrower/shorter than the unit itself). fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize { - let above = usize::from(usize::from(above_px) < tx_px); - let left = usize::from(usize::from(left_px) < tx_px); + txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px) +} + +/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2): +/// libaom's `txfm_partition_context` compares the above context against +/// `tx_size_wide` and the left one against `tx_size_high`, and takes its +/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one +/// side for a square transform, which is why the square form above is a +/// special case of this one. +fn txfm_partition_ctx_rect( + above_px: u8, + left_px: u8, + blk_max_px: usize, + tx_w: usize, + tx_h: usize, +) -> usize { + let above = usize::from(usize::from(above_px) < tx_w); + let left = usize::from(usize::from(left_px) < tx_h); + let tx_px = tx_w.max(tx_h); // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as // `log2(px) - 2`. @@ -10029,16 +10248,30 @@ fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize /// resolved transform's own size. fn txfm_partition_update( n: &mut Neighbours, - (mi_r, mi_c): (usize, usize), + at_mi: (usize, usize), tx_px: usize, txb_px: usize, ) { - for i in 0..txb_px / MI { + txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px)); +} + +/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2): +/// the left column records `tx_size_high` over the parent's own height and +/// the above row records `tx_size_wide` over its width. +fn txfm_partition_update_rect( + n: &mut Neighbours, + (mi_r, mi_c): (usize, usize), + (tx_w, tx_h): (usize, usize), + (txb_w, txb_h): (usize, usize), +) { + for i in 0..txb_h / MI { if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { - *cell = tx_px as u8; + *cell = tx_h as u8; } + } + for i in 0..txb_w / MI { if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { - *cell = tx_px as u8; + *cell = tx_w as u8; } } } @@ -10260,6 +10493,264 @@ fn read_block_tx_size( Ok((tx, None)) } +/// lane-inter4 r2: the shapes whose *rectangular inter* residual this +/// decoder codes -- a 2:1 strip whose own max rect transform +/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a +/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient +/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a +/// 64-point rect transform, and 16x8/8x16 needs +/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol +/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a +/// rect transform), neither of which exists yet -- both stay refused by name. +fn rect_inter_residual_supported(w: usize, h: usize) -> bool { + matches!((w, h), (32, 16) | (16, 32) | (16, 8) | (8, 16)) +} + +/// The luma coefficient/`tx_type` table set of a whole-block rectangular +/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits +/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so +/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of +/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and +/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced +/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF +/// row (`txsize_sqr_map`), never the 16x16 one. +fn rect_inter_luma_set(w: usize, h: usize) -> TxbSet { + match (w, h) { + (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter, + (16, 8) | (8, 16) => { + if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) { + TxbSet::LumaRect16x8Inter + } else { + TxbSet::LumaRect16x8InterSet1 + } + } + _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), + } +} + +/// The chroma table set of the same block's single rectangular chroma unit +/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8 +/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit +/// the luma unit's. +fn rect_inter_chroma_set(w: usize, h: usize) -> TxbSet { + match (w, h) { + (16, 8) | (8, 16) => TxbSet::ChromaRect16x8, + (8, 4) | (4, 8) => TxbSet::ChromaRect8x4, + _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), + } +} + +/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's +/// inter path reaches, from the block's TRUE footprint rather than the +/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2, +/// everything 32 and above -> 3. +fn size_group_wh(w: usize, h: usize) -> usize { + // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom + // `common_data.h:60`) is 0 for every block with a 4-px side + // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old + // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0. + match w.min(h) { + 0..=4 => 0, + 8 => 1, + 16 => 2, + _ => 3, + } +} + +#[test] +fn size_group_wh_matches_libaom_size_group_lookup() { + // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s + // transcribed values (common_data.h:60-62). + const TABLE: [((usize, usize), usize); 22] = [ + ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1), + ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3), + ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3), + ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2), + ]; + for ((w, h), want) in TABLE { + assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})"); + } +} + +/// The default (2D) coefficient scan of a rectangular transform. +fn rect_scan(w: usize, h: usize) -> &'static [u16] { + match (w, h) { + (32, 16) => &SCAN_32X16, + (16, 32) => &SCAN_16X32, + (16, 8) => &SCAN_16X8, + (8, 16) => &SCAN_8X16, + (8, 4) => &SCAN_8X4, + (4, 8) => &SCAN_4X8, + _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), + } +} + +/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2): +/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own +/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The +/// depth-0 `txfm_partition` symbol reads its context off the rect transform's +/// own width/height; a `0` leaves one whole-block rect transform unit +/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE +/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the +/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so +/// every leaf of a split rect block is square and the existing square leaf +/// loop reconstructs it unchanged. +#[allow(clippy::too_many_arguments)] +fn read_block_tx_size_rect( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + n: &mut Neighbours, + at_mi: (usize, usize), + (bw, bh): (usize, usize), + (mi_cols, mi_rows): (usize, usize), + skip: bool, +) -> Result>> { + if skip { + // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records + // its own BLOCK size -- width above, height left -- not a transform. + txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh)); + return Ok(None); + } + // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and + // `rect_inter_residual_supported` has already excluded everything above 32. + let (tx_w, tx_h) = (bw, bh); + if !TX_SELECT_INTER.with(std::cell::Cell::get) { + // `TX_MODE_LARGEST`: no symbol at all, the whole block is one + // transform, and `set_txfm_ctxs` records exactly what + // `txfm_partition_update` would for that same unit. + txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); + RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1)); + return Ok(None); + } + let ctx = txfm_partition_ctx_rect( + n.above_txfm[at_mi.1], + n.left_txfm[at_mi.0], + bw.max(bh), + tx_w, + tx_h, + ); + let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; + TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1)); + if std::env::var_os("EC_TRACE_MODE_STEP").is_some() { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}", + at_mi.0, + at_mi.1, + u8::from(split) + ); + } + if !split { + txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); + RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1)); + return Ok(None); + } + TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1)); + let sub = tx_w.min(tx_h); + let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1)); + let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0)); + let mut leaves = Vec::new(); + for row in (0..bh / MI).step_by(sub / MI) { + for col in (0..bw / MI).step_by(sub / MI) { + read_var_tx_size( + dec, + cdfs, + n, + at_mi, + bw.max(bh), + (max_w_mi, max_h_mi), + sub, + 1, + row, + col, + &mut leaves, + ); + } + } + Ok(Some(leaves)) +} + +/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2): +/// the coefficients are read with the rect coefficient machinery +/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*` +/// types), inverted with the rect inverse transform +/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale), +/// and added onto the top-left `w x h` of the block's own square-strided +/// motion-compensated prediction buffer. Returns the *rect* coefficient grid +/// and the coded `tx_type`. +/// +/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e. +/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch. +#[allow(clippy::too_many_arguments)] +fn read_inter_plane_rect( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + set: TxbSet, + (w, h): (usize, usize), + stride: usize, + plane_idx: usize, + around: (bool, bool, i32), + tx_mode: usize, + plane: &mut PlaneBuf, + x: usize, + y: usize, + prediction: &[u16], + inherited_luma_tx_type: Option, +) -> Result<(Vec, TxType)> { + let skip_ctx = if plane_idx == 0 { + 0 + } else { + usize::from(around.0) + usize::from(around.1) + }; + let mut coding = cdfs.txb(set, tx_mode); + // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e. + // the *longer* side of this rect transform. + let default_tx_type = match inherited_luma_tx_type { + Some(t) if w.max(h) < 32 => t, + _ => TxType::DctDct, + }; + let (grid, tx_type) = read_coeffs_rect( + dec, + &mut coding, + rect_scan(w, h), + w, + h, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + )?; + let (dc_delta, ac_delta) = plane_q_delta(plane_idx); + let residual = dequant_and_inverse_typed_wh( + &grid, + w, + h, + bit_depth(), + block_q_idx(), + dc_delta, + ac_delta, + tx_type, + ); + // `reconstruct_mc_rect` reads both buffers at the square prediction + // stride, so the dense `w x h` residual is re-laid at that stride first. + let mut strided = vec![0i32; stride * stride]; + for row in 0..h { + strided[row * stride..][..w].copy_from_slice(&residual[row * w..][..w]); + } + plane.reconstruct_mc_rect(x, y, stride, w, h, prediction, &strided); + Ok((grid, tx_type)) +} + +/// A rect coefficient grid re-laid into the square `stride x stride` grid the +/// neighbour/deblock stamps downstream of the residual expect. +fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec { + let mut full = vec![0i32; stride * stride]; + for row in 0..h { + full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]); + } + full +} + /// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8 /// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single /// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in @@ -11539,16 +12030,31 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } p } else { + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit is the answer, not a formality -- libaom's + // `ec_read_partition_impl` returns `PARTITION_HORZ` (resp. + // `PARTITION_VERT`) when it reads 0, and only `PARTITION_SPLIT` + // when it reads 1. Forcing SPLIT here desynced the last + // superblock row of every frame whose height is not a multiple + // of 64 -- the ReelB head (3840x1608) diverges at + // mi_row=400 mi_col=0, the first block of that row. match (has_cols, has_rows) { (true, false) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); + if dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); + if dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - _ => {} + _ => PARTITION_SPLIT, } - PARTITION_SPLIT }; match part { PARTITION_NONE => { @@ -11605,20 +12111,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } else { match (has_cols32, has_rows32) { (true, false) => { - dec.symbol_fixed(&gather( - &cdfs.partition_w32[ctx32], - VERT_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather( - &cdfs.partition_w32[ctx32], - HORZ_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - _ => {} + _ => PARTITION_SPLIT, } - PARTITION_SPLIT }; match part32 { PARTITION_NONE => { @@ -12057,16 +12570,63 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( does not code yet", )); } - if has_cols16 { + // lane-golomb r1 (class + // `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 names + // PARTITION_HORZ (resp. VERT), only 1 is + // SPLIT (libaom `ec_read_partition_impl`). + // This path can only walk the four SPLIT + // leaves, so a 0 refuses by name instead + // of desyncing. + let edge_split = if has_cols16 { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], VERT_ALIKE, - )); + )) } else { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], HORZ_ALIKE, - )); + )) + }; + if edge_split == 0 { + // lane-oddh r1: the strip IS decodable + // -- libaom's `decode_partition` codes + // only the FIRST half of an edge + // HORZ/VERT (the second call is + // guarded by the same has_rows/ + // has_cols test that made the + // partition non-square), so one + // 16x8 (resp. 8x16) strip covers the + // whole visible band of a frame whose + // height (resp. width) is 8 mod 16 -- + // the user's 3840x1608 film. + HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1)); + EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1)); + let (mi_row0, mi_col0) = + (sr as u32 * SUB_MI, sc as u32 * SUB_MI); + let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) }; + let mode = decode_leaf_rect( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + (mi_row0 as usize, mi_col0 as usize), + bw, + bh, + None, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + neighbours.above_mode[sc] = mode; + neighbours.left_mode[sr] = mode; + continue; } let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); @@ -12616,22 +13176,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, reduced_tx_set, )?; - decode_block_rect64( - &mut dec, - &mut cdfs, - &mut neighbours, - (at.0 + 2, at.1), - 64, - 32, - &mut y, - &mut u, - &mut v, - enable_filter_intra, - allow_screen_content_tools, - base_q_idx, - tx_select, - reduced_tx_set, - )?; + // lane-golomb r1: at the frame edge only the first half of the + // strip is coded (libaom `decode_partition` guards the second + // with the same has_rows test that made this partition non-square). + if has_rows { + decode_block_rect64( + &mut dec, + &mut cdfs, + &mut neighbours, + (at.0 + 2, at.1), + 64, + 32, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } } PARTITION_VERT => { // lane-sbpart r2: mirror of PARTITION_HORZ above with @@ -12652,22 +13217,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, reduced_tx_set, )?; - decode_block_rect64( - &mut dec, - &mut cdfs, - &mut neighbours, - (at.0, at.1 + 2), - 32, - 64, - &mut y, - &mut u, - &mut v, - enable_filter_intra, - allow_screen_content_tools, - base_q_idx, - tx_select, - reduced_tx_set, - )?; + // lane-golomb r1: at the frame edge only the first half of the + // strip is coded (libaom `decode_partition` guards the second + // with the same has_cols test that made this partition non-square). + if has_cols { + decode_block_rect64( + &mut dec, + &mut cdfs, + &mut neighbours, + (at.0, at.1 + 2), + 32, + 64, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } } PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => { // lane-part32 r4: the four superblock-level AB arms, each @@ -13916,11 +14486,33 @@ fn obmc_blend( // its OWN neighbour cap (width-log2 for above, height-log2 for left) and // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was // right only for square blocks. + // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by + // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left): + // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old + // `1..=4 => 2` row was right only for blocks at least 16 px on that axis + // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where + // libaom walks one, blending an extra 8-px-tall neighbour into every + // rect leaf with two of them on its left edge (class table-narrowed-to- + // the-reachable-sizes; the square gates could never expose it). let max_nb = |n4: usize| match n4 { - 1..=4 => 2, + 0..=1 => 0, + 2 => 1, + 3..=4 => 2, 5..=8 => 3, _ => 4, }; + // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels + // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in + // both decoders on that exact stream: the neighbour lists agree entry for + // entry (position, span, mv, ref, size, filter) and all six pre-filter + // frames are byte-identical to the instrumented aomdec's. The refusal is + // gone; the counter below is what the gate's `--enable-obmc=1` arm reads. + // The only decode-path change between r3's measurement and this one is the + // lane-interbis merge (`build_motion_field`'s compound slot walk), which + // moves temporal MV candidates -- not bisected further. + if matches!((write_w, write_h), (16, 8) | (8, 16)) { + OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1)); + } let overlap_above = write_h / 2; let overlap_left = write_w / 2; // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc` @@ -14303,6 +14895,12 @@ fn build_gm_mv_table( /// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already /// refuse. #[allow(clippy::too_many_arguments)] +/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit +/// [`decode_inter_block`]'s `at` now takes. +const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) { + (t.0 * (SUB / MI), t.1 * (SUB / MI)) +} + fn decode_inter_block( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, @@ -14339,7 +14937,11 @@ fn decode_inter_block( chroma_tx: usize, scan_luma: &[u16], scan_chroma: &[u16], - size_group: usize, + // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the + // one site that read it (`y_mode`) -- a rect strip's group comes from its + // true footprint, not the caller's square `side`. Kept in the signature + // rather than editing twenty call sites. + _size_group: usize, allow_high_precision_mv: bool, force_integer_mv: bool, interp_fixed: Option, @@ -14417,13 +15019,16 @@ fn decode_inter_block( // combinations that don't implement scaled MC yet. frame_width: usize, ) -> Result<()> { - let (r, c) = at; + // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can + // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the + // few 16-px-granular uses below. + let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI)); // lane-inter8 r2: the inter side bands are mi-granular; this block's own // above/left neighbour is the mi cell at its top-left corner (libaom // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads // exactly what it read before. - let (rmi, cmi) = (r * (SUB / MI), c * (SUB / MI)); - let (px, py) = (c * SUB, r * SUB); + let (rmi, cmi) = at; + let (px, py) = (at.1 * MI, at.0 * MI); let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2); @@ -14431,7 +15036,7 @@ fn decode_inter_block( if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}", - r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 + rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } let skip_mode_ctx = @@ -14447,7 +15052,7 @@ fn decode_inter_block( } // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before // `skip_mode`/`skip`, `inter_segment_id(0)` after them. - let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (seg_mi_r, seg_mi_c) = (rmi, cmi); let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4); inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; @@ -14464,21 +15069,27 @@ fn decode_inter_block( let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false); - maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip); - maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); - maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip); + maybe_read_cdef_idx(dec, rmi, cmi, skip); + // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip + // is NOT the whole superblock, so its `skip` never suppresses the read. + let whole_sb = side == 64 && write_w == 64 && write_h == 64; + maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip); + maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip); // lane-warp r5: see `reject_residual` -- a square-block decode of a // HORZ_B strip is symbol-exact only for `skip` (no residual, no // motion_mode/warp symbol), so gate here before any further read. - if reject_residual && !skip { + if reject_residual && !skip && !rect_inter_residual_supported(write_w, write_h) { + if std::env::var_os("EC_AV1_RECT_DUMP").is_some() { + eprintln!("EC_RECT_REFUSE mi_row={rmi} mi_col={cmi} w={write_w} h={write_h} side={side}"); + } return Err(unsupported( "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", )); } let (has_above, has_left) = ( - r > neighbours.tile_row0_mi / (SUB / MI), - c > neighbours.tile_col0_mi / (SUB / MI), + rmi > neighbours.tile_row0_mi, + cmi > neighbours.tile_col0_mi, ); let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); @@ -14486,15 +15097,15 @@ fn decode_inter_block( if std::env::var_os("EC_TRACE_MODE").is_some() { eprintln!( "EC_MODE mi_row={} mi_col={} rng={}", - r * SUB_MI as usize, - c * SUB_MI as usize, + rmi, + cmi, dec.debug_state().0 ); } if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}", - r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 + rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } @@ -14514,7 +15125,7 @@ fn decode_inter_block( // than one luma transform -- read back by the residual loop, the // coefficient-context write-back and the loop-filter grid fill below. let mut vartx_leaves: Option> = None; - let at_mi = (r * (SUB / MI), c * (SUB / MI)); + let at_mi = at; if is_inter { let above_nbr = has_above.then(|| NeighbourRef { is_inter: above_inter, @@ -14559,7 +15170,7 @@ fn decode_inter_block( neighbours.left_ref[rmi], ) }; - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: true footprint, mirroring the single-ref path below. let bw4 = write_w / 4; let bh4 = write_h / 4; @@ -15293,17 +15904,32 @@ fn decode_inter_block( mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v); } - vartx_leaves = read_block_tx_size( - dec, - cdfs, - neighbours, - at_mi, - side, - (mi_cols as usize, mi_rows as usize), - true, - skip, - )? - .1; + // lane-inter4 r2: a rectangular strip's transform tree starts from + // its own rect `max_txsize_rect_lookup` entry, not a square one. + let rect_tu = (write_w, write_h) != (side, side); + vartx_leaves = if rect_tu { + read_block_tx_size_rect( + dec, + cdfs, + neighbours, + at_mi, + (write_w, write_h), + (mi_cols as usize, mi_rows as usize), + skip, + )? + } else { + read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1 + }; if skip { y.reconstruct_mc_rect( px, @@ -15336,7 +15962,14 @@ fn decode_inter_block( u_grid = vec![0i32; chroma_side * chroma_side]; v_grid = vec![0i32; chroma_side * chroma_side]; } else { - let around = neighbours.around(at, side); + // lane-inter4 r2: a rect strip's coefficient context spans its + // OWN width above and height left -- reading `side` cells both + // ways indexes past the tile's last mi row for a bottom strip. + let around = if rect_tu { + neighbours.around_mi_rect(at_mi, write_w, write_h) + } else { + neighbours.around_mi(at, side) + }; let luma_tx_type; if let Some(leaves) = vartx_leaves.clone() { // spec 5.11.17's transform tree, leaf by leaf in the order @@ -15383,6 +16016,26 @@ fn decode_inter_block( // inherits the *first* (top-left) luma unit's coded type. luma_tx_type = first_tx_type; luma_grid = vec![0i32; side * side]; + } else if rect_tu { + // The whole-block rectangular transform unit + // (`txfm_partition` said 0 at depth 0). + let (grid, tx_type) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_luma_set(write_w, write_h), + (write_w, write_h), + side, + 0, + around[0], + mode_for_tx, + y, + px, + py, + &pred_y, + None, + )?; + luma_tx_type = tx_type; + luma_grid = embed_rect_grid(&grid, write_w, write_h, side); } else { (luma_grid, luma_tx_type) = read_inter_plane( dec, @@ -15402,6 +16055,55 @@ fn decode_inter_block( None, )?; } + if rect_tu { + // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a + // 2:1 strip is the strip's own rect chroma size (16x8 / + // 8x16), one unit for the whole block, and it codes no + // `tx_type` symbol -- it inherits the luma unit's. + let (uw, uh) = (write_chroma_w, write_chroma_h); + u_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (uw, uh), + chroma_side, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + &pred_u, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + v_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (uw, uh), + chroma_side, + 2, + around[2], + mode_for_tx, + v, + cpx, + cpy, + &pred_v, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + } else { u_grid = read_inter_plane( dec, cdfs, @@ -15438,6 +16140,7 @@ fn decode_inter_block( None, )? .0; + } } } else { let ref_frame = @@ -15451,7 +16154,7 @@ fn decode_inter_block( ); ref_frame_for_lf = ref_frame; if std::env::var_os("EC_AV1_TELL").is_some() { - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); eprintln!( "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}", dec.debug_bitpos(), dec.debug_state().0 @@ -15479,7 +16182,7 @@ fn decode_inter_block( } }; - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: the mv stack must be queried with the block's // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from // xd->width/xd->height, not a square guess) -- `write_w`/ @@ -15526,6 +16229,10 @@ fn decode_inter_block( ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; + // lane-interbis r1: which single-ref mode this block resolved to, + // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for + // the `EC_MODE_VAL` value ladder below. + let mut dbg_mode = 16u32; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the @@ -15558,9 +16265,11 @@ fn decode_inter_block( let mv = if !not_zero { // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already // computed at this block's own position in `gm_table`. + dbg_mode = 15; gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + dbg_mode = if nearest { 13 } else { 14 }; if nearest { stack.nearest_mv } else { @@ -15582,6 +16291,21 @@ fn decode_inter_block( }; (mv, false) }; + if std::env::var_os("EC_TRACE_MODE").is_some() { + for (i, e) in stack.entries.iter().enumerate() { + eprintln!( + "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", + e.mv.0, e.mv.1, e.weight + ); + } + eprintln!( + "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}", + mv.0, + mv.1, + stack.entries.len(), + dec.debug_state().0 + ); + } // lane-gm r2: the two libaom predicates single-ref GLOBALMV // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating @@ -15613,8 +16337,22 @@ fn decode_inter_block( // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3. let mut interintra_mode: Option = None; let mut wedge_mask: Option<(&'static [u8], usize)> = None; - if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) { - let bsize_group = if side == 16 { 2 } else { 3 }; + // lane-inter4 r1: `is_interintra_allowed_bsize` is + // `BLOCK_8X8..=BLOCK_32X32` in libaom's enum ORDER, which excludes + // every 1:4 shape (BLOCK_8X32 = 18, BLOCK_32X8 = 19) even though + // both dimensions are in range -- reading this symbol on a 1:4 + // strip is a symbol the reference never wrote. + let interintra_shape = + write_w.max(write_h) <= 32 && write_w.max(write_h) / write_w.min(write_h) <= 2; + if enable_interintra_compound + && !skip_mode + && (side == 16 || side == 32) + && interintra_shape + { + // lane-inter4 r3: `size_group_lookup` reads the block's + // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip + // group 2, not their square `side`'s 2/3. + let bsize_group = size_group_wh(write_w, write_h); let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1; if interintra { // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode, @@ -15709,12 +16447,29 @@ fn decode_inter_block( // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4, // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's // strip motion_mode read diverged on the square row. - let bsize_idx = if write_w == write_h { - (write_w.trailing_zeros() - 3) as usize - } else if write_w == 16 { - 4 - } else { - 5 + // lane-inter4 r1: every rect shape this decoder can now + // reach reads its OWN libaom bsize row (the packed order is + // documented on `cdf::MOTION_MODE`); a wrong row is a wrong + // interval narrowing, not a wrong value (class + // wrong-alphabet-same-value). + let bsize_idx = match (write_w, write_h) { + (w, h) if w == h => (w.trailing_zeros() - 3) as usize, + (16, 32) => 4, + (32, 16) => 5, + (32, 64) => 6, + (64, 32) => 7, + (8, 32) => 8, + (32, 8) => 9, + (16, 64) => 10, + (64, 16) => 11, + // lane-inter4 r3: the 16x16-level rect inter leaves. + (8, 16) => 12, + (16, 8) => 13, + _ => { + return Err(unsupported( + "a motion_mode symbol for a block shape with no CDF row here", + )); + } }; // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf` // instead of the 2-symbol `obmc_cdf` exactly when @@ -16127,17 +16882,32 @@ fn decode_inter_block( interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v); } - vartx_leaves = read_block_tx_size( - dec, - cdfs, - neighbours, - at_mi, - side, - (mi_cols as usize, mi_rows as usize), - true, - skip, - )? - .1; + // lane-inter4 r2: a rectangular strip's transform tree starts from + // its own rect `max_txsize_rect_lookup` entry, not a square one. + let rect_tu = (write_w, write_h) != (side, side); + vartx_leaves = if rect_tu { + read_block_tx_size_rect( + dec, + cdfs, + neighbours, + at_mi, + (write_w, write_h), + (mi_cols as usize, mi_rows as usize), + skip, + )? + } else { + read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1 + }; if skip { y.reconstruct_mc_rect( px, @@ -16170,7 +16940,14 @@ fn decode_inter_block( u_grid = vec![0i32; chroma_side * chroma_side]; v_grid = vec![0i32; chroma_side * chroma_side]; } else { - let around = neighbours.around(at, side); + // lane-inter4 r2: a rect strip's coefficient context spans its + // OWN width above and height left -- reading `side` cells both + // ways indexes past the tile's last mi row for a bottom strip. + let around = if rect_tu { + neighbours.around_mi_rect(at_mi, write_w, write_h) + } else { + neighbours.around_mi(at, side) + }; let luma_tx_type; if let Some(leaves) = vartx_leaves.clone() { // spec 5.11.17's transform tree, leaf by leaf in the order @@ -16217,6 +16994,26 @@ fn decode_inter_block( // inherits the *first* (top-left) luma unit's coded type. luma_tx_type = first_tx_type; luma_grid = vec![0i32; side * side]; + } else if rect_tu { + // The whole-block rectangular transform unit + // (`txfm_partition` said 0 at depth 0). + let (grid, tx_type) = read_inter_plane_rect( + dec, + cdfs, + rect_inter_luma_set(write_w, write_h), + (write_w, write_h), + side, + 0, + around[0], + mode_for_tx, + y, + px, + py, + &pred_y, + None, + )?; + luma_tx_type = tx_type; + luma_grid = embed_rect_grid(&grid, write_w, write_h, side); } else { (luma_grid, luma_tx_type) = read_inter_plane( dec, @@ -16236,6 +17033,55 @@ fn decode_inter_block( None, )?; } + if rect_tu { + // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a + // 2:1 strip is the strip's own rect chroma size (16x8 / + // 8x16), one unit for the whole block, and it codes no + // `tx_type` symbol -- it inherits the luma unit's. + let (uw, uh) = (write_chroma_w, write_chroma_h); + u_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (uw, uh), + chroma_side, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + &pred_u, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + v_grid = embed_rect_grid( + &read_inter_plane_rect( + dec, + cdfs, + rect_inter_chroma_set(write_chroma_w, write_chroma_h), + (uw, uh), + chroma_side, + 2, + around[2], + mode_for_tx, + v, + cpx, + cpy, + &pred_v, + Some(luma_tx_type), + )? + .0, + uw, + uh, + chroma_side, + ); + } else { u_grid = read_inter_plane( dec, cdfs, @@ -16272,6 +17118,7 @@ fn decode_inter_block( None, )? .0; + } } } } else { @@ -16287,20 +17134,35 @@ fn decode_inter_block( this decoder does not code yet", )); } - let mode = dec.symbol(&mut cdfs.y_mode[size_group]); + let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]); if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", )); } - if (V_PRED..=D67_PRED).contains(&mode) { - let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]); - if angle != ANGLE_DELTA_ZERO { - return Err(unsupported( - "a nonzero angle delta (this encoder never writes one)", - )); - } - } + // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`, + // inside `read_intra_block_mode_info`) -- an intra block in an inter + // frame reads `angle_delta_y` off the same + // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and + // the delta feeds the directional predictor (and the edge + // filter/upsample decision derived from the delta'd angle) unchanged. + // The symbol was read and then refused before this round even though + // aomenc enables `--enable-angle-delta` by default. + let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { + read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) + } else { + 0 + }; + if angle_delta_y != 0 { + INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1)); + } + // The delta'd angle decides whether the intra edge filter runs at + // all, so this block needs the same luma edge-filter-type neighbour + // check a key-frame block does (`get_intra_edge_filter_type`, spec + // 7.11.2) -- this arm passed a hardcoded `false` while every + // directional intra-in-inter block was refused above. + let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); + let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); if (9..=12).contains(&uv_mode) { SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); @@ -16324,6 +17186,7 @@ fn decode_inter_block( }; if angle_delta_uv != 0 { UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1)); + INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.set(c.get() + 1)); } uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED @@ -16377,7 +17240,7 @@ fn decode_inter_block( block_filter = [3, 3]; ref_frame_for_lf = 0; globalmv_for_lf = false; - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let (mi_row, mi_col) = (rmi, cmi); for dr in 0..side / 4 { for dc in 0..side / 4 { grid.set( @@ -16435,12 +17298,12 @@ fn decode_inter_block( tu_py, tx_px, mode, - 0, + angle_delta_y, tu_reach, &vec![0i32; tx_px * tx_px], None, filter_intra, - false, + smooth_neighbor, ); vec![0i32; tx_px * tx_px] } else { @@ -16457,7 +17320,7 @@ fn decode_inter_block( neighbours.around_mi(tu_mi, tx_px)[0], mode, mode, - 0, + angle_delta_y, tu_reach, y, tu_px, @@ -16468,7 +17331,7 @@ fn decode_inter_block( None, filter_intra, Some(tu_skip_ctx), - false, + smooth_neighbor, )? }; neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid); @@ -16481,12 +17344,12 @@ fn decode_inter_block( py, side, mode, - 0, + angle_delta_y, reach, &vec![0i32; side * side], None, filter_intra, - false, + smooth_neighbor, ); } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); @@ -16518,7 +17381,7 @@ fn decode_inter_block( u_grid = vec![0i32; chroma_side * chroma_side]; v_grid = vec![0i32; chroma_side * chroma_side]; } else { - let around = neighbours.around(at, side); + let around = neighbours.around_mi(at, side); luma_grid = if split_luma { // Already coded and reconstructed unit by unit above; the // block-level grid is only the neighbour write-back's input, @@ -16534,7 +17397,7 @@ fn decode_inter_block( around[0], mode, mode, - 0, + angle_delta_y, reach, y, px, @@ -16545,7 +17408,7 @@ fn decode_inter_block( None, filter_intra, None, - false, + smooth_neighbor, )? }; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); @@ -16604,7 +17467,7 @@ fn decode_inter_block( if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=block_end tell={} range={}", - r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 + rmi, cmi, dec.debug_bitpos(), dec.debug_state().0 ); } if vartx_leaves.is_some() { @@ -16612,9 +17475,9 @@ fn decode_inter_block( // ([`Neighbours::record_mi_luma`] above); this writes everything else // [`Neighbours::record_rect`] would (a var-tx block is always square, // so `write_w == write_h == side`). - neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]); + neighbours.record_split_luma_rect_mi(at, side, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]); } else { - neighbours.record_rect( + neighbours.record_rect_mi( at, write_w, write_h, @@ -16623,10 +17486,10 @@ fn decode_inter_block( &[luma_grid, u_grid, v_grid], ); } - neighbours.record_inter_rect( + neighbours.record_inter_rect_mi( at, - write_w, - write_h, + write_w / MI, + write_h / MI, skip, is_inter, ref_frame_for_lf, @@ -16634,16 +17497,16 @@ fn decode_inter_block( skip_mode, ); if let Some((ref1, group_idx, idx)) = compound_ctx { - neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx); + neighbours.record_compound_ctx_rect_mi(at, write_w / MI, write_h / MI, ref1, group_idx, idx); } neighbours.fill_skip_grid_rect( - (r * (SUB / MI), c * (SUB / MI)), + (rmi, cmi), write_w / MI, write_h / MI, skip, ); neighbours.fill_lf_grid_rect( - (r * (SUB / MI), c * (SUB / MI)), + (rmi, cmi), write_w / MI, write_h / MI, // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the @@ -17934,13 +18797,33 @@ fn decode_inter_block8( "an intra mode this decoder does not code (round 2)", )); } - if (V_PRED..=D67_PRED).contains(&mode) { - let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]); - if angle != ANGLE_DELTA_ZERO { - return Err(unsupported( - "a nonzero angle delta (this encoder never writes one)", - )); - } + // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`, + // inside `read_intra_block_mode_info`) -- an intra block in an inter + // frame reads `angle_delta_y` off the same + // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and + // the delta feeds the directional predictor (and the edge + // filter/upsample decision derived from the delta'd angle) unchanged. + // The symbol was read and then refused before this round even though + // aomenc enables `--enable-angle-delta` by default. + let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { + read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) + } else { + 0 + }; + if angle_delta_y != 0 { + INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1)); + // lane-angleinter r1: the >=16x16 arm's lift is gated by a real + // aomenc stream; this leaf's is NOT -- 80 attempts across two + // sizes and five quantisers never produced an 8x8 intra leaf with + // a nonzero delta (the leaf's own sibling refusals -- non-DC + // chroma, the TX_4X4 split, sub-16 rect inter leaves -- fire + // first). The prediction below would handle it; refusing keeps + // the rule that no lift ships ungated. Note the claim is about + // THIS DECODER's gate coverage, not about what an encoder writes. + return Err(unsupported( + "a nonzero angle delta on an 8x8 intra leaf in an inter frame (no gate reaches \ + this leaf with one; the >=16x16 arm decodes deltas)", + )); } let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); if uv_mode != DC_PRED { @@ -18035,7 +18918,7 @@ fn decode_inter_block8( py, SIDE, mode, - 0, + angle_delta_y, reach, &vec![0i32; SIDE * SIDE], None, @@ -18080,7 +18963,7 @@ fn decode_inter_block8( around[0], mode, mode, - 0, + angle_delta_y, reach, y, px, @@ -18637,6 +19520,64 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } CDEF_TRANSMITTED.with(|c| c.set(false)); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); + // lane-inter4 r1: every rect inter piece below is the same + // `decode_inter_block` call with only position / true footprint / + // transform-set differing; the macro keeps the new arms readable + // instead of six more 60-line copies of the argument list. + macro_rules! inter_piece { + ($at_mi:expr, $side:expr, $li:expr, $lt:expr, $ch:expr, $ltx:expr, + $ctx:expr, $sl:expr, $sc:expr, $sg:expr, $ww:expr, $wh:expr) => { + decode_inter_block( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + $at_mi, + $side, + mi_cols, + mi_rows, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + &ref_slots, + &sign_bias_table, + &global_motion, + base_q_idx, + $li, + $lt, + $ch, + $ltx, + $ctx, + $sl, + $sc, + $sg, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + tpl_frame.as_ref(), + reference_select, + enable_masked_compound, + enable_interintra_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, + switchable_motion_mode, + allow_warped_motion, + true, + $ww, + $wh, + allow_screen_content_tools, + frame_width as usize, + )? + }; + } let sb_ctx = neighbours.partition_ctx(sb_at, SB); let (has_cols, has_rows) = ( sb_c * SB_MI + SB_MI / 2 < mi_cols, @@ -18662,12 +19603,24 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( p } (true, false) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)); - PARTITION_SPLIT + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)); - PARTITION_SPLIT + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } (false, false) => PARTITION_SPLIT, }; @@ -18687,7 +19640,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - sb_at, + sub16_to_mi(sb_at), SB, mi_cols, mi_rows, @@ -18733,10 +19686,73 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )?; continue; } + if matches!( + part64, + PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4 + ) { + // lane-inter4 r1: the superblock-level rect + 1:4 pairs as + // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 / + // 16x64 ones. Each piece keeps `side = SB` for every + // syntax/CDF/prediction-buffer decision (the square-context + // corner-cut PARTITION_HORZ already ships at the 32 level) + // but names its own true footprint through `write_w`/ + // `write_h`, which is what `motion_mode`'s bsize row, the + // mv-stack's bw4/bh4, the delta-q `bSize == sbSize` test and + // every neighbour stamp read. `reject_residual = true`: a + // non-skip strip refuses by name rather than over-read a + // square residual (rectangular inter residual coding is not + // ported -- see lanes/inter4-r1.report.md). + let horz = matches!(part64, PARTITION_HORZ | PARTITION_HORZ_4); + let four = matches!(part64, PARTITION_HORZ_4 | PARTITION_VERT_4); + let base_mi = ( + sb_r as usize * SB_MI as usize, + sb_c as usize * SB_MI as usize, + ); + let (n_pieces, step_mi) = if four { (4usize, 4usize) } else { (2usize, 8usize) }; + let (bw, bh) = match (horz, four) { + (true, false) => (64usize, 32usize), + (false, false) => (32, 64), + (true, true) => (64, 16), + (false, true) => (16, 64), + }; + for i in 0..n_pieces { + let at_mi = if horz { + (base_mi.0 + i * step_mi, base_mi.1) + } else { + (base_mi.0, base_mi.1 + i * step_mi) + }; + // libaom `decode_partition`'s own `i > 0` frame-edge break. + if i > 0 && (at_mi.0 >= mi_rows as usize || at_mi.1 >= mi_cols as usize) { + break; + } + inter_piece!( + at_mi, + SB, + TxbSet::Luma64, + TxbSet::Luma64, + TxbSet::Chroma32, + TX32, + TX32, + &scan32, + &scan32, + 3, + bw, + bh + ); + match (horz, four) { + (true, false) => INTER_SB_HORZ_HITS.with(|c| c.set(c.get() + 1)), + (false, false) => INTER_SB_VERT_HITS.with(|c| c.set(c.get() + 1)), + (true, true) => INTER_SB_HORZ4_HITS.with(|c| c.set(c.get() + 1)), + (false, true) => INTER_SB_VERT4_HITS.with(|c| c.set(c.get() + 1)), + } + } + continue; + } if part64 != PARTITION_SPLIT { return Err(unsupported( - "an inter SB-level partition type other than NONE or SPLIT (this decoder's \ - inter tile path recurses a superblock only as SPLIT)", + "an inter SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B; this \ + decoder's inter tile path codes a superblock as NONE, SPLIT, HORZ, \ + VERT, HORZ_4 or VERT_4)", )); } @@ -18772,14 +19788,27 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } else { match (has_cols32, has_rows32) { (true, false) => { - dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - _ => {} + _ => PARTITION_SPLIT, } - PARTITION_SPLIT }; match part32 { PARTITION_NONE => { @@ -18788,7 +19817,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -18871,17 +19900,24 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( p } else { if has_cols16 { - dec.symbol_fixed(&gather( - &cdfs.partition_w16[ctx16], - VERT_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w16[ctx16], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } else { - dec.symbol_fixed(&gather( - &cdfs.partition_w16[ctx16], - HORZ_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - PARTITION_SPLIT }; if part16 == PARTITION_NONE { decode_inter_block( @@ -18889,7 +19925,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at16, + sub16_to_mi(at16), SUB, mi_cols, mi_rows, @@ -18937,9 +19973,96 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( allow_screen_content_tools, frame_width as usize, )?; + } else if part16 == PARTITION_HORZ || part16 == PARTITION_VERT { + // lane-inter4 r3: the 16x16-level rect inter + // leaves -- two true 16x8 (HORZ) or 8x16 + // (VERT) inter blocks. Same shape as the + // 32-level HORZ/VERT arm above: `side = SUB` + // keeps every CDF/prediction-buffer decision + // square, `write_w`/`write_h` carry the true + // footprint into the mv stack, the motion-mode + // row, the neighbour stamps and the rectangular + // residual path (`rect_inter_residual_supported` + // covers 16x8/8x16 since this round). + let horz = part16 == PARTITION_HORZ; + if horz { + INTER_LEAF16_HORZ_HITS.with(|c| c.set(c.get() + 1)); + } else { + INTER_LEAF16_VERT_HITS.with(|c| c.set(c.get() + 1)); + } + let base_mi = sub16_to_mi(at16); + let (ww, wh) = if horz { (16, 8) } else { (8, 16) }; + for piece in 0..2 { + let piece_mi = if horz { + (base_mi.0 + piece * 2, base_mi.1) + } else { + (base_mi.0, base_mi.1 + piece * 2) + }; + // libaom `decode_partition`'s own second- + // half frame-edge break. + if piece > 0 + && (piece_mi.0 >= mi_rows as usize + || piece_mi.1 >= mi_cols as usize) + { + break; + } + decode_inter_block( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + piece_mi, + SUB, + mi_cols, + mi_rows, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + &ref_slots, + &sign_bias_table, + &global_motion, + base_q_idx, + TxbSet::Luma16, + if reduced_tx_set { + TxbSet::Luma16Inter + } else { + TxbSet::Luma16InterSet1 + }, + TxbSet::Chroma8, + TX16, + TX8, + &scan16, + &scan8, + 1, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + tpl_frame.as_ref(), + reference_select, + enable_masked_compound, + enable_interintra_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, + switchable_motion_mode, + allow_warped_motion, + true, + ww, + wh, + allow_screen_content_tools, + frame_width as usize, + )?; + } } else if part16 != PARTITION_SPLIT { return Err(unsupported( - "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)", + "an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT or SPLIT)", )); } else { if has_cols16 && has_rows16 { @@ -19095,7 +20218,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at32, + sub16_to_mi(at32), BLOCK, mi_cols, mi_rows, @@ -19148,7 +20271,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), SUB, mi_cols, mi_rows, @@ -19202,7 +20325,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19266,7 +20389,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -19315,7 +20438,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), BLOCK, mi_cols, mi_rows, @@ -19369,7 +20492,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -19418,7 +20541,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), BLOCK, mi_cols, mi_rows, @@ -19473,7 +20596,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), SUB, mi_cols, mi_rows, @@ -19526,7 +20649,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19579,7 +20702,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), BLOCK, mi_cols, mi_rows, @@ -19634,7 +20757,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), SUB, mi_cols, mi_rows, @@ -19687,7 +20810,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2)), SUB, mi_cols, mi_rows, @@ -19740,7 +20863,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), BLOCK, mi_cols, mi_rows, @@ -19796,7 +20919,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - at, + sub16_to_mi(at), BLOCK, mi_cols, mi_rows, @@ -19845,7 +20968,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19898,7 +21021,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut cdfs, &mut neighbours, &mut grid, - (r32 as usize * 2 + 1, c32 as usize * 2 + 1), + sub16_to_mi((r32 as usize * 2 + 1, c32 as usize * 2 + 1)), SUB, mi_cols, mi_rows, @@ -19947,6 +21070,49 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_width as usize, )?; } + PARTITION_HORZ_4 | PARTITION_VERT_4 => { + // lane-inter4 r1: four 32x8 / 8x32 inter strips, + // `quarter_step` = 2 mi -- the arm ReelC's first inter + // frame stops at (`value=9` = PARTITION_VERT_4). + // `at` is in 16-px cells and cannot name an 8-px + // offset, which is why `decode_inter_block` takes mi + // coordinates now. + let horz = part32 == PARTITION_HORZ_4; + let base_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); + let (bw, bh) = if horz { (32usize, 8usize) } else { (8, 32) }; + for i in 0..4 { + let strip_mi = if horz { + (base_mi.0 + i * 2, base_mi.1) + } else { + (base_mi.0, base_mi.1 + i * 2) + }; + if i > 0 + && (strip_mi.0 >= mi_rows as usize + || strip_mi.1 >= mi_cols as usize) + { + break; + } + inter_piece!( + strip_mi, + BLOCK, + TxbSet::Luma32, + TxbSet::Luma32Inter, + TxbSet::Chroma16, + TX32, + TX16, + &scan32, + &scan16, + 3, + bw, + bh + ); + if horz { + RECT4_32_HORZ_INTER_HITS.with(|c| c.set(c.get() + 1)); + } else { + RECT4_32_VERT_INTER_HITS.with(|c| c.set(c.get() + 1)); + } + } + } _ => { return Err(unsupported(format!( "an INTER 32x32 partition type this decoder does not code (value={part32})" @@ -20002,6 +21168,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mi_cols as usize, mi_rows as usize, order_hint, + order_hint_bits, ref_order_hints, ); @@ -20577,8 +21744,13 @@ mod tests { ) .unwrap_err(); let msg = err.to_string(); + // lane-inter4 r1: this fixture's SB value is PARTITION_HORZ, now + // DECODED rather than refused outright; its first 64x32 strip is + // non-skip, so the named refusal is the rectangular-inter-residual + // one. Either string proves what the pin was written for: a non-SPLIT + // superblock never silently decodes as SPLIT. assert!( - msg.contains("SPLIT"), + msg.contains("SPLIT") || msg.contains("rectangular residual coding"), "expected the named inter-SB-partition refusal, got: {msg}" ); } @@ -21061,7 +22233,7 @@ mod tests { &mut cdfs, &mut neighbours, &mut grid, - (r, c), + sub16_to_mi((r, c)), side, mi_cols, mi_rows, diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 925d5718..cb8e4e4d 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -148,10 +148,6 @@ const ALIASES: &[(&str, &str)] = &[("superres-mode", "enable-superres")]; /// depth retires the entry, and this test fails until it is deleted. #[cfg(test)] const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[ - ( - "enable-angle-delta", - "off in 36 gates, on in none: the directional-intra gates pin it off to isolate the base modes", - ), ( "enable-cfl-intra", "off in 41 gates, on in none: chroma-from-luma prediction is unimplemented", @@ -180,10 +176,6 @@ const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[ "enable-rect-tx", "never spelled; rect transforms reach the decoder only through partition shape, never through a gate that names the tool", ), - ( - "enable-ref-frame-mvs", - "off in 27 gates, on in none: temporal MV projection is unimplemented", - ), ( "enable-tx64", "never spelled; TX_64X64 appears only where aomenc's default picks it, which is unknown per stream", @@ -214,10 +206,6 @@ const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ // lane-cwarp's 10-bit comp // gate passes `=1` for both. `enable-1to4-partitions` left it on 2026-09-02: // lane-tx64x16 r4's 32-level 1:4 gate has a 10-bit arm that asserts both // orientations and coded strips inside pixel-exact attempts. - ( - "enable-angle-delta", - "hole at both depths, see the 8-bit list", - ), ( "enable-cfl-intra", "hole at both depths, see the 8-bit list", @@ -234,10 +222,6 @@ const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ // lane-cwarp's 10-bit comp // 1D tx class). ("enable-intrabc", "hole at both depths, see the 8-bit list"), ("enable-rect-tx", "hole at both depths, see the 8-bit list"), - ( - "enable-ref-frame-mvs", - "hole at both depths, see the 8-bit list", - ), ("enable-tx64", "hole at both depths, see the 8-bit list"), ]; diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index bac2f6eb..330a5e97 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -31,13 +31,23 @@ pub struct MotionField { cells: Vec>, pub order_hint: u32, pub ref_order_hints: [u32; 7], + /// libaom `motion_field_projection`'s own first test: a start frame whose + /// `frame_type` is `KEY_FRAME`/`INTRA_ONLY_FRAME` is never projected at + /// all (`return 0`), so it also never spends a `ref_stamp` slot. + pub is_intra: bool, } impl MotionField { /// A field sized for an `mi_cols` by `mi_rows` frame, all cells /// initially unset (spec 7.9's own reset to `-1`/invalid before any /// block writes into it). - pub fn new(mi_cols: usize, mi_rows: usize, order_hint: u32, ref_order_hints: [u32; 7]) -> Self { + pub fn new( + mi_cols: usize, + mi_rows: usize, + order_hint: u32, + ref_order_hints: [u32; 7], + is_intra: bool, + ) -> Self { let cols = mi_cols.div_ceil(2); let rows = mi_rows.div_ceil(2); Self { @@ -46,6 +56,7 @@ impl MotionField { cells: vec![None; cols * rows], order_hint, ref_order_hints, + is_intra, } } @@ -53,10 +64,14 @@ impl MotionField { /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution /// write. - pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: SavedMv) { + /// `saved == None` is `av1_copy_frame_mvs`'s own leading clear + /// (`mv->ref_frame = NONE_FRAME; mv->mv.as_int = 0;`), which every block + /// of an inter frame performs -- an intra (or nothing-to-store) block + /// sharing an 8x8 cell with an earlier inter one wipes that cell. + pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: Option) { let (r, c) = (mi_row / 2, mi_col / 2); if r < self.rows && c < self.cols { - self.cells[r * self.cols + c] = Some(saved); + self.cells[r * self.cols + c] = saved; } } @@ -217,6 +232,14 @@ fn motion_field_projection( dir: u8, tpl_cells: &mut [Option<((i32, i32), i32)>], ) -> bool { + // libaom's own first two `return 0`s, in order: a key/intra-only start + // frame is never projected (and so never spends a `ref_stamp` slot -- + // returning `true` here made a forward key frame, `--enable-fwd-kf=1`, + // consume the slot ALTREF/LAST2 should have had), then the frame-size + // test. + if start.is_intra { + return false; + } let mvs_rows = mi_rows.div_ceil(2); let mvs_cols = mi_cols.div_ceil(2); if start.rows != mvs_rows || start.cols != mvs_cols { @@ -264,6 +287,24 @@ fn motion_field_projection( true } +thread_local! { + /// Frames whose `av1_setup_motion_field` saw at least one forward + /// references holding a key/intra-only frame -- the `ref_stamp` path + /// [`motion_field_projection`]'s intra early return governs. + static REFSTAMP_INTRA_FRAMES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The subset of those frames with TWO or more such references. + static REFSTAMP_INTRA2_FRAMES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Reads the counter above (gate +/// `a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact`). +pub fn refstamp_intra_frames() -> (usize, usize) { + ( + REFSTAMP_INTRA_FRAMES.with(std::cell::Cell::get), + REFSTAMP_INTRA2_FRAMES.with(std::cell::Cell::get), + ) +} + /// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to /// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order /// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when @@ -287,6 +328,11 @@ pub fn setup_motion_field( let cols = mi_cols.div_ceil(2); let rows = mi_rows.div_ceil(2); let mut cells = vec![None; cols * rows]; + // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;` + // leaves every `tpl_mvs` cell INVALID. + if order_hint_bits == 0 { + return TplField { cols, rows, cells }; + } let slot_of = |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref(); @@ -294,6 +340,27 @@ pub fn setup_motion_field( let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1 + // Gate counter (lane-refstamp): frames whose forward references include at + // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the + // early return above fixes. + let intra_forward_refs = [ + BWDREF_FRAME, + crate::mvstack::ALTREF2_FRAME, + ALTREF_FRAME, + ] + .into_iter() + .filter(|&rf| { + get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0 + && slot_of(rf).is_some_and(|m| m.is_intra) + }) + .count(); + if intra_forward_refs >= 1 { + REFSTAMP_INTRA_FRAMES.with(|c| c.set(c.get() + 1)); + } + if intra_forward_refs >= 2 { + REFSTAMP_INTRA2_FRAMES.with(|c| c.set(c.get() + 1)); + } + if let Some(last) = slot_of(LAST_FRAME) { let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize]; let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME); @@ -420,7 +487,17 @@ pub fn add_tpl_ref_mv( if row8 < 0 || col8 < 0 { return None; } - let (fwd_mv, ref_frame_offset) = tpl.get(row8 as usize / 2, col8 as usize / 2)?; + let probe = tpl.get(row8 as usize / 2, col8 as usize / 2); + if std::env::var_os("EC_TRACE_TPL").is_some() { + match probe { + None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"), + Some((m, rfo)) => eprintln!( + "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}", + m.0, m.1 + ), + } + } + let (fwd_mv, ref_frame_offset) = probe?; let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset); let mv = lower_mv_precision(projected, allow_high_precision_mv); Some(TplCandidate { mv }) @@ -454,14 +531,14 @@ mod tests { // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV // against its own LAST_FRAME (order_hint 1). The current frame // (order_hint 4) names that same slot as *its* LAST_FRAME. - let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0]); + let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0], false); mf.set( 0, 0, - SavedMv { + Some(SavedMv { mv: (-64, 0), ref_frame: LAST_FRAME, - }, + }), ); let slots: [Option; 8] = std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None }); diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 32c5c199..3f33ea57 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -26,11 +26,11 @@ const CAPABILITY_CLAIMS: &[&str] = &[ "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)", "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)", - "a nonzero angle delta (this encoder never writes one)", ]; #[cfg(test)] const REFUSALS: &[&str] = &[ + "a nonzero angle delta on an 8x8 intra leaf in an inter frame (no gate reaches this leaf with one; the >=16x16 arm decodes deltas)", "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)", @@ -67,12 +67,13 @@ const REFUSALS: &[&str] = &[ // the 8x8 leaf's TX_4X4 2x2 grid is still refused here. "an 8x8 intra leaf in an inter frame whose tx_depth splits it into 4x4 transform units", "an inter frame with no key frame before it", - "an inter SB-level partition type other than NONE or SPLIT (this decoder's inter tile path recurses a superblock only as SPLIT)", - "an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet)", + "an inter SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B; this decoder's inter tile path codes a superblock as NONE, SPLIT, HORZ, VERT, HORZ_4 or VERT_4)", + "an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT or SPLIT)", "an intra mode this decoder does not code (round 2)", "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet", "warp prediction with a scaled reference (superres, unimplemented)", "an 8x8 partition leaf under a scaled reference (superres, unimplemented)", + "a motion_mode symbol for a block shape with no CDF row here", ]; /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index bd856bf9..7a094e68 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -55,6 +55,19 @@ fn final_dump_prefix() -> Option { /// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search: /// (HORZ_4 strips, VERT_4 strips, strips that read coefficients). +/// lane-inter4 r1: the INTER-frame partition counters this lane's gates +/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded. +pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) { + ( + crate::decode::rect4_32_horz_inter_hits(), + crate::decode::rect4_32_vert_inter_hits(), + crate::decode::inter_sb_horz_hits(), + crate::decode::inter_sb_vert_hits(), + crate::decode::inter_sb_horz4_hits(), + crate::decode::inter_sb_vert4_hits(), + ) +} + pub fn rect4_32_counters() -> (usize, usize, usize) { ( crate::decode::rect4_32_horz_hits(), @@ -63,6 +76,17 @@ pub fn rect4_32_counters() -> (usize, usize, usize) { ) } +/// lane-inter4 r4: rectangular inter transform units coded whole, rect +/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the +/// three counters a recipe sweep needs to see from outside the crate. +pub fn rect_inter_tu_counters() -> (usize, usize, usize) { + ( + crate::decode::rect_inter_tu_hits(), + crate::decode::rect_inter_txsplit_hits(), + crate::decode::obmc_rect_leaf_hits(), + ) +} + /// Decode every frame in a raw AV1 OBU stream, in coding order. /// /// A key frame becomes the reference for the inter frames that follow it, @@ -615,6 +639,9 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.mi_rows as usize, header.order_hint, ref_order_hints, + // `frame_type` for the DPB slot: a key (or intra-only) frame is + // never a projection source, and never spends a `ref_stamp`. + true, ); (picture, end_cdfs, motion_field) } else { @@ -921,6 +948,208 @@ mod tests { ); } + /// lane-oddh r2 GATE: the frame-edge half-strip arms r1 added (a 64x32 / + /// 32x64 superblock-level or 16x8 / 8x16 16-level INTER block where the + /// frame's true edge cuts the strip in half) actually fire and decode + /// pixel-exact, at both bit depths. 160 = two full superblock rows plus + /// 32 pixels, so every superblock in the last row is a half strip; without + /// r1's arms these attempts refused outright, which is why this gate + /// asserts a nonzero `edge_rect_strip_hits` DELTA on attempts that were + /// actually compared -- a refused attempt's hits would prove nothing + /// (class "counter from refused stream"). + #[test] + #[ignore = "2026-09-02 lane-oddh r2: no aomenc recipe reaches the INTER edge half-strip arm yet -- rect partitions OFF makes the encoder answer the forced gathered edge symbol SPLIT every time (both bit depths decode 192x160 pixel-exact, edge_rect_strip_hits=0), and rect ON stops at three other lanes' gaps first: at cq 40 'a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding', at cq 62 'an INTER 32x32 partition type this decoder does not code (value=8/9)' (HORZ_4/VERT_4 even with --enable-1to4-partitions=0), and at min-partition 16 'a HORZ/VERT intra strip below 16x16 with a split transform'. The KEY-frame half of the same edge is gated: the tiny size sweep now covers 64x72/72x64/64x136/136x64/192x136"] + fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); + return; + } + let (width, height, frames) = (192usize, 160usize, 6usize); + let mut compared = 0u32; + let mut strip_hits = 0usize; + let mut refused = 0u32; + for bit_depth in [8u32, 10u32] { + let duration = frames as f64 / 25.0; + let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25"); + 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 mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=62", + // cpu-used >= 1 keeps libaom on 64x64 superblocks at this + // size (`av1_select_sb_size`: speed >= 1 and <= 480p). + "--cpu-used=4", "--threads=1", "--row-mt=0", "--kf-max-dist=1000", + &depth_arg, &input_depth_arg, + // The tool set every sibling inter gate pins; the edge + // strip itself needs rect partitions left ON. + "--enable-warped-motion=0", "--enable-obmc=0", "--enable-masked-comp=0", + "--enable-interintra-comp=0", "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", "--enable-smooth-interintra=0", + // Rect partitions stay ON: the edge strip is a FORCED + // (gathered) HORZ at the boundary, but with rect coding + // off the encoder answers that gathered symbol SPLIT every + // time and the arm never fires (measured, r2). + "--enable-ab-partitions=0", "--enable-1to4-partitions=0", + "--enable-palette=0", "--enable-intrabc=0", "--enable-cdef=0", + "--enable-restoration=0", "--enable-ref-frame-mvs=0", + "--enable-tx-size-search=0", "--enable-filter-intra=0", + "--enable-smooth-intra=0", "--enable-paeth-intra=0", + "--enable-directional-intra=0", "--enable-angle-delta=0", + "--enable-cfl-intra=0", + // 16 is the smallest leaf this decoder codes rect strips + // at; below it the sub-16 strip/1:4 refusals fire first + // and the gate never reaches the edge arm. + // 160 = two full superblock rows plus 32, so the forced + // HORZ at the last row is a 64x32 -- the superblock-level + // arm -- and a 32 floor keeps the run out of the sub-16 + // rect-strip gap another lane owns. + "--min-partition-size=32", "--max-partition-size=64", + "--obu", "-o", "-", "-", + ]) + .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("write y4m"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr)); + let stream = out.stdout; + + let before = crate::decode::edge_rect_strip_hits(); + let decoded = match decode_stream(&stream) { + Ok(f) => f, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME}: {bit_depth}-bit failed outright, not a named refusal: {msg}" + ); + eprintln!("{NAME}: {bit_depth}-bit REFUSED {msg}"); + refused += 1; + continue; + } + }; + let reference = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames) + }; + assert_eq!( + decoded.len(), + reference.len(), + "{NAME}: {bit_depth}-bit frame count" + ); + for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() { + let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count(); + assert_eq!( + (nd(&ours.y, &theirs.y), nd(&ours.u, &theirs.u), nd(&ours.v, &theirs.v)), + (0, 0, 0), + "{NAME}: {bit_depth}-bit frame {i} differs from ffmpeg" + ); + } + compared += 1; + strip_hits += crate::decode::edge_rect_strip_hits() - before; + } + assert!(compared > 0, "{NAME}: every attempt refused ({refused}) -- gate proved nothing"); + assert!( + strip_hits > 0, + "{NAME}: {compared} attempts decoded pixel-exact but not one frame-edge half strip \ + fired -- the recipe no longer reaches the arm this gate exists for" + ); + eprintln!("{NAME}: {compared} attempts pixel-exact, edge_rect_strip_hits={strip_hits}, {refused} refusals"); + } + + /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real + /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at + /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows + /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition + /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case + /// r1 mis-read as a 10-symbol BLOCK_64X64 partition. + /// + /// The `use_128x128_superblock` assert is the "knob reached the tool" + /// half: without it an aomenc that ignored `--sb-size=128` would leave + /// the gate proving nothing about 128 superblocks. + #[test] + fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() { + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP: no ffmpeg/aomenc"); + return; + } + let (width, height) = (64usize, 72usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4", "-t", "0.04", + "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr)); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", + "--cpu-used=0", "--sb-size=128", "--kf-max-dist=0", "--limit=1", + "--threads=1", "--row-mt=0", "--obu", "-o", "-", "-", + ]) + .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("write y4m"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr)); + let stream = out.stdout; + + // The knob actually arrived: this stream's sequence header codes + // `use_128x128_superblock = 1`. + let mut parser = Av1Parser::new(); + let mut pos = 0usize; + let mut sb128 = false; + while pos < stream.len() { + let Ok(obu) = parser.parse_obu(&stream[pos..]) else { + break; + }; + pos += obu.total_size.max(1); + if let Some(seq) = parser.sequence_header() { + sb128 = seq.use_128x128_superblock; + break; + } + } + assert!(sb128, "aomenc ignored --sb-size=128: this stream is 64x64-superblock"); + + let _guard = lock_gate_counters(); + let (frames, hidden) = + decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72"); + assert!(frames > 0, "no frames decoded for {width}x{height}"); + eprintln!( + "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \ + {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}" + ); + } + /// `decode_stream` on a lone key frame's stream matches both the tile /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and /// the encoder's own reconstruction, at an even and an odd size. @@ -1965,6 +2194,10 @@ mod tests { // masked compound, palette, ...) are other lanes' work; // this gate is about hidden frames, not about them. "--enable-warped-motion=0", + // OBMC stays off HERE (this gate is about hidden frames); + // the tool's own coverage is the `obmc*` gates and, on a + // 16x8/8x16 leaf, the `--enable-obmc=1` arm of + // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4). "--enable-obmc=0", "--enable-masked-comp=0", "--enable-interintra-comp=0", @@ -2685,6 +2918,41 @@ mod tests { eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits()); } + /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu` + /// is the first frame of the user's ReelB AV1 release (3840x1608 + /// yuv420p10le, `ffmpeg -i -c copy -frames:v 1 -f obu`, 147 bytes) -- + /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel + /// superblock, so its last superblock row (mi_row=400 of 402) carries the + /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl` + /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and + /// this decoder used to READ that bit and throw it away, forcing SPLIT + /// (class `parsed-then-discarded`). The desync surfaced two rows later as + /// "a Golomb tail longer than this decoder reads" -- a refusal naming the + /// symptom, never the cause. + #[test] + fn the_reelb_head_key_frame_decodes_pixel_exact() { + const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/reelb_head_key_frame.obu"); + let stream = std::fs::read(&path) + .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); + let (width, height) = (3840usize, 1608usize); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused: {e}"), + }; + assert_eq!(frames.len(), 1, "{NAME}: one key frame"); + assert_eq!((frames[0].width, frames[0].height), (width, height)); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); + } + /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1 /// --superres-denominator=12` key frame, decoded pixel-exact against /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s @@ -4699,38 +4967,63 @@ mod tests { ); } - /// lane-chroma r2 stage 1: a real aomenc key frame with - /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`) - /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still- - /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never - /// fires; smooth *luma* neighbours are exactly what this gate wants to - /// exercise, proving [`decode::smooth_luma_hits`] actually landed a - /// directional block next to a smooth-predicted one and decoded - /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix). + /// lane-angleinter r1 (class [[refusal-strings-are-claims]] + + /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with + /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's + /// own defaults; every inter gate before this one pinned BOTH off) in + /// which the RD gives an INTRA block inside an inter frame a directional + /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms + /// read that symbol and then REFUSED it as "this encoder never writes + /// one" -- the claim is false, `read_intra_angle_info` writes it exactly + /// as a key frame does. Hard-asserts + /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never + /// produced one proves nothing, and exhausting every attempt is a + /// FAILURE, not a SKIP. #[test] - fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() { + fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact() + { + angle_delta_in_inter_gate(8, "--min-partition-size=16"); + } + + /// The 10-bit arm (both of the user's films are `yuv420p10le`). + #[test] + fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact() + { + angle_delta_in_inter_gate(10, "--min-partition-size=16"); + } + + fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) { + let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})"); + let leaf8 = min_partition.ends_with('8'); + assert!(!leaf8, "the 8x8-leaf arm keeps its refusal; see the module note"); if !have_ffmpeg() { - eprintln!( - "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg" - ); + eprintln!("SKIP {name}: no ffmpeg"); return; } if !have_aomenc() { - eprintln!( - "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}", - aomenc_path().display() - ); + eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); return; } - let (width, height) = (64usize, 64usize); + let (width, height, frame_count) = (64usize, 64usize, 8usize); let mut refusals = Vec::new(); - let mut fired_runs = 0u32; let mut uncounted_exact = 0u32; for attempt in 0..40u32 { let seed = 42 + attempt; + // A zooming fractal: every frame moves (so the sequence is + // genuinely inter-coded) and keeps sharp new detail entering at + // the borders, which is what makes aomenc's RD choose an INTRA + // block inside an inter frame -- and then split its transform. + // A zooming fractal with a hard CUT halfway (`overlay` switching + // a second, unrelated fractal on at frame 4): after the cut every + // block is unpredictable from the reference, which is what makes + // aomenc code INTRA blocks inside an inter frame -- and at this + // cq the RD then splits their transforms. let source = format!( - "mandelbrot=size=64x64:start_scale={}:rate=25", - 5.0 - f64::from(attempt) * 0.06 + "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\ + mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\ + [a][b]overlay=enable='gte(n,4)'", + 5.0 - f64::from(attempt) * 0.06, + 0.9 + f64::from(attempt) * 0.11 ); let y4m = Command::new("ffmpeg") .args([ @@ -4740,12 +5033,21 @@ mod tests { "lavfi", "-i", &source, + // Desaturated chroma keeps `uv_mode` on DC_PRED, so the + // still-refused directional-chroma gaps never fire and + // luma detail alone drives the transform split. + "-vf", + "hue=s=0", "-pix_fmt", - "yuv420p", + if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }, + "-strict", + "-1", "-t", - "0.04", + "0.32", "-f", "yuv4mpegpipe", + "-strict", + "-1", "-", ]) .stdin(Stdio::null()) @@ -4758,32 +5060,72 @@ mod tests { "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr) ); + // The 8x8-leaf arm is fenced by three sibling refusals (non-DC + // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter + // leaves), so it sweeps the quantiser as well as the source: a + // coarser q is what pushes the RD to directional intra at 8x8. + let cq = if leaf8 { + format!("--cq-level={}", 20 + (attempt % 5) * 10) + } else { + "--cq-level=30".to_string() + }; + let depth_args: &[&str] = if bit_depth == 10 { + &["-b", "10", "--input-bit-depth=10"] + } else { + &[] + }; let mut child = Command::new(aomenc_path()) + .args(depth_args) .args([ "--codec=av1", "--passes=1", "--end-usage=q", - "--cq-level=45", + &cq, "--cpu-used=0", - "--enable-rect-partitions=0", + "--lag-in-frames=0", + "--auto-alt-ref=0", + // One key frame only: every later frame is an inter frame, + // which is where this gate's intra blocks must sit. The + // MIN distance is what stops aomenc's scene-cut detector + // from inserting a second key frame at the cut this gate's + // source deliberately contains. + "--kf-max-dist=1000", + "--kf-min-dist=1000", + "--threads=1", + "--row-mt=0", + "--enable-order-hint=0", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", "--enable-ab-partitions=0", "--enable-1to4-partitions=0", - "--enable-filter-intra=0", - "--enable-smooth-intra=1", - // Smooth/paeth chroma is a still-refused, separate - // round-2 gap -- off so no attempt trips it while this - // gate is purely about luma's edge-filter fix. + "--enable-smooth-intra=0", "--enable-paeth-intra=0", - "--enable-tx-size-search=0", + "--enable-directional-intra=1", + "--enable-angle-delta=1", "--enable-cdef=0", "--enable-restoration=0", - "--enable-intra-edge-filter=1", - "--max-partition-size=32", - "--min-partition-size=16", "--enable-palette=0", "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0", + // Per-arm overrides go LAST (aomenc keeps the last + // occurrence of a repeated --enable-* flag): the intra + // tx_depth symbol only exists under TX_MODE_SELECT, and + // rect partitions are a separate named refusal. + "--enable-filter-intra=1", + "--enable-tx-size-search=1", + "--enable-rect-partitions=0", + "--max-partition-size=32", + // Sub-16 inter partitions are a separate named refusal, + // as is the 8x8 intra leaf's own TX_4X4 split. + min_partition, "--obu", "-o", "-", @@ -4807,21 +5149,214 @@ mod tests { String::from_utf8_lossy(&out.stderr) ); let stream = out.stdout; - let smooth_before = decode::smooth_luma_hits(); + let before = decode::intra_in_inter_angle_delta_y_hits(); + let before_uv = decode::intra_in_inter_angle_delta_uv_hits(); let frames = match decode_stream(&stream) { Ok(frames) => frames, Err(e) => { - refusals.push(format!("seed {seed}: {e}")); + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{name} decode failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); continue; } }; - // class [[gate-skips-on-its-own-failure]]: a decode that succeeded - // is ALWAYS pixel-compared below; the hit counter only decides whether - // the attempt counts toward the firing total. - let counted = decode::smooth_luma_hits() != smooth_before; - if counted { - fired_runs += 1; - } else { + let fired = decode::intra_in_inter_angle_delta_y_hits() - before; + let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv; + // class [[gate-skips-on-its-own-failure]]: a decode that + // succeeded is ALWAYS pixel-compared below; the counter only + // decides whether the attempt counts as firing. + let counted = fired != 0; + if !counted { + uncounted_exact += 1; + refusals.push(format!( + "seed {seed}: decoded and pixel-compared, but no intra block in an inter \ + frame carried a nonzero angle_delta_y" + )); + } + 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); + eprintln!( + "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \ + {fired}, angle_delta_uv = {fired_uv}" + ); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + for (plane, (g, w)) in [ + ("Y", (&got.y, &want.y)), + ("U", (&got.u, &want.u)), + ("V", (&got.v, &want.v)), + ] { + let stride = if plane == "Y" { width } else { width / 2 }; + if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { + eprintln!( + "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \ + want {} ({} samples differ)", + at % stride, + at / stride, + g[at], + w[at], + g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), + ); + } + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); + } + if counted { + gate_buckets( + &name, + 1, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); + return; + } + } + gate_buckets( + &name, + 0, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); + panic!( + "{name} never observed a nonzero angle delta on an intra block in an inter \ + frame:\n{}", + refusals.join("\n") + ); + } + + /// lane-chroma r2 stage 1: a real aomenc key frame with + /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`) + /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still- + /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never + /// fires; smooth *luma* neighbours are exactly what this gate wants to + /// exercise, proving [`decode::smooth_luma_hits`] actually landed a + /// directional block next to a smooth-predicted one and decoded + /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix). + #[test] + fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height) = (64usize, 64usize); + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + let mut uncounted_exact = 0u32; + for attempt in 0..40u32 { + let seed = 42 + attempt; + let source = format!( + "mandelbrot=size=64x64:start_scale={}:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-t", + "0.04", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=1", + // Smooth/paeth chroma is a still-refused, separate + // round-2 gap -- off so no attempt trips it while this + // gate is purely about luma's edge-filter fix. + "--enable-paeth-intra=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--enable-intra-edge-filter=1", + "--max-partition-size=32", + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]) + .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 smooth_before = decode::smooth_luma_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + refusals.push(format!("seed {seed}: {e}")); + continue; + } + }; + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::smooth_luma_hits() != smooth_before; + if counted { + fired_runs += 1; + } else { uncounted_exact += 1; refusals.push(format!( "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \ @@ -5623,27 +6158,951 @@ mod tests { ); } } - return; + return; + } + panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}"); + } + + #[test] + fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() { + chroma_class1_eob_gate( + "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact", + false, + ); + } + + #[test] + fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() { + chroma_class1_eob_gate( + "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact", + true, + ); + } + + /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/ + /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the + /// inter tile path refused outright before this lane ("an inter SB-level + /// partition type other than NONE or SPLIT"). `--min-partition-size=32` + /// keeps every 32x32-level rect shape (already coded, and residual-capable + /// only when skip) out of the picture so the counters can only be earned + /// at the superblock level; the noiseless split-motion source (one half + /// translating, the other static, flat inside each half) is what makes + /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` -- + /// the ONLY inter rect shape this decoder can complete, since rectangular + /// inter residual coding is not ported (see `reject_residual`). + /// + /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt + /// that refuses by name is counted, never turned into a SKIP; and an + /// attempt that decoded without firing the arm is counted separately and + /// still required to be pixel-exact (class gate-skips-on-its-own-failure). + #[test] + fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open + // residue, not a tolerance: across all 16 attempts x both depths, every + // 10-bit attempt that reached a superblock-level rect strip found it + // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B) + // strip needs rectangular residual coding". The 10-bit twin below is + // `#[ignore]`d with that exact reason rather than deleted or weakened. + for bit_depth in [8u32] { + let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = + (0u32, 0u32, 0u32, 0u32); + let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + for attempt in 0..16u32 { + // Two orientations (the transposed pair a one-sided gate could + // never separate) x four quantisers x two motion steps: which + // superblock the RD hands a skip-able rect strip moves with + // the quantiser, and the 10-bit arm needs a different corner + // of the grid from the 8-bit one. + let vertical_split = attempt % 2 == 1; + let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize]; + let sp = 8 + (attempt / 8) * 4; + let geq = if vertical_split { + format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)") + } else { + format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)") + }; + let duration = frame_count as f64 / 25.0; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='{geq}',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let cq_arg = format!("--cq-level={cq}"); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--enable-tx-size-search=0", "--lag-in-frames=0", + // Per-arm overrides go LAST: aomenc keeps the last + // occurrence of a repeated --enable-* flag. + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", "--min-partition-size=32", + "--max-partition-size=64", + "--obu", "-o", "-", "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = crate::stream::inter_rect_counters(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let after = crate::stream::inter_rect_counters(); + let (horz, vert) = (after.2 - before.2, after.3 - before.3); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + superblock-level inter rect strips -- another shape's defect" + ); + } + continue; + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + } + horz_proved += horz; + vert_proved += vert; + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \ + {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)" + ); + assert_eq!( + oos_mismatch, 0, + "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \ + decoded but mismatched ffmpeg -- a defect of another shape, not a pass" + ); + assert!( + horz_proved + vert_proved > 0, + "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \ + inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \ + {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing" + ); + } + } + + /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT` + /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1 + /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs + /// rectangular residual coding"). The strip's own rectangular max + /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree, + /// its coefficients through [`TxbSet::LumaRect32x16Inter`] / + /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse + /// transform. + /// + /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock + /// level (64x32, still refused -- no 64-point rect transform) out, so + /// every counted hit is a 32-level strip. The source is textured and + /// translating precisely so the strips are NOT skip: a flat source (r1's) + /// makes aomenc code them skip and proves nothing about the residual. + /// Both `--enable-tx-size-search` arms run: `=0` exercises the + /// whole-block rect transform with no `txfm_partition` symbol at all, + /// `=1` the rect var-tx tree (no-split rect unit, or the split into square + /// sub-transforms). + /// + /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and + /// V; a refusal is counted, never SKIPped; an attempt that carried no rect + /// inter residual is counted separately and still required pixel-exact. + /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream + /// whose compound blocks feed the next frame's motion field + /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`). + /// + /// lane-interbis r1 pinned this recipe because it is the one the rect + /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a + /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its + /// nearest candidate from a temporal cell holding the wrong reference: + /// `build_motion_field` stored a compound block's FIRST reference where + /// libaom stores its second). Every fully decoded attempt is compared + /// plane by plane; a refusal is counted, never SKIPped; the temporal + /// candidate counter must fire on a compared attempt, or the gate proves + /// nothing. + #[test] + fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize); + for attempt in 0..2u32 { + let tx_search = if attempt == 0 { "0" } else { "1" }; + let duration = frame_count as f64 / 25.0; + // The pinned source: horizontal structure translating along X + // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN + // blocks whose stored motion field the last frame reads back. + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let tx_arg = format!("--enable-tx-size-search={tx_search}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=34", "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--lag-in-frames=0", + // Per-arm overrides go LAST (aomenc keeps the last + // occurrence of a repeated --enable-* flag). + &tx_arg, + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=32", + "--obu", "-o", "-", "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::tmv_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let tmv = decode::tmv_hits() - before; + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + } + compared += 1; + tmv_proved += tmv; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \ + pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}" + ); + assert!( + compared > 0, + "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing" + ); + assert!( + tmv_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \ + candidate into a block's stack -- gate proved nothing" + ); + } + } + + /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the + /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only + /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF) + /// holds a key frame while temporal MV projection runs. libaom's + /// `motion_field_projection` returns 0 for such a start frame, so it costs + /// no `ref_stamp`; ours used to project the (empty) field and report + /// success, spending the slot ALTREF/LAST2 should have had and losing + /// their temporal candidates. + /// + /// Both bit depths; EVERY decoded frame (including the hidden alt-refs) + /// compared to the oracle in decode order; a refusal is counted, never + /// SKIPped. Two hard counters make the gate non-vacuous: frames that + /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks + /// that folded a temporal MV candidate into their stack. + #[test] + fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_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, 24usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) = + (0u32, 0u32, 0usize, 0usize); + let mut stamp2_proved = 0usize; + for attempt in 0..2u32 { + let duration = frame_count as f64 / 25.0; + // Natural-ish motion: structure translating along X at 3 px per + // frame plus a slow vertical drift, the source family the + // temporal-MV gate already decodes fully. + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 }); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=32", + // Per-arm/feature overrides go LAST (aomenc keeps the LAST + // occurrence of a repeated --enable-* flag). + "--enable-order-hint=1", "--enable-ref-frame-mvs=1", + "--enable-fwd-kf=1", "--fwd-kf-dist=8", "--kf-max-dist=1000", + "--lag-in-frames=16", "--auto-alt-ref=1", "--arnr-maxframes=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_tmv = decode::tmv_hits(); + let before_stamp = crate::motion_field::refstamp_intra_frames(); + if let Err(e) = decode_stream(&stream) { + 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; + } + let tmv = decode::tmv_hits() - before_tmv; + let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0; + let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1; + // Every frame, hidden ones included, compared in DECODE order. + let (total, hidden) = decode_all_frames_vs_oracle( + &stream, + &format!("{NAME}-{bit_depth}bit-attempt{attempt}"), + ); + eprintln!( + "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \ + ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \ + forward ref={stamp} (two or more: {stamp2})" + ); + compared += 1; + tmv_proved += tmv; + stamp_proved += stamp; + stamp2_proved += stamp2; + } + assert!( + compared > 0, + "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \ + proved nothing" + ); + assert!( + tmv_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \ + into a block's stack -- gate proved nothing" + ); + assert!( + stamp_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \ + holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \ + path this gate exists for never ran" + ); } - panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}"); } #[test] - fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() { - chroma_class1_eob_gate( - "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact", - false, - ); + // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter + // residual path IS implemented and reached, but no aomenc recipe swept + // this round produced a stream whose FIRST rect inter block is a 32x16 / + // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or + // an intra rect strip) earlier in the tile, and both of those still refuse + // by name, so the decode stops before any 32-level 2:1 strip. The 16x8 + // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the + // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect + // transform), which this round did not add. See lanes/inter4-r2.report.md. + // lane-inter4 r4 re-measured after the 16-level rect inter leaf shipped + // (r3): STILL RED, and the blocker moved -- 12 named refusals over 16 + // 8-bit attempts, 10 of them "an intra-coded HORZ/VERT strip needs + // rectangular intra prediction this decoder does not code yet" and 2 the + // 16-level AB/1:4 inter refusal; 4 attempts decoded with no rect inter + // residual at all and none of them mismatched (tu=0, split=0). Neither + // remaining blocker is this lane's: the gate un-ignores when the intra + // rect strip lands. + #[ignore = "lane-inter4 r4 (re-measured): 12/16 8-bit attempts stop at the intra-rect-strip (10) or 16-level inter AB/1:4 (2) refusal, the other 4 code no rect inter residual -- tu=0, split=0; blocked on rectangular INTRA prediction, not on this lane"] + fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = + (0u32, 0u32, 0u32, 0u32); + let (mut tu_proved, mut split_proved) = (0usize, 0usize); + for attempt in 0..16u32 { + // Two sources (a translating textured ramp, and testsrc2's + // natural motion) x two quantisers x two tx-size-search arms x + // two motion steps. + let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; + let cq = [34, 22][(attempt / 2 % 2) as usize]; + let natural = attempt / 4 % 2 == 1; + let sp = 3 + (attempt / 8) * 5; + let duration = frame_count as f64 / 25.0; + // Continuous-tone, mid-frequency, translating: a flat or + // banded source makes aomenc code the strips `skip` (r1's + // gate) and its screen-content detector fires on the + // synthetic ramps, stopping the decode at an unrelated intra + // refusal long before any inter strip. + // Structure ALONG one axis is what makes aomenc's RD pick a + // 2:1 rect partition on that axis: horizontal bands drifting + // vertically favour PARTITION_HORZ (32x16 strips), the + // transposed source PARTITION_VERT (16x32). + let lum = if natural { + format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)") + } else { + format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)") + }; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='{lum}',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let cq_arg = format!("--cq-level={cq}"); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let tx_arg = format!("--enable-tx-size-search={tx_search}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--lag-in-frames=0", + // Per-arm overrides go LAST: aomenc keeps the last + // occurrence of a repeated --enable-* flag. + &tx_arg, + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=32", + "--obu", "-o", "-", "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits()); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits()); + let (tu, split) = (after.0 - before.0, after.1 - before.1); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if tu + split == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + coded rect inter transform units -- another shape's defect" + ); + } + continue; + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + } + tu_proved += tu; + split_proved += split; + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \ + rect trees that split={split_proved}, {out_of_scope} attempts carried none \ + ({oos_mismatch} of them mismatched)" + ); + assert_eq!( + oos_mismatch, 0, + "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \ + mismatched ffmpeg -- a defect of another shape, not a pass" + ); + assert!( + tu_proved > 0, + "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \ + residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \ + {out_of_scope} out of scope) -- gate proved nothing" + ); + } } #[test] - fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() { - chroma_class1_eob_gate( - "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact", - true, + // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ / + // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter + // blocks, mode info + rectangular residual + prediction. Every decoded + // frame is compared Y/U/V against ffmpeg, refusals are counted and never + // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that + // also coded a rectangular inter transform unit (i.e. was not `skip`). + fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + // Coded (non-skip) rect inter transform units, summed over both bit + // depths: at 10 bits this recipe's rect leaves all come out `skip` + // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop + // reaching a rect leaf at all), so the RESIDUAL half of the claim is + // proven by the 8-bit arm while the 10-bit arm proves the mode-info, + // prediction and neighbour halves on both axes. + let mut tu_total = 0usize; + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = + (0u32, 0u32, 0u32, 0u32); + let (mut tu_proved, mut split_proved) = (0usize, 0usize); + let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize); + // lane-inter4 r4, measured residue of this recipe family (sweep + // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search + // on, via `decode_probe`'s `rect_inter:` counters): the rect + // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit + // rect leaf is always `skip` (tu=0 at every cq that decodes) -- + // below cq 22 every attempt stops at another lane's intra refusal + // ("a HORZ/VERT intra strip below 16x16 with a split transform"). + // Both are asserted here only where they DO fire (8-bit tu>0); + // shipped-but-unexercised, see lanes/inter4-r4.report.md. + // lane-inter4 r4: attempts 16..32 repeat the same sweep with + // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's + // instrumented-aomdec comparison showed the neighbour list AND + // every pre-filter frame bit-exact, so the arm is a gate now. + let mut obmc_leaf_proved = 0usize; + for attempt in 0..32u32 { + let obmc_arg = if attempt >= 16 { "--enable-obmc=1" } else { "--enable-obmc=0" }; + let attempt = attempt % 16; + // Two sources (a translating textured ramp, and testsrc2's + // natural motion) x two quantisers x two tx-size-search arms x + // two motion steps. + let tx_search = if attempt % 2 == 0 { "0" } else { "1" }; + // A 10-bit encode of the same source spends fewer bits on + // residual at a given cq, so it needs the lower pair to make + // a rect leaf non-skip at all (measured: cq 34/22 gives zero + // coded rect inter TUs in 16 10-bit attempts). + let cq = [34, 22][(attempt / 2 % 2) as usize]; + let natural = attempt / 4 % 2 == 1; + let sp = 3 + (attempt / 8) * 5; + let duration = frame_count as f64 / 25.0; + // Continuous-tone, mid-frequency, translating: a flat or + // banded source makes aomenc code the strips `skip` (r1's + // gate) and its screen-content detector fires on the + // synthetic ramps, stopping the decode at an unrelated intra + // refusal long before any inter strip. + // Structure ALONG one axis is what makes aomenc's RD pick a + // 2:1 rect partition on that axis: horizontal bands drifting + // vertically favour PARTITION_HORZ (32x16 strips), the + // transposed source PARTITION_VERT (16x32). + let lum = if natural { + format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)") + } else { + format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)") + }; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='{lum}',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let cq_arg = format!("--cq-level={cq}"); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let tx_arg = format!("--enable-tx-size-search={tx_search}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--lag-in-frames=0", + // Per-arm overrides go LAST: aomenc keeps the last + // occurrence of a repeated --enable-* flag. + &tx_arg, + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=8", + "--max-partition-size=16", + obmc_arg, + "--obu", "-o", "-", "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits()); + let before_obmc_leaf = decode::obmc_rect_leaf_hits(); + let before_leaf = ( + decode::inter_leaf16_horz_hits(), + decode::inter_leaf16_vert_hits(), + decode::inter_sub16_split_hits(), + ); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits()); + let (tu, split) = (after.0 - before.0, after.1 - before.1); + let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf; + let (horz, vert, splits16) = ( + decode::inter_leaf16_horz_hits() - before_leaf.0, + decode::inter_leaf16_vert_hits() - before_leaf.1, + decode::inter_sub16_split_hits() - before_leaf.2, + ); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + out_of_scope += 1; + if mismatched { + oos_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + 16-level rect inter leaf -- another shape's defect" + ); + } + continue; + } + if mismatched { + // lane-inter4 r3: where, not just that -- a handful of + // 4x4-aligned pixels is a prediction/reconstruction + // defect, a whole band from the first row down is a + // desync. + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + let bad: Vec = (0..got.y.len()) + .filter(|&k| got.y[k] != want.y[k]) + .collect(); + if !bad.is_empty() { + eprintln!( + "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \ + pixels differ, first at ({}, {}), max |delta| {}", + bad.len(), + bad[0] % width, + bad[0] / width, + bad.iter() + .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs()) + .max() + .unwrap_or(0) + ); + } + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"); + } + tu_proved += tu; + obmc_leaf_proved += obmc_leaf; + split_proved += split; + sub16_split += splits16; + if horz > 0 { + horz_proved += 1; + } + if vert > 0 { + vert_proved += 1; + } + matched += 1; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \ + 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \ + split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \ + leaf={obmc_leaf_proved}, {out_of_scope} attempts \ + carried none ({oos_mismatch} of them mismatched)" + ); + assert_eq!( + oos_mismatch, 0, + "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \ + mismatched ffmpeg -- a defect of another shape, not a pass" + ); + assert!( + horz_proved > 0 && vert_proved > 0, + "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \ + axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \ + SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \ + scope) -- gate proved nothing" + ); + assert!( + obmc_leaf_proved > 0, + "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \ + 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing" + ); + tu_total += tu_proved; + } + assert!( + tu_total > 0, + "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \ + residual on a 16-level leaf -- the residual half of the claim is unproven" ); } + #[test] fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() { if !have_ffmpeg() { @@ -11957,8 +13416,26 @@ mod tests { eprintln!("SKIP: no ffmpeg/aomenc"); return; } - let sizes: &[(usize, usize)] = - &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)]; + // lane-oddh r2: the second half of this list is the odd-height / + // odd-width ladder -- frame sizes whose last superblock row or column + // is a partial 64 (72 = one full SB plus 8 rows, 136 = two plus 8), + // which is where the frame-edge half-strip path r1 added is the only + // way to code the edge. 192x136 is the inter-sized member. + let sizes: &[(usize, usize)] = &[ + (8, 8), + (16, 16), + (32, 32), + (16, 32), + (32, 16), + (64, 64), + (48, 48), + (24, 24), + (64, 72), + (72, 64), + (64, 136), + (136, 64), + (192, 136), + ]; let mut total_exact = 0u32; for &(width, height) in sizes { let mut ok = 0u32; @@ -12076,12 +13553,12 @@ mod tests { } // Hit counter: the sweep proved nothing unless every size x seed // attempt really ran end to end (aomenc -> us -> ffmpeg compare). - // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds + // Floor (hit counter): 12 of the 13 sizes must decode all 10 seeds // pixel-exact -- only 8x8 is allowed to refuse outright today. If a // future change makes sizes refuse instead of decode, this fails // rather than passing on refusals alone. assert!( - total_exact >= 70, + total_exact >= 120, "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \ refusals cannot substitute for decodes" ); @@ -18672,12 +20149,16 @@ mod tests { geq=lum='mod(floor({axis}/8)*{step},256)',\ noise=alls={noise}:all_seed={seed},format=yuv420p" ); + // lane-band63: the second cq is 63, not 45 -- a near-max + // quantiser is where deblock/CDEF do the most work and where a + // 1:4 strip is most often skip; all 16 streams of this family at + // cq 63 (8- and 10-bit) decode pixel-exact. let cq_level = if tx_search { // 12..28: the window measured to fire both split depths on // this fixture (lanes/tx64x16-r4.handoff.md). format!("--cq-level={}", 12 + (attempt % 4) * 5) } else { - format!("--cq-level={}", if attempt % 4 < 2 { 32 } else { 45 }) + format!("--cq-level={}", if attempt % 4 < 2 { 32 } else { 63 }) }; let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; let y4m = Command::new("ffmpeg") @@ -18941,7 +20422,11 @@ mod tests { geq=lum='mod(floor({axis}/8)*{step},256)',\ noise=alls={noise}:all_seed={seed},format=yuv420p" ); - let cq_level = format!("--cq-level={}", [32, 45, 55][(attempt / 2 % 3) as usize]); + // lane-band63: 63 joins the rotation -- filter intra ON at a + // near-max quantiser is exactly the configuration the stale + // cq-63 premise blamed, and it decodes exact. + let cq_level = + format!("--cq-level={}", [32, 45, 55, 63][(attempt / 2 % 4) as usize]); let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; let y4m = Command::new("ffmpeg") .args([ diff --git a/lanes/angleinter-r1.report.md b/lanes/angleinter-r1.report.md new file mode 100644 index 00000000..c41f937e --- /dev/null +++ b/lanes/angleinter-r1.report.md @@ -0,0 +1,105 @@ +# lane-angleinter r1 — a nonzero angle delta on an intra block inside an inter frame + +Branch `lane-angleinter` off `lane-fiinter` 6b82994. Class: +[[refusal-strings-are-claims]] + [[tool-disabled-in-every-gate]]. + +## The claim, tested + +Both intra-in-inter arms read `angle_delta_y` and then refused it as +"a nonzero angle delta (this encoder never writes one)". The claim is FALSE: +aomenc's `--enable-angle-delta` defaults to 1 and libaom's +`read_intra_angle_info` (inside `read_intra_block_mode_info`, decodemv.c) +writes the symbol for any directional `y_mode` at bsize >= 8x8 exactly as a +key frame does. A real default-settings inter stream desynced there. + +Confirmed by the gate below on the FIRST attempt (seed 42, 8-bit): 4 intra +blocks inside inter frames carry a nonzero `angle_delta_y`. + +## What changed + +- `crates/ec-av1/src/decode.rs:15542` (`decode_inter_block`, >=16x16 arm): + refusal replaced by `read_angle_delta`; the delta is threaded into every + luma prediction of the block — the split-transform per-TU + `reconstruct`/`read_plane` pair and the block-level pair — where a literal + `0` used to go. +- `crates/ec-av1/src/decode.rs:15555`: the same arm derived + `smooth_neighbor` (`get_intra_edge_filter_type`, spec 7.11.2) via the + existing `Neighbours::modes_above_left` helper; it passed a hardcoded + `false` before, which was unobservable while every directional + intra-in-inter block was refused, and decides the intra edge filter's + strength once a delta'd angle reaches it. +- `crates/ec-av1/src/decode.rs:82` (+ around): counters + `intra_in_inter_angle_delta_y_hits` / `intra_in_inter_angle_delta_uv_hits`. +- `crates/ec-av1/src/decode.rs:17191` (`decode_inter_block8`, 8x8 leaf): + the refusal STAYS, reworded to a claim about this decoder's gate coverage + instead of about the encoder — see "Not lifted" below. +- `crates/ec-av1/src/stream.rs`: gate `angle_delta_in_inter_gate` + its 8-bit + and 10-bit tests. +- `refusal_inventory.rs`: the capability claim is gone; the 8x8-leaf refusal + is listed as a decoder-scoped refusal. `gate_coverage.rs`: + `enable-angle-delta` deleted from `NEVER_EXERCISED_8BIT` and `_10BIT`. + +## Gate + +`a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact` +(+ `..._10bit_...`). Recipe = the intrainter/fiinter one (64x64 mandelbrot +zoom with a hard overlay cut at frame 4, `--cq-level=30`, `--kf-min-dist=1000` +`--kf-max-dist=1000`, `--min-partition-size=16`) with +`--enable-directional-intra=1` and `--enable-angle-delta=1` — each flag +spelled ONCE in the arg list (the base recipe's `=0` entries were edited in +place, so flag precedence cannot silently invert the arm). Every frame's Y, U +and V are compared against ffmpeg; a decode error or mismatch is a FAILURE, +never a SKIP; the hit counter is a hard assert. + +``` +cargo test -p ec-av1 --lib with_a_directional_intra_block_with_angle_delta -- --nocapture +``` + +EVIDENCE: $HOME/.cache/angleinter-suite.log | aomenc --enable-angle-delta=1 --enable-directional-intra=1, 8 frames decoded and Y/U/V-compared vs ffmpeg | 8-bit seed 42: 4 nonzero-angle_delta_y intra-in-inter blocks, 0 sample mismatches; 10-bit seed 47: 4 blocks, 0 mismatches (buckets counted-exact=1 uncounted-exact=0) + +EVIDENCE: negative control (scratchpad decode.rs.bak diff) | re-inserted `return Err(unsupported("NEGATIVE CONTROL: a nonzero angle delta"))` at decode.rs:15549, reran both gates | 2 passed -> 2 FAILED, all 40 attempts refused with that string; lift reverted afterwards + +## Mutation sweep (task 3) + +All 56 `--enable-angle-delta=0` spellings in `stream.rs` flipped to `=1`, then +the 17 `inter_sequence` gates rerun: **17 passed / 0 failed** — no hidden +defect behind the flag. stream.rs restored from the scratchpad copy +afterwards (only the new gate's own two spellings are `=1` on the branch). + +EVIDENCE: mutation run | sed -i 's/--enable-angle-delta=0/=1/g' + `cargo test -p ec-av1 --lib inter_sequence` | test result: ok. 17 passed; 0 failed; 2 ignored + +## Not lifted (disposition) + +`deferred: the 8x8-leaf arm's nonzero-delta case (decode.rs:17205) — 80 +attempts (64x64 and 128x128 sources, cq 20/30/40/50/60, seeds 42..81) never +produced an 8x8 intra leaf with a nonzero angle_delta_y, nor even one with a +directional luma mode: the leaf's three sibling refusals ("a non-DC chroma +mode on an 8x8 inter-frame leaf", "an 8x8 intra leaf ... whose tx_depth +splits it into 4x4 transform units", "an inter partition below 16x16 other +than SPLIT") fire first on 37/40 attempts. Lifting it would ship an ungated +capability claim (class refusal-lifted-without-a-gate), so the refusal stays, +reworded to be about this decoder. — unblocked by: lifting the non-DC-chroma +and TX_4X4-split refusals on that leaf, which then makes a directional 8x8 +intra leaf reachable.` + +`accepted: angle_delta_uv fired 0 times in every passing attempt — the +recipe's `hue=s=0` desaturation is what keeps uv_mode on DC and the transform +split luma-driven. The uv delta path was already read AND already threaded +into both chroma predictions before this round (decode.rs:15556 ff.), so the +lift did not touch it; the counter is in place for a future chroma gate.` + +`accepted: decode_inter_block8 still passes a hardcoded `false` for its luma +edge-filter neighbour type. Unobservable while its directional-mode +population is empty (see above); reverted rather than shipped ungated.` + +## Suite + film + +`cargo test -p ec-av1 --lib` (systemd unit, log `$HOME/.cache/angleinter-suite.log`): +**348 passed / 0 failed / 32 ignored**, 384 s. + +Film probe (`hg-head.obu`, 0.4 s of the ReelB 2160p10 film, 18 frame +headers): now stops at `filter intra on a HORZ/VERT strip (this decoder +predicts square-only)` — a different, rect-prediction refusal; the angle-delta +refusal is no longer on its path. + +EVIDENCE: $HOME/.cache/angleinter-suite.log | `cargo test -p ec-av1 --lib` under a systemd unit + `cargo run --example decode_probe -- hg-head.obu` | 348 passed / 0 failed; film refusal string = "filter intra on a HORZ/VERT strip" diff --git a/lanes/band63-r1.report.md b/lanes/band63-r1.report.md new file mode 100644 index 00000000..4eec8691 --- /dev/null +++ b/lanes/band63-r1.report.md @@ -0,0 +1,119 @@ +# lane-band63 r1 — the cq-63 "defect" does not exist; a real one at cq 32 does + +Branch `lane-band63` off main `c729a38`, plus a merge of `lane-fi32x8` (c3a5032) so the +filter-intra-on configuration could be tested at all. + +## 1. The chartered premise is FALSE (measured, not argued) + +Charter: *"the 8-px band fixture at `--cq-level=63` mismatches ffmpeg on frame 0 for 8-bit +seeds 58/59/64 EVEN WITH `--enable-filter-intra=0`"* (from lanes/fi32x8-r1.report.md residue). + +Reproduced the exact recipe (fi32x8 gate family: `geq=lum='mod(floor({axis}/8)*{step},256)'`, +`noise=alls={18+(attempt%4)*3}:all_seed={42+attempt}`, `--cq-level=63`, cpu-used=0, +1:4 partitions on, min/max partition 8/32, directional/paeth/smooth intra off) and swept it +far wider than the three named seeds: + +| sweep | streams | result | +|---|---|---| +| fi32x8 family, attempts 0..23, 8+10 bit, `--enable-filter-intra=0` | 48 | 48 pixel-exact, 0 refusals | +| fi32x8 family, attempts 0..23, 8+10 bit, `--enable-filter-intra=1` (last) | 48 | 48 pixel-exact, 0 refusals | +| 32x32-gate family (noise 6..15), attempts 0..7, 8+10 bit, cq 63 | 16 | 16 pixel-exact | +| 32x32-gate family, seeds 58/59/64 x noise 6/9/12/15 x both axes, cq 63 | 24 | 24 pixel-exact | + +Seeds 58/59/64 (= fi32x8 attempts 16/17/22) are inside the first two rows and are exact at +both depths. Streams hashed; generator `gen.sh`/`gen2.sh`/`gen3.sh` in the scratchpad. + +EVIDENCE: $HOME/.cache/cargo-target-band63/debug/examples/decode_probe + ffmpeg rawvideo | 136 aomenc streams at cq 63 regenerated across 4 parameter sweeps, each decoded by ec-av1 and by ffmpeg and byte-compared full-frame (8-bit u8 dump, 10-bit u16 dump) | 136/136 identical, 0 refusals + +Why the premise looked true in fi32x8's round: that lane's control ran `--enable-filter-intra=0` +*before* the base recipe's `--enable-filter-intra=1`, and **aomenc keeps the LAST occurrence** +(class aomenc-first-flag-wins, already in memory) — so the control flag never arrived, and what +it saw was its own then-unfixed filter-intra path, not "another shape". Class: stale-premise +lanes / refusal-names-a-correlate. + +My own instrument repeated the class once: `decode_probe` had no 10-bit dump, so an +`EC_PROBE_OUT16` compare against a never-written file read as MISMATCH for three streams +(class stale-output-faked-measurement). Fixed by adding the dump, then re-measured. + +## 2. What changed + +- `crates/ec-av1/examples/decode_probe.rs:81` — `EC_PROBE_OUT16` dumps planes as + little-endian u16, the only form a 10-bit pixel diff against + `ffmpeg -pix_fmt yuv420p10le` can use. Without it no 10-bit claim from this instrument is real. +- `crates/ec-av1/src/stream.rs:16757` — the 32x32-level 1:4 gate's second quantiser is **63** + instead of 45 (attempts 2,3,6,7 at both depths). The cq-32 attempts keep their exact streams, + so nothing changes by accident. cq 63 is now coded, so the premise cannot come back unmeasured. +- `crates/ec-av1/src/stream.rs:16992` — the filter-intra 1:4 gate's rotation is + `[32,45,55,63]` (attempts 6,7,14,15 at cq 63), same reason, with filter intra ON. + +Both gates keep every existing hard assert (per-depth `horz_proved > 0 && vert_proved > 0`, +`coeff_proved > 0`, `matched > 0`, `out_of_scope_mismatch == 0`, full-frame Y/U/V compare). + +Gate run: +``` +EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-band63 \ + cargo test -p ec-av1 --lib -j3 -- --nocapture 1to4 +``` +→ `test result: ok. 3 passed; 0 failed` (14.7 s): +- 32x32-level 1:4: 8-bit 8/8 exact, horz_4=56 vert_4=84 coded=140; 10-bit 8/8 exact, + horz_4=56 vert_4=68 coded=124. +- filter-intra 1:4: 8-bit 5 matches/3 refusals, 54x(32x8)+5x(8x32); 10-bit 6 matches/1 refusal, + 9x(32x8)+17x(8x32). +- superblock-level 1:4 (sibling, untouched): ok. + +EVIDENCE: gate stdout above | both 1:4 gates run with cq 63 in the rotation at 8 and 10 bit | 3 passed / 0 failed, cq-63 attempts pixel-exact with the 1:4 counters non-zero per depth + +## 3. A REAL defect found on the way (NOT the chartered one) + +The first rotation I tried (`[32,45,63]`) also moved attempt 6 from cq 45 to cq 32, creating a +stream nothing had ever coded — and it mismatches. Fully bisected, then set aside because it is +not this lane's charter and not reachable from the shipped rotation: + +- Stream: 192x128, 8-bit, seed 48, `geq` axis Y, step 103, `noise=alls=12:all_seed=48`, + **`--cq-level=32`**, otherwise the 32x32-level 1:4 gate recipe (filter intra off). + Pinned at `/tmp/.../scratchpad/b63/gateA.obu` (regenerate: `gen.sh 48 Y 103 12 32 8 `). +- Stage: **reconstruction**, not filtering — `EC_AV1_PREFILT_DUMP` already differs, identically + to `EC_AV1_POSTDEBLOCK_DUMP` (9057 luma samples, first at x=64,y=64). +- First divergent element (range ladder, `EC_TRACE_MODE`/`EC_TRACE_MODE_STEP`, ours vs the + instrumented aomdec, aligned by (mi_row, mi_col, name)): **`mi_row=24 mi_col=8`, element + `mode`** — identical entry range 46952 on both sides, then aomdec `val=12 rng=36608`, + ec-av1 `val=7 rng=33744`. Same range in, different value and range out = **wrong y-mode CDF + row**, i.e. a wrong intra-mode neighbour context, not a wrong table value. +- Context: the block is `BLOCK_32X16` (aomdec `bsize=8`) at the 32x32 level; its *above* + neighbour is the last 32x8 `PARTITION_HORZ_4` strip at (22,8) (mode 12/PAETH) and its *left* + is the 32x8 strip at (24,0) (mode 0/DC). `decode_block_rect4` (decode.rs:5990) stamps the + COARSE 16-px `above_mode`/`left_mode` cells with "last strip wins"; the suspect is that + coarse stamp seen by a 32x16 sibling in the next quadrant (class + context-read-from-one-cell / neighbour-votes-all-its-fields). +- Everything before that element is bit-exact: the ladder matches element for element through + `mi_row=22`, so the entropy stream, the strips' own coefficients and their pixels are right. + +EVIDENCE: /tmp/.../scratchpad/b63/{gateA.obu,ours.trace,aom.trace,o.pre.f0,a.pre.f0} | ec-av1 vs instrumented aomdec range ladders + pre-filter/post-deblock dumps on the pinned stream | first divergence mi_row=24 mi_col=8 `mode` (entry rng 46952 both, out 36608 vs 33744); recon differs from (64,64), 9057 luma samples, deblock-only bleed at rows 62-63 + +## 4. Residue + +- deferred: the seed-48 @ cq-32 y-mode-context defect above — a wrong CDF row for a 32x16 block + whose above neighbour is a 32x8 1:4 strip — what unblocks it: reading the above/left mode ctx + ec-av1 computes at (24,8) against libaom's `intra_mode_context[]` of the same two neighbours + (the ladder, stream and stage are already pinned above, so it starts at the fix, not the hunt). + Not reachable from the shipped gate rotation (attempts 0,1,4,5 keep their original cq-32 + streams and pass). +- accepted: this lane merges `lane-fi32x8` (c3a5032, merge-ready per its own report) because the + filter-intra-on arm of the premise cannot be tested on main, which still refuses those strips. + If fi32x8 lands on main first, this merge is a no-op. +- accepted: no refusal is lifted this round — nothing was refused. The deliverable is a coded + quantiser the gates never coded, and a disproof. + +## 5. Suite + +``` +systemd-run --user --unit=band63-suite-... -p MemoryMax=10G --same-dir bash -lc \ + 'EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-band63 \ + nice -n 10 cargo test -p ec-av1 --lib -j3 > $HOME/.cache/band63-suite.log 2>&1' +``` +→ `test result: ok. 340 passed; 0 failed; 31 ignored` (337.9 s). + +`a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact` — red on main 11633d7 when +lane-fi32x8 reported — is green here: lane-mtfix fixed it in main c729a38, this base carries it. + +EVIDENCE: $HOME/.cache/band63-suite.log | full `cargo test -p ec-av1 --lib` on lane-band63 c099bef with the oracle required | 340 passed / 0 failed / 31 ignored diff --git a/lanes/golomb-r1.report.md b/lanes/golomb-r1.report.md new file mode 100644 index 00000000..484257cb --- /dev/null +++ b/lanes/golomb-r1.report.md @@ -0,0 +1,47 @@ +# lane-golomb r1 — the edge partition bit was read and thrown away + +## Verdict +The "a Golomb tail longer than this decoder reads" refusal on the ReelB head was, as +suspected (`refusal-from-own-desync`), a symptom. Root cause: at a frame edge the partition +symbol is a single *gathered* bit, and this decoder read it and **discarded** it, always +inferring `PARTITION_SPLIT`. libaom `ec_read_partition_impl` (decodeframe.c:1255): +`!has_rows && has_cols` → `read ? PARTITION_SPLIT : PARTITION_HORZ`; the mirror case → +`PARTITION_VERT`. Class: `parsed-then-discarded`. + +Charter STEP-2 fallback ("libaom read_golomb caps at 32 bits, extend the reader") is FALSE: +`~/.cache/aom-oracle/src/av1/decoder/decodetxb.c:22` aborts the frame at `length > 20`, exactly +our cap. The cap was never the bug and is unchanged. + +## First divergent element (EVIDENCE) +EVIDENCE: /tmp/.../scratchpad/{ao-all.txt,ours-all.txt} | instrumented aomdec vs decode_probe, +EC_TRACE_MODE+EC_TRACE_MODE_STEP+EC_TRACE_COEFF on the 2-frame extract f2.obu, ladders aligned +element by element on msac RANGE | first diff at element 12053: key frame, **mi_row=400 +mi_col=0** (last, 8-pixel-tall superblock row of a 1608-tall frame), `name=skip` +oracle rng=34753 vs ours rng=43258. Oracle codes that superblock as one `BLOCK_64X32` +(`EC_IMODE ... bsize=11`, PARTITION_HORZ); we forced SPLIT and descended to 16x16. +After the fix the range ladder is element-exact for all 13712 shared elements of the key frame +(EVIDENCE: /tmp/.../scratchpad/{a4.n,o4.n} | awk first-diff | idx 13713, inside a later INTER +frame, i.e. past the whole key frame). + +## Fix +`crates/ec-av1/src/decode.rs` — every edge-partition site, both tile paths, all three levels +(64/32/16, intra and inter): the gathered bit now names HORZ/VERT vs SPLIT. The 64-level +HORZ/VERT arms only decode the second half when it is inside the frame (`has_rows`/`has_cols`), +mirroring libaom `decode_partition`. The intra 16x16 edge site can only walk four SPLIT leaves, +so a 0 bit refuses by name there (new string, listed in `refusal_inventory.rs`) instead of +desyncing. + +## Gates +- NEW `stream::tests::the_reelb_head_key_frame_decodes_pixel_exact` — the film itself: + `crates/ec-av1/fixtures/reelb_head_key_frame.obu` (147 B, first frame of his 3840x1608 + yuv420p10le release) decodes and matches `ffmpeg -pix_fmt yuv420p10le` on Y, U and V. + EVIDENCE: cargo test -p ec-av1 --lib -- the_reelb_head_key_frame | 1 passed | + Y/U/V all equal to ffmpeg's decode, 3840x1608. +- Full lib suite: `$HOME/.cache/golomb-suite.log` — **337 passed / 0 failed / 31 ignored**. + +## Film probes after the fix +- `hg-head.obu` (18 frames): key frame + first inter frames now entropy-exact; stops at + "an inter SB-level partition type other than NONE or SPLIT" — the same edge partition, now + correctly decoded as HORZ, on an INTER superblock row the inter path cannot code (rect inter + residual coding does not exist here). Next lane. +- `reelb5.obu`: "a 32x32-level 1:4 strip with a split transform (depth=2)" (unchanged by this lane). diff --git a/lanes/inter4-r1.report.md b/lanes/inter4-r1.report.md new file mode 100644 index 00000000..9dba6d76 --- /dev/null +++ b/lanes/inter4-r1.report.md @@ -0,0 +1,97 @@ +# lane-inter4 r1 — inter-frame rect / 1:4 partition arms + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off main `146896f` (charter said 8262b99; main had moved two merges further — +the worktree was already at 146896f and was NOT rebased backwards). + +## Premise re-measure (charter's premise was stale) + +`cargo run --release --example decode_probe` on both ReelC extracts, on THIS tree +before any edit of mine, stops at + + unsupported: AV1 tile (a coded HORZ/VERT strip whose chroma transform has no + rect coefficient tables here) + +i.e. an INTRA-frame refusal owned by lane-rectchroma, not "an INTER 32x32 partition +type ... (value=9)". The charter's `value=9` observation was made on lane-rectchroma +587d388, a tree where that intra refusal is already lifted. So ReelC's *next* blocker +after rectchroma merges is plausibly the inter 1:4 arm, but this lane cannot observe it. + +## The real ceiling this round found + +`decode_inter_block` refuses every NON-SKIP rectangular inter block: + + decode.rs:12938 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs + rectangular residual coding" + +Rectangular inter residual coding does not exist. Empirically (30 aomenc recipes swept, +`$HOME/.cache/inter4-probe`), every real stream that reaches an inter rect strip finds it +non-skip and stops there — including every 10-bit attempt of this lane's own gate. +Porting the partition ARMS is therefore necessary but not sufficient: the arms are +reachable, but only an all-skip strip completes. + +## Changed + +- `crates/ec-av1/src/decode.rs` + - `decode_inter_block`'s `at` is now in **MI (4 px) units**, not 16-px cells — a 32-level + 1:4 strip sits at an 8-px offset the old unit could not name. All 20 call sites wrapped + in the new `sub16_to_mi` helper; the body routes through `around_mi`, + `record_rect_mi` (new), `record_split_luma_rect_mi` (new), `record_inter_rect_mi`, + `record_compound_ctx_rect_mi`. `record_rect`/`record_split_luma_rect` now delegate to the + new mi variants, so there is one implementation each. + - `motion_mode`/`obmc` CDF row selection: `bsize_idx` is a full `(write_w, write_h)` match + over every shape the decoder can now reach; an unknown shape refuses by name instead of + reading the wrong-width alphabet (class wrong-alphabet-same-value). + - `interintra` is no longer read on a 1:4 strip: `is_interintra_allowed_bsize` is + `BLOCK_8X8..=BLOCK_32X32` in libaom's ENUM ORDER, which excludes BLOCK_8X32 (18) and + BLOCK_32X8 (19) even though both dimensions are in range (class + equal-range-means-unread / symbol the reference never wrote). + - `maybe_read_delta_q`/`_lf`'s `is_whole_sb` is now `bsize == sbSize` (`side == 64 && + write_w == 64 && write_h == 64`), not `side == 64` — a 64x32 strip's `skip` must not + suppress the read. + - inter tile, superblock level: `PARTITION_HORZ`/`VERT`/`HORZ_4`/`VERT_4` arms + (two 64x32/32x64 strips, four 64x16/16x64 ones) with libaom's `i > 0` frame-edge break. + AB at superblock level still refuses, by a new named string. + - inter tile, 32x32 level: `PARTITION_HORZ_4`/`VERT_4` arms (four 32x8 / 8x32 strips, + quarter step 2 mi). + - new counters + accessors: `rect4_32_{horz,vert}_inter_hits`, + `inter_sb_{horz,vert,horz4,vert4}_hits`. + - a local `inter_piece!` macro carries the shared 50-argument call instead of six more copies. +- `crates/ec-av1/src/cdf.rs`, `cdf_state.rs` — `OBMC`/`MOTION_MODE` widened 6 -> 12 rows with + libaom's BLOCK_32X64/64X32/8X32/32X8/16X64/64X16 rows (`default_{obmc,motion_mode}_cdf`, + `entropymode.c:549,562` of the oracle source). +- `crates/ec-av1/src/refusal_inventory.rs` — the SB-level string now names AB only; new + "a motion_mode symbol for a block shape this decoder has no CDF row for". +- `crates/ec-av1/src/stream.rs` — `inter_rect_counters()` + the new gate. +- `crates/ec-av1/examples/decode_probe.rs` — prints the six inter rect counters. + +## Gate + +`a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact` +(stream.rs). 16 attempts x {2 orientations, 4 quantisers, 2 motion steps}, 192x128, 6 frames, +`--min-partition-size=32 --max-partition-size=64 --enable-rect-partitions=1 +--enable-1to4-partitions=1 --lag-in-frames=0 --cpu-used=0` (overrides last, aomenc keeps the +last occurrence). Noiseless split-motion source (one half translating, the other static) is +what makes aomenc's RD pick a superblock HORZ whose strips are `skip`. Every decoded frame is +compared Y/U/V to ffmpeg; refusals are counted, never SKIPped; a decoded attempt that carried +no rect strip is still required to be pixel-exact. + + EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib superblock_level_rect_partition -- --nocapture + +EVIDENCE: $HOME/.cache/inter4-suite.log + `cargo test -p ec-av1 --lib superblock_level_rect_partition` | 16 aomenc encodes, decode + ffmpeg Y/U/V pixel compare over 6 frames each | 8-bit: 4 named refusals, 2 pixel-exact attempts carrying the arm, 64x32 strips=4, 32x64 strips=0, 10 out-of-scope (0 mismatched); gate ok. Full suite at commit 754a7dd: 321 passed / 2 failed / 30 ignored; both failures were stale pins of MINE (the SB refusal string and a line-continuation in a new refusal literal) and are fixed in the follow-up commit -- the suite has NOT been re-run end to end since. + +## Open residue (nothing here is claimed done) + +- **fix-now (r2): rectangular inter residual coding.** Until it exists no gate can cover a + non-skip inter rect strip, and that is 100% of what real content produces. This blocks: + the 32-level 1:4 inter arms (0 hits in every recipe swept), the SB-level VERT arm (fires, + then its second strip is non-skip), the SB-level 1:4 arms, and the whole 10-bit side. +- **deferred: the 10-bit twin of the new gate** — every 10-bit attempt found the strip + non-skip. Unblocked by the item above. Written as an 8-bit-only loop with the reason in + the source, not a weakened assert. +- **deferred: SB-level AB inter partitions** — refused by name, no gate. Unblocked by the + same residue (their pieces are rect too). +- **accepted: `size_group` stays 3 for rect pieces** — inert (it only feeds the intra + `y_mode` branch, which refuses non-square) and it matches the existing 32-level HORZ arm. +- **DO NOT MERGE the two new arms as a capability claim**: the SB-level HORZ arm is gated, + the SB-level VERT/1:4 and the 32-level 1:4 arms are NOT (class refusal-lifted-without-a-gate). diff --git a/lanes/inter4-r2.report.md b/lanes/inter4-r2.report.md new file mode 100644 index 00000000..aa71f368 --- /dev/null +++ b/lanes/inter4-r2.report.md @@ -0,0 +1,128 @@ +# lane-inter4 r2 — rectangular INTER residual coding + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off r1's `59ccb01` (main `146896f`). No rebase this round (main unchanged since). + +## Owed from r1: the full suite at 59ccb01 + + $HOME/.cache/inter4-suite-r2a.log + test result: ok. 323 passed; 0 failed; 30 ignored; finished in 458.10s + +r1's two self-failures were indeed fixed by `59ccb01`. + +EVIDENCE: $HOME/.cache/inter4-suite-r2a.log | ec-av1 --lib under systemd-run at 59ccb01 | 323 passed / 0 failed / 30 ignored + +## What this round built (capability present, NOT claimed proven) + +Rectangular inter residual coding for the 2:1 shapes whose tables exist — +32x16 / 16x32 (`crates/ec-av1/src/decode.rs`): + +- `rect_inter_residual_supported` (decode.rs) — the shape gate. The r1 refusal + string ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular + residual coding") is now conditional on it, so `refusal_inventory` is + unchanged and 64x32/64x16/32x8/8x32/16x8 keep refusing by name. +- `read_block_tx_size_rect` — spec 5.11.17 from the block's own *rect* + `max_txsize_rect_lookup` entry. `TX_MODE_LARGEST`: no symbol, one rect TU. + `TX_MODE_SELECT`: one depth-0 `txfm_partition` symbol whose context comes + from the new `txfm_partition_ctx_rect` (above compares `tx_size_wide`, left + `tx_size_high`, category from `txsize_sqr_up_map`); `0` leaves one rect TU, + `1` splits into `sub_tx_size_map`'s two SQUARE sub-transforms from which the + existing square `read_var_tx_size` continues at depth 1 — so every leaf of a + split rect block is square and the existing square leaf loop reconstructs it. +- `txfm_partition_update_rect` / the skipped-inter case — a skipped rect inter + block records its own BLOCK width above and height left (libaom + `set_txfm_ctxs(.., skip && is_inter)`), where r1 recorded a square `side` + both ways. +- `read_inter_plane_rect` + `embed_rect_grid` — rect coefficients via + `read_coeffs_rect` (TxClass-aware scans/contexts), rect inverse via + `dequant_and_inverse_typed_wh`, added onto the top-left `w x h` of the + square-strided MC predictor. `txb_skip_ctx` 0 for luma (this unit IS the + block: `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch); + chroma at `av1_get_max_uv_txsize` (16x8 / 8x16, `TxbSet::ChromaRect16x8`), + inheriting the luma unit's `tx_type`. +- `cdf_state.rs`: new `TxbSet::LumaRect32x16Inter` — `LumaRect32x16`'s + coefficient tables (512-coefficient `eob_pt`) plus the inter `tx_type` + alphabet `default_inter_ext_tx_cdf[3][TX_16X16]` (`EXT_TX_SET_DCT_IDTX`, + which is what `av1_get_ext_tx_set_type` returns for an inter TU with + `tx_size_sqr_up == TX_32X32`) — i.e. the existing `INTER_TX_TYPE_SET3_16`. +- Two out-of-bounds fixes found by the new content (both in r1 code, both hit + before any of this round's residual code runs): `around_mi(at, side)` read + `side` cells left for a rect strip and indexed past the tile's last mi row + (now `around_mi_rect(at_mi, write_w, write_h)` for a rect strip); and + `record_rect_mi`/`record_split_luma_rect_mi` stamped past the frame's last + 16-px column for an edge strip (now bounds-checked). +- `EC_AV1_RECT_DUMP=1` prints the shape of every refused rect strip. +- New counters `rect_inter_tu_hits` / `rect_inter_txsplit_hits` + accessors. + +## Gate — RED, kept and `#[ignore]`d with its exact reason + +`a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact` +(stream.rs): 16 attempts x {2 axis-structured sources, 2 quantisers, 2 +`--enable-tx-size-search` arms, 2 motion steps} x {8-bit, 10-bit}, 192x128, +6 frames, `--enable-rect-partitions=1 --enable-ab-partitions=0 +--enable-1to4-partitions=0 --min-partition-size=16 --max-partition-size=32`, +overrides last; every decoded frame compared Y/U/V to ffmpeg, refusals counted +never SKIPped, out-of-scope attempts still required pixel-exact. + +It never fires, and the reason is NOT the residual code: on real motion content +the decode stops earlier, every attempt, at one of + + an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter leaves are not coded yet) + an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet + an inter partition below 8x8 ... + +so no stream ever reached a 32x16/16x32 inter strip. Content sweep this round +(4 source families x cq 22..61): flat/banded sources make the strips `skip` +(r1's case) or trip aomenc's screen-content detector into an intra-strip +refusal; textured/natural ones reach 16-level rect leaves first. `EC_AV1_RECT_DUMP` +on the earlier recipe showed the only rect shapes actually refused were 32x8 / +8x32 (the 32-level 1:4 arms), never 32x16. + +EVIDENCE: `cargo test -p ec-av1 --lib coded_rectangular_residual -- --nocapture` | 16 aomenc encodes x 8-bit, decode + ffmpeg Y/U/V compare | 15 named refusals, 0 attempts carrying a rect inter residual, whole-block rect TUs=0 -- gate proved nothing, so it is `#[ignore]`d with that sentence, not weakened + +EVIDENCE: `cargo test -p ec-av1 --lib superblock_level_rect_partition -- --nocapture` | r1's skip-strip gate re-run on this round's tree | 4 named refusals, 2 pixel-exact attempts carrying the arm, 64x32 strips=4, 0 mismatches -- the rect skip-context change did not regress it + +## Suite + + $HOME/.cache/inter4-suite-r2.log (systemd-run, unit inter4-suite-r2) + test result: ok. 323 passed; 0 failed; 31 ignored; finished in 410.27s + +Same 323 passing as the 59ccb01 baseline; the one extra ignored test is this +round's red gate. + +EVIDENCE: $HOME/.cache/inter4-suite-r2.log | ec-av1 --lib under systemd-run at b9dec1f | 323 passed / 0 failed / 31 ignored + +Sibling gates inside that run: inter_sequence*, 8x8_leaf_split, tx_select, +superblock_level_*, obmc, warp, globalmv, force_integer_mv, refusal_inventory, +gate_coverage -- all green. + +## Residue + +- **fix-now (r3): 16x8/8x16 inter rect leaves.** They are the real reach + blocker: real content codes one before any 32-level 2:1 strip. Needs (a) the + 16-level rect inter partition arm, (b) `default_inter_ext_tx_cdf[2][TX_8X8]` + (12-symbol `DTT9_IDTX_1DDCT` at `tx_size_sqr == TX_8X8`, reachable only + through a rect transform) as a new CDF + adaptation field, (c) a + `TxbSet::LumaRect16x8Inter`. The residual machinery this round added then + covers them unchanged. +- **deferred: the 32x16/16x32 gate** — unblocked by the item above (or by a + recipe that reaches a 32-level strip first; four source families did not). +- **deferred: 64x32/32x64/64x16/16x64 and 32x8/8x32 rect residual** — 64-point + and 1:4 rect transforms have no coefficient tables here; still refused by name. +- **deferred: film probe** — not re-run: r1 measured both ReelC extracts stopping + at lane-rectchroma's INTRA refusal ("a coded HORZ/VERT strip whose chroma + transform has no rect coefficient tables here"), which nothing in this diff + touches. +- **accepted: a rect block's luma/chroma coefficient grid is embedded in the + square grid** the downstream neighbour/deblock stamps expect (top-left + placement). The split-leaf path already hands those stamps an all-zero square + grid, so this is strictly more information than the shipping behaviour. +- **open (not this lane's shape): 1-2 attempts per recipe decode fully with + ZERO rect inter transform units and still MISMATCH ffmpeg** on 192x128 + rect-partition inter content. Proven pre-existing for the banded recipe: with + r1's square skip-context recording restored the same three attempts mismatch + identically, so it is not this round's change. Not bisected (budget). +- **DO NOT MERGE as a capability claim**: rectangular inter residual coding is + implemented and compiles, and is exercised by no green gate (class + refusal-lifted-without-a-gate). The refusal itself is still in place for every + shape but 32x16/16x32. diff --git a/lanes/inter4-r3.report.md b/lanes/inter4-r3.report.md new file mode 100644 index 00000000..9c3bbdc5 --- /dev/null +++ b/lanes/inter4-r3.report.md @@ -0,0 +1,125 @@ +# lane-inter4 r3 — the 16x16-level rectangular INTER leaf + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off r2's `d2d7327` (main `11633d7`). No rebase needed (main unchanged since r2). + +## What shipped (commit `d913935`) + +The refusal r2 named as the reach blocker is gone: `PARTITION_HORZ`/`PARTITION_VERT` +at 16x16 on an inter frame now decodes two 16x8 / 8x16 inter blocks. + +- `crates/ec-av1/src/decode.rs` (16-level partition site, ~17930): the HORZ/VERT + arms. `side = SUB` keeps every CDF / prediction-buffer decision square (the + corner-cut the 32-level rect arm already ships), `write_w`/`write_h` carry the + true 16x8 / 8x16 footprint into the mv stack, the motion-mode row, the neighbour + stamps and the rect residual path. AB / 1:4 at 16 refuse by name. +- `rect_inter_residual_supported` + `rect_inter_luma_set` / `rect_inter_chroma_set` + (decode.rs ~9020): 16x8/8x16 joins 32x16/16x32; the residual call sites pick the + TxbSet from the block's TRUE shape instead of the hard-coded 32x16 pair. +- `TxbSet::LumaRect16x8Inter` / `LumaRect16x8InterSet1` (cdf_state.rs): + `LumaRect16x8`'s coefficient tables with the INTER `tx_type` alphabet. + `av1_get_ext_tx_set_type(TX_16X8, is_inter=1, reduced)` = `EXT_TX_SET_DCT_IDTX` + reduced, `EXT_TX_SET_ALL16` otherwise (`tx_size_sqr == TX_8X8`, not TX_16X16), + both at the **TX_8X8** CDF row -- i.e. the existing `inter_tx_type_8` / + `inter_tx_type_8_set1` tables, no new CDF and no new counter-reset entry. + **r2's report was wrong here** (it predicted the 12-symbol + `default_inter_ext_tx_cdf[2][TX_8X8]`); checked against + `blockd.h:1092-1122` + `av1_num_ext_tx_set = {1,2,5,7,12,16}` in the oracle tree. +- **Defect found in shipped code (class: table narrowed to the reachable sizes):** + `eob_pt_128_luma_class1` and `eob_pt_32_chroma_class1` did not exist, so + `LumaRect16x8`/`LumaRect16x8Set1` (the INTRA rect leaf, already shipping) and + `ChromaRect8x4` fell back to the 2D `eob_pt` alphabet for `V_DCT`/`H_DCT` + units. Added from `token_cdfs.h:792-848` (plane 0 / plane 1, class index 1), + wired into all four `LumaRect16x8*` sets, `ChromaRect8x4`, and the per-frame + `reset1` list. +- **Second defect in shipped code:** `obmc_blend`'s `max_nb` closure was + `1..=4 => 2`, while libaom's `max_neighbor_obmc[] = {0,1,2,3,4,4}` indexed by + `mi_size_{wide,high}_log2` gives 0 for 1 mi and 1 for 2 mi. Only a block under + 16 px on that axis can expose it -- i.e. exactly this round's leaves. +- `size_group_wh` (decode.rs): `y_mode` (intra block in an inter frame) and the + `interintra` / `interintra_mode` rows now come from `size_group_lookup[bsize]` + of the block's TRUE footprint. The 32-level rect strips were reading the square + row (3 where libaom says 2); a 16x8 leaf would have read 2 where libaom says 1. + Deviation from charter: not requested, but it is the same defect shape and one + helper covers every caller. +- `MOTION_MODE` / `OBMC` CDFs extended from 12 to 14 packed rows with libaom's + `BLOCK_8X16` (index 4) and `BLOCK_16X8` (index 5) entries. + +## Gate — GREEN + +`a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact` +(stream.rs): 16 attempts x {2 axis-structured sources, 2 quantisers, 2 +`--enable-tx-size-search` arms, 2 motion steps} x {8-bit, 10-bit}, 192x128, 6 +frames, `--enable-rect-partitions=1 --enable-ab-partitions=0 +--enable-1to4-partitions=0 --min-partition-size=8 --max-partition-size=16 +--enable-obmc=0`, per-arm overrides LAST. Every decoded frame compared Y/U/V vs +ffmpeg; a refusal is counted, never SKIPped; an attempt carrying no 16-level rect +leaf is still required pixel-exact (`oos_mismatch == 0`). Hard asserts: a +pixel-exact attempt carrying a 16x8 leaf AND one carrying an 8x16 leaf, per bit +depth, plus at least one coded (non-skip) rectangular inter transform unit across +the two depths. + + cargo test -p ec-av1 --lib 16_level_rect_leaf -- --nocapture + +EVIDENCE: $HOME/.cache/inter4-suite-r3.log (gate line) | 32 aomenc encodes, decode + ffmpeg Y/U/V compare of every frame | 8-bit: 6 refusals, 5 pixel-exact leaf-carrying attempts, 16x8=3, 8x16=2, coded rect TUs=2, 0 mismatches; 10-bit: 2 refusals, 4 leaf-carrying attempts, 16x8=2, 8x16=3, 0 mismatches + +## Refusals + +Lifted: `"an inter partition below 16x16 other than SPLIT (16x8/8x16 rect inter +leaves are not coded yet)"`. + +Added (both in `refusal_inventory.rs`, both named, both narrow): + +- `"an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; ...)"` +- `"OBMC on a 16x8/8x16 inter leaf (blend mismatches the reference on this shape)"` + +## The OBMC residue (open, instrumented) + +With `--enable-obmc=1` and everything else identical, attempt 10 (8-bit, cq 22, +tx-size-search off) decodes all 6 frames but frame 5 has **5302 luma pixels +wrong, max |delta| 84, first at (176,0)**; frames 0-4 are exact. The same recipe +with `--enable-obmc=0` decodes 5 leaf-carrying attempts pixel-exact, and a run +with obmc/warp/interintra/masked-compound ALL off is also exact -- re-enabling +obmc alone reproduces it, so warp, interintra and masked compound are exonerated +for this shape. The blend geometry in `obmc_blend` was checked element by element +against libaom `build_obmc_inter_pred_above`/`_left` and +`av1_skip_u4x4_pred_in_obmc` and matches for these shapes; `max_neighbor_obmc` +was wrong and is fixed, but the fix left the mismatch byte-identical, so the +cause is upstream of the blend (the neighbour walk's `size`/`size_h` stamps for a +rect leaf, or `has_top_right`, whose doc still says "no rectangular partition +ever produces an inter leaf here"). Refused by name rather than shipped. + +EVIDENCE: gate run with `--enable-obmc=1` | same 16 attempts, decode + ffmpeg compare | attempt 10 frame 5: 5302 luma pixels differ, max |delta| 84; with `--enable-obmc=0`: 0 mismatches over 5 leaf-carrying attempts + +## Suite + + $HOME/.cache/inter4-suite-r3.log (systemd user unit inter4-suite-1788315557) + test result: ok. 324 passed; 0 failed; 31 ignored; finished in 412.37s + +Same 323 as r2's baseline plus this round's new gate; the one ignored addition +is still r2's own 32x16/16x32 gate. Sibling gates inside that run: every +`inter_sequence*`, `8x8_leaf_split`, `tx_select`, `superblock_level_rect_partition`, +`obmc`, `warp`, `globalmv`, `force_integer_mv`, `refusal_inventory`, +`gate_coverage` -- all green, including the ones that read the tables this round +touched (`MOTION_MODE`/`OBMC` rows, `LumaRect16x8*`, `ChromaRect8x4`). + +EVIDENCE: $HOME/.cache/inter4-suite-r3.log | ec-av1 --lib under a systemd user unit at d913935 | 324 passed / 0 failed / 31 ignored + +## Residue + +- **fix-now (r4): OBMC on a 16x8/8x16 leaf** -- named refusal today. Next step is + `has_top_right` for rect inter blocks (libaom's `xd->width < xd->height` / + `> ` / `PARTITION_VERT_A` branches are dropped in our copy) and the + `overlappable_above/left` step caps (`AOMMIN(xd->width, mi_size_wide[nb])`). +- **deferred: r2's 32x16/16x32 gate** (`..._with_a_coded_rectangular_residual_...`) + -- still `#[ignore]`d; not re-measured this round (budget). With the 16-level + leaves reachable it may now get past its first rect strip; unblocked by simply + re-running it, which r4 should do before anything else. +- **deferred: 16x16 SPLIT under this recipe** -- the gate counts `16x16 SPLITs=0` + on every attempt (aomenc picks NONE/HORZ/VERT at 16 here); the 8x8-leaf path is + gated by its own sibling test, so the count is printed, not asserted. +- **accepted: the 10-bit arm proves no residual** -- every 10-bit rect leaf in + this recipe is `skip` at cq 34/22, and cq 30/26 or 24/12 stops reaching a rect + leaf at all (measured). The residual half is asserted across both depths. +- **accepted: `_size_group` is now a dead parameter** of `decode_inter_block` + (superseded by `size_group_wh`), kept rather than editing twenty call sites. diff --git a/lanes/inter4-r4.report.md b/lanes/inter4-r4.report.md new file mode 100644 index 00000000..ee12df72 --- /dev/null +++ b/lanes/inter4-r4.report.md @@ -0,0 +1,142 @@ +# lane-inter4 r4 — OBMC on a 16x8/8x16 inter leaf (refusal lifted, gated) + +Branch `lane-inter4`, worktree `/home/user/Documents/Code/Rust/edith_codecs-inter4`, +off r3's `96847a3`, with `lane-interbis` (`8a6bede`, `build_motion_field`'s compound +slot walk) merged FIRST as chartered. + +## TASK 1 — r2's ignored 32x16/16x32 gate: re-measured, STILL RED, blocker moved + + cargo test -p ec-av1 --lib coded_rectangular_residual -- --ignored --nocapture + +`a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact` +still cannot prove itself: over its 16 8-bit attempts, **12 named refusals** — 10 of +them `"an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder +does not code yet"` and 2 `"an inter 16x16-level AB or 1:4 partition ..."` — and the +other 4 attempts decode with **zero** rect inter residual (`tu=0`, `split=0`, 0 +mismatches). So the 16-level leaf landing in r3 did NOT unblock it: what stops these +streams now is rectangular *intra* prediction, another lane's refusal. Kept `#[ignore]`, +with the reason string replaced by that measurement (stream.rs:4902). + +EVIDENCE: $HOME/.cache/inter4-t1.log | 16 aomenc encodes, decode + counter read | 12 named refusals (10 intra-rect-strip, 2 inter AB/1:4), 4 attempts with tu=0/split=0, 0 mismatches + +## TASK 2 — the OBMC residue: no defect left; refusal lifted + +r3 refused `"OBMC on a 16x8/8x16 inter leaf (blend mismatches the reference on this +shape)"` off a measured 5302-luma-pixel mismatch (attempt 10, 8-bit, cq 22, frame 5). +Re-measured on THIS tree before touching any code: + +- Rebuilt that exact stream from the gate's attempt-10 recipe with `--enable-obmc=1` + (`scratchpad/o10.obu`, md5 `b643a93a8db45e2a1b89b2d777147ee3`, 828 B). +- Added an `EC_OBMC` rung to the oracle `aomdec` + (`dec_build_prediction_by_above_pred` / `_left_pred`, printing the block, the + neighbour's rel position, `op_mi_size`, mv, ref, bsize, filter) and the matching + rung to our `obmc_blend`, then compared. + +Both decoders emit **exactly 9 OBMC neighbour invocations**, in the same order, with +identical block shape, `off4`/`rel`, `span4`/`op_mi_size`, neighbour mv, ref frame and +filter — including the three on `wh=(8x16)` leaves. And every one of the six +`EC_AV1_PREFILT_DUMP` frames is **byte-identical** between our decoder and aomdec +(luma diff 0 on f0..f5). There is nothing left to fix on this shape: the mismatch r3 +saw is gone. The only decode-path change between r3's measurement and this one is the +lane-interbis merge (temporal MV candidates); not bisected further. + +EVIDENCE: scratchpad/{ours.obmc,ref.obmc,ours.yuv.f0-5,ref.yuv.f0-5} | EC_OBMC + EC_AV1_PREFILT_DUMP on o10.obu, ours (release decode_probe) vs instrumented aomdec | 9 vs 9 identical neighbour lines; per-frame luma diff 0/0/0/0/0/0 + +### What shipped + +- `crates/ec-av1/src/decode.rs` (`obmc_blend`, ~12843): the `(16,8)|(8,16)` refusal + deleted; in its place the new `OBMC_RECT_LEAF_HITS` counter (+ `obmc_rect_leaf_hits()` + at ~1355) that the gate reads. +- `crates/ec-av1/src/refusal_inventory.rs`: the OBMC-rect-leaf string removed. +- `crates/ec-av1/src/stream.rs` (`..._with_a_16_level_rect_leaf_...`, ~5090): the sweep + runs **32 attempts** now — the same 16 (2 sources x 2 quantisers x 2 tx-size-search + arms x 2 motion steps) with `--enable-obmc=0`, then repeated with `--enable-obmc=1` + as the LAST flag. New hard assert per bit depth: `obmc_leaf_proved > 0`. +- `crates/ec-av1/src/stream.rs` ~1948: the hidden-frames gate's `--enable-obmc=0` + comment no longer cites a refusal that does not exist. + +### Gate — GREEN + + cargo test -p ec-av1 --lib 16_level_rect_leaf -- --nocapture + +- 8-bit: 15 named refusals, 9 pixel-exact leaf-carrying attempts (16x8=5, 8x16=4), + whole-block rect TUs=4, **OBMC blends on a rect leaf=10**, 8 attempts carried none + (0 mismatched). +- 10-bit: 4 named refusals, 8 pixel-exact leaf-carrying attempts (16x8=4, 8x16=6), + **OBMC blends on a rect leaf=4**, 20 carried none (0 mismatched). + +EVIDENCE: $HOME/.cache/inter4-g4.log | 64 aomenc encodes (32 attempts x 2 depths), every decoded frame Y/U/V vs ffmpeg | test result: ok. 1 passed; 0 failed; OBMC-on-rect-leaf blends 10 (8-bit) / 4 (10-bit), 0 mismatches + +## Verifier findings folded in (r4, after the OBMC commit) + +1. **`size_group_wh` was wrong for a 4-px side** (decode.rs ~9126): libaom + `size_group_lookup[BLOCK_SIZES_ALL]` (`common_data.h:60`) is **0** for + BLOCK_4X4/4X8/8X4/4X16/16X4, and our `0..=8 => 1` row gave those group 1 -- + the `y_mode` / `interintra` / `interintra_mode` CDF row of every sub-8 leaf. + Fixed, and pinned by a new unit test `size_group_wh_matches_libaom_size_group_lookup` + that enumerates all 22 `BLOCK_SIZES_ALL` entries against the transcribed table + (class enumerate-the-table-domain). + + cargo test -p ec-av1 --lib size_group_wh_matches -- --nocapture + +2. **rect var-tx SPLIT and the 10-bit coded rect TU are shipped unexercised.** + Swept cq {8,12,16,22} x both source axes x both depths with tx-size-search on, + reading `decode_probe`'s new `rect_inter: tu=.. txsplit=.. obmc_leaf=..` line: + `txsplit=0` in every single decoding attempt, and every 10-bit rect leaf is + `skip` (`tu=0`) at every cq that decodes at all. Below cq 22 the attempts stop + at another lane's refusal -- mostly `"a HORZ/VERT intra strip below 16x16 with + a split transform (per-unit rect prediction is not ported)"`, plus the sub-16 + `HORZ_A/HORZ_B/VERT_A` and 32-level 1:4 ones. Deviation from the verifier's + ask, stated: I did NOT add an `#[ignore]`d pin -- an ignored test that runs + nothing carries the same information as the measurement now written into the + gate's own comment (stream.rs ~5097) and into the residue below, at less code. + The asserts stay where the feature does fire (8-bit `tu_total > 0`). + +3. `stream.rs` "aomenc keeps the last occurrence of a repeated `--enable-*` flag" + is CORRECT (class aomenc-first-flag-wins is about `--enable-*` repeats resolving + to the last one, and it is what the r4 obmc arm relies on) -- left unchanged. + +4. `cdf.rs` doc slip fixed: `EOB_PT_128_CHROMA_CLASS1_Q0` had lost its doc comment + to the `EOB_PT_128_LUMA_CLASS1_Q0` block added in r3; moved back. + +EVIDENCE: sweep output in this round's transcript | 16 aomenc encodes (cq 8/12/16/22 x 2 axes x 8/10-bit) decoded through release decode_probe | txsplit=0 in all 7 decoding attempts, 10-bit tu=0 in all 4, 8-bit cq22 tu=1 txsplit=0 obmc_leaf=1 + +## Refusals + +Lifted: `"OBMC on a 16x8/8x16 inter leaf (blend mismatches the reference on this shape)"`. +None added. + +## Suite + + $HOME/.cache/inter4-suite-r4.log + + test result: ok. 326 passed; 0 failed; 31 ignored; finished in 776.14s + +r3's 324 + the lane-interbis gate + this round's `size_group_wh` unit test; the 31 +ignored are unchanged (still including r2's 32x16/16x32 gate). Every sibling ran in +it: `obmc*`, `16_level_rect_leaf`, `superblock_level_rect_partition`, +`inter_sequence*`, `temporal_mv_candidates`, `refusal_inventory`, `gate_coverage`. + +EVIDENCE: $HOME/.cache/inter4-suite-r4.log | ec-av1 --lib under a systemd user unit at b0588e4 + this report | 326 passed / 0 failed / 31 ignored + +## Film + +`scratchpad/hg-head.obu` through the release `decode_probe` on this lane still stops at +`unsupported: AV1 tile (filter intra on a HORZ/VERT strip (this decoder predicts +square-only))` — an intra refusal owned by another lane, unchanged by this round. + +EVIDENCE: scratchpad/hg-head.obu | release decode_probe under a 6G scope | REFUSED: filter intra on a HORZ/VERT strip + +## Residue + +- deferred: r2's 32x16/16x32 rect-residual gate — still `#[ignore]`d — unblocked by + rectangular INTRA prediction (`an intra-coded HORZ/VERT strip ...`) landing, not by + anything in this lane. +- accepted: which change fixed r3's OBMC mismatch is not bisected (interbis merge is the + only candidate); the shape is now proven exact against an instrumented aomdec, so the + question is archaeology, not a defect. +- deferred: the rect var-tx SPLIT path and a coded 10-bit rect TU are unexercised -- + unblocked by the sub-16 intra-rect-strip refusal landing (every lower-cq attempt + stops there before a rect inter leaf can carry a split tree). +- accepted: `16x16 SPLITs=0` under this recipe (aomenc picks NONE/HORZ/VERT at 16); + covered by the 8x8-leaf sibling gate. diff --git a/lanes/interbis-r1.report.md b/lanes/interbis-r1.report.md new file mode 100644 index 00000000..5d3293d0 --- /dev/null +++ b/lanes/interbis-r1.report.md @@ -0,0 +1,129 @@ +# lane-interbis r1 — the "decodes fully, still mismatches" inter defect + +Branch `lane-interbis`, worktree `edith_codecs-interbis`, off lane-inter4 `d2d7327`. +No rebase (main unchanged since that base). + +## STEP 1 — reproduced and pinned + +The rect gate's 8-bit **attempt 1** is the one that decodes fully and mismatches: +192x128, 6 frames @25, `geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)'`, cq 34, +`--enable-tx-size-search=1`, `--min/max-partition-size=16/32`, cpu-used=0, lag 0. +Regenerated twice, byte-identical: +`fa70b7f68d311e577e3d14a86574909e6e58cac817b5a7fae04341c41ff50260` +(script `$HOME/.cache/interbis/gen.sh`; 10-bit twin +`67cad9bd5341db897de8a5308faecaedb1b0df761e4f315f1817156d124caef7`). + +Decode order == display order (no hidden frames; `--lag-in-frames=0`). +Frames 0..4 exact; **frame 5** luma only, 646 px, bbox x160-191 y93-127, max delta 39. +`EC_AV1_PREFILT_DUMP` (ours) vs the same rung from the instrumented aomdec: +frames 0-4 byte-identical, frame 5 differs in 640 luma px at x160-191 y96-127 — +i.e. **reconstruction**, not deblock/CDEF/LR, and exactly one 32x32 block: +mi (row 24, col 40), the frame's last block. + +EVIDENCE: $HOME/.cache/interbis/{o_pre.f5,a_pre.f5} | EC_AV1_PREFILT_DUMP ours vs aomdec, per-frame byte diff | frames 0-4 identical, frame 5 640 luma px wrong in the single 32x32 block at mi(24,40) + +## STEP 2 — first divergent element + +Entropy is **exact**: the msac range ladder agrees at that block's entry +(`EC_MODE ... rng=37852` both) and at the end of its mode read +(`rng=59818` both). Both decoders read mode 13 (NEARESTMV), ref0=2 (LAST2), +stack size 3. The **VALUE** differs: + + ours EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,72) + aomdec EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,-230) + +New `EC_STACK` rung (added to both decoders) shows entries 1 and 2 identical +(`(0,24) w=2`, `(0,-785) w=2`, the extra-search neighbours) and entry 0 — +the temporal (MFMV) candidate — wrong: ours `(0,72) w=32`, aomdec `(0,-230) w=16`. + +New `EC_TPL` rung (per `add_tpl_ref_mv` probe, both decoders) isolates it to the +projected motion field itself: over the 16 probes of that block, aomdec reads +`INVALID` at blk_col 0/2 and `mfmv0=(0,-230) rfo=3` at blk_col 4/6; ours reads +`mfmv0=(0,24) rfo=1` at all 16. `(0,24)*3/1 = (0,72)` — our wrong stored pair +projected exactly to the wrong candidate. + +EVIDENCE: $HOME/.cache/interbis/{o_tpl.txt,a_tpl.txt} | EC_TRACE_MODE + EC_TRACE_TPL on both decoders, block mi(24,40) of frame 5 | ours mfmv0=(0,24) rfo=1 x16 vs aomdec INVALID x8 + (0,-230) rfo=3 x8; stack entry 0 (0,72) vs (0,-230) + +## Root cause (decode.rs `build_motion_field`, spec 7.19 / libaom `av1_copy_frame_mvs`) + +Our per-frame saved motion field stored **`ref_frame[0]`/`mv[0]` of every inter +block**. libaom walks **both** reference slots and the **last qualifying one +wins**, skipping a slot when + +* `cm->ref_frame_side[ref]` is non-zero — the reference's OrderHint is ahead of + (or equal to) this frame's (`av1_calculate_ref_frame_side`), or +* `|mv| > REFMVS_LIMIT` (`(1<<12)-1`). + +Every compound block in this stream is `LAST + GOLDEN` (both past), so libaom +stores GOLDEN's mv with `ref_frame_offset = 3` where we stored LAST's with +offset 1 — a wrong (mv, distance) pair in every compound block's 8x8 cell, which +the next frame's temporal candidate then projects with the wrong reference +distance. Class name: **saved-field-keeps-slot-0** — a per-frame/DPB *summary* +of a multi-slot field must replay the reference's own slot walk (order + skips), +not keep slot 0. (Sibling of `neighbour-votes-all-its-fields`: there the +consumer voted only one slot, here the producer stores only one.) + +Fix: `crates/ec-av1/src/decode.rs:1728-1800` (`build_motion_field` now takes +`order_hint_bits`, walks both slots last-wins, applies the side and +`REFMVS_LIMIT` skips); call site `decode.rs:19040`. + +## Sweep + +`build_motion_field` is the only writer of `MotionField`/`SavedMv` +(`grep -rn "SavedMv\|MotionField" crates/ec-av1/src`); the mv-stack neighbour +maps already carry both slots (`MiInfo::ref_frame1`/`mv1`), and +`motion_field_projection`/`setup_motion_field` were re-read line-for-line +against `mvref_common.c` this round and match (one known, unreached gap noted +below). + +## Gate — GREEN, and it binds + +`a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact` +(`crates/ec-av1/src/stream.rs`, next to the rect gate): the pinned recipe above, +2 tx-size-search arms x {8-bit, 10-bit}, every fully decoded attempt compared +Y/U/V against ffmpeg, refusals counted (never SKIPped), and `decode::tmv_hits()` +asserted > 0 per depth. + + cargo test -p ec-av1 --lib temporal_mv_candidates -- --nocapture + 8-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 66 + 10-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 67 + test result: ok. 1 passed; 0 failed + +EVIDENCE: $HOME/.cache/interbis-tmvgate.log | cargo test -p ec-av1 --lib temporal_mv_candidates | 8-bit + 10-bit pixel-exact, tmv counter 66/67 + +Negative control (gate binds): with the store put back to first-slot-wins the +same gate fails at `frame 5 luma vs ffmpeg (attempt 1, 8-bit)`. + +EVIDENCE: $HOME/.cache/interbis-tmvgate-neg.log | one-line revert to `if saved.is_none()` then re-run the gate | FAILED, frame 5 luma, restored immediately after + +## Instruments added (env-gated, both decoders) + +- ours: `EC_MODE_VAL` + `EC_STACK` on the single-ref path of `decode_inter_block` + (byte-format-identical to the oracle's rung), `EC_TPL` per `add_tpl_ref_mv` probe. +- oracle (`~/.cache/aom-oracle/src`): `EC_STACK` (stack dump at `EC_MODE_VAL`) and + `EC_TPL` (per probe, incl. the `INVALID_MV` arm); `ninja aomdec` rebuilt. + +## Residue + +- **accepted: `motion_field_projection` does not check the source frame's + frame_type.** libaom returns 0 for a KEY/INTRA_ONLY source; here an intra + frame's saved field has no cells set, so the projection is inert — but its + *return value* (which feeds `ref_stamp`) can differ. Unreached on every stream + swept; fix-now if a future stream shows a `ref_stamp` divergence. +- **deferred: the rect inter residual gate** stays `#[ignore]`d (lane-inter4's + own residue, unblocked by 16x8/8x16 rect inter leaves); its + `out_of_scope_mismatch` assert is what surfaced this defect and is now + satisfiable on the 8-bit arm. +- **deferred: film probe** — this diff lifts no refusal; both films still stop at + lane-rectchroma's intra-rect-strip refusal. + +## Suite + + $HOME/.cache/interbis-suite.log (systemd-run unit, MemoryMax=10G) + test result: ok. 324 passed; 0 failed; 31 ignored; finished in 443.08s + +323 (lane-inter4 r2 baseline) + this round's new gate. Siblings inside that run: +inter_sequence*, obmc, warp, globalmv, compound_*, altref/hidden-frame, +tx_select, refusal_inventory, gate_coverage — all green. + +EVIDENCE: $HOME/.cache/interbis-suite.log | ec-av1 --lib at 0527911 | 324 passed / 0 failed / 31 ignored diff --git a/lanes/oddh-r1.report.md b/lanes/oddh-r1.report.md new file mode 100644 index 00000000..e3913c71 --- /dev/null +++ b/lanes/oddh-r1.report.md @@ -0,0 +1,76 @@ +# lane-oddh r1 — frames whose height/width is 8 mod 16 + +Branch `lane-oddh` off main `b1d8457`. Target: the user's ReelB film shape +(3840x1608, `1608 % 16 == 8`), where every inter attempt derailed. + +## What the round established (measured, not reasoned) + +1. **The charter's premise is stale in its blame, right in its shape.** The refusal + `"a non-DC chroma mode on an 8x8 inter-frame leaf"` is NOT what odd-height frames + stop at once lane-golomb's edge-partition fix is present. Cherry-picking + `eacd7fd` (clean, no conflicts) moves 192x136 to the same refusal its + *even-height control* 192x128 hits, i.e. that one is width/content-related, not + odd-height (see 4). + +2. **Minimal repro is 64x72, not 192x136.** With the standard inter-gate recipe + (`--enable-rect-partitions=0 --min/max-partition-size=8/16`, mandelbrot, cq 40): + - `64x64` decodes 4/4 frames pixel-exact (control), + - `64x72` (bottom band 8 px) stopped at the key-frame 16-level edge refusal, + - `72x64` (right band 8 px) stops in the inter tile path. + +3. **The real blocker underneath is a first-symbol desync of the KEY tile at + height 72.** Not an edge-band defect at all: the *first* partition symbol of the + frame diverges. + `EVIDENCE: /tmp/.../scratchpad/k-64x72.obu (667 B, key frame only, aomenc cq40) | EC_AV1_TRACE=1 decode_probe vs EC_TRACE=1 aomdec | first element mi=(0,0) bsize=BLOCK_64X64 ctx=0: aomdec value=3 (PARTITION_SPLIT, tell=1 rng=32768), ours value=9` + `EVIDENCE: /tmp/.../scratchpad/k-64x72.{ours,aom,ref}.y | aomdec --rawvideo + ffmpeg rawvideo vs our Y dump | aomdec == ffmpeg byte-for-byte; ours differs in 4583 of 4608 Y samples (whole frame), while the 64x64 control differs in 0` + Our tile payload starts at file offset 20 in both the 64x64 and the 64x72 stream + (`key_tile_bytes len=543`/`647`, file sizes 563/667), and `base_q_idx=160`, + `mi_cols=16`, `mi_rows=18` all parse correctly, so the header field values are + right; the divergence is in the very first symbol read off those bytes. + **Not diagnosed further — this is the handoff item.** Ruled out by reading the + source: `sb_rows`/`sb_cols` (`sequence.rs:409-422`, 18 -> 2 correct) and the + uniform-spacing tile-info loops (`frame.rs:1296-1334`, both increment loops match + spec 5.9.15, so the extra `increment_tile_rows_log2` bit that height 72 introduces + IS consumed). + +4. Pre-existing, unrelated to odd height: `192x128` and `192x136` both stop at + `"a 1:4 partition below 16x16"` with `--enable-1to4-partitions=0` on the command + line — a same-shaped refusal-from-own-desync at width 192, present on the control. + +## Code changed (all in this worktree, unproven end to end) + +- cherry-pick `eacd7fd` (lane-golomb) — the frame-edge partition bit at 6 sites in + both tile paths, plus its film key-frame fixture/gate. Clean merge. +- `crates/ec-av1/src/decode.rs:11371` — the key-frame 16-level frame-edge + `PARTITION_HORZ`/`VERT` now decodes its single visible 16x8 / 8x16 strip through + `decode_leaf_rect` instead of refusing (removes that refusal string; entry dropped + from `refusal_inventory.rs`). +- `crates/ec-av1/src/decode.rs` (inter tile path, superblock level and 16-level) — + the same edge half-strip as one 64x32 / 32x64 resp. 16x8 / 8x16 inter block + (`write_w`/`write_h`, square CDF/size-class corner-cut, exactly the accepted + corner-cut of the 32-level rect arm at `decode.rs:18448`). Interior rect + partitions still refuse by name. +- `decode.rs` — new counter `edge_rect_strip_hits()` (blocks decoded inside the 8px + edge band), for the gate a successor must write. + +`corner-cut:` the two inter edge arms read square CDFs / size classes for a +rectangular block (ceiling: coefficient and mode syntax for TX_64X32/TX_16X8 inter is +not modelled; upgrade path = the same treatment the 32-level rect arm eventually gets). + +## Verification status — honest + +- NO gate was added and NO refusal claim is proven: every stream that reaches the new + arms is desynced before them (finding 3), so a pixel compare would measure the + desync, not the arm. Writing + `a_real_aomenc_inter_sequence_with_an_8px_tall_edge_row_decodes_pixel_exact` on top + of a first-symbol desync would have produced a vacuous or a permanently-red gate. +- Suite: see `$HOME/.cache/oddh-suite.log` (run as a systemd unit, result quoted in + the handoff message). + +## Disposition + +- fix-now (next round, r2): the 64x72 key-tile first-symbol desync. It is the root + blocker; the edge arms above are dead code until it is fixed. +- deferred(the desync above): the 8px-edge-band gate + the refusal lift claim. +- deferred(width-192 defect, separate lane): the `"1:4 partition below 16x16"` stop + that both 192x128 and 192x136 share. diff --git a/lanes/oddh-r2.report.md b/lanes/oddh-r2.report.md new file mode 100644 index 00000000..6d938597 --- /dev/null +++ b/lanes/oddh-r2.report.md @@ -0,0 +1,97 @@ +# lane-oddh r2 — the 64x72 first-symbol desync is 128x128 superblocks + +## Root cause (byte-level proof, not inference) + +r1's pinned defect — a 64x72 aomenc KEY frame desyncing at the FIRST symbol +(aomdec value=3, ours 9) — is **not** an odd-height defect and **not** a header +parse defect. The stream's sequence header codes `use_128x128_superblock = 1`, +and this decoder is 64x64-superblock only (`SB_MI = 16`, no BLOCK_128X128 +partition read anywhere; `decode.rs` never reads `use_128x128_superblock`). + +libaom picks it: `av1_select_sb_size` (encoder_utils.c:1000-1003) returns +BLOCK_64X64 only when `speed >= 1 && min(w,h) <= 480`. r1's fixture was +encoded at `--cpu-used=0`, so speed 0 fell through to BLOCK_128X128. + +What the two decoders do with the same first byte: + +| | libaom (aomdec) | ours | +|---|---|---| +| first block | BLOCK_128X128 at mi (0,0): `has_cols = 0+16 < 16` false, `has_rows = 16 < 18` true | BLOCK_64X64 at mi (0,0) | +| symbol read | gathered 2-symbol partition (`partition_gather_horz_alike`) | 10-symbol `partition_cdf[12]` | +| value | 3 = PARTITION_SPLIT | 9 = PARTITION_VERT_4 | + +Ruled out first, by hand, field by field against spec 5.9.2 for this stream: +the uncompressed header is **49 bits** (3 before tile_info, 1 tile_info, 12 +quant, 1 seg, 1 delta, 29 loop filter — levels 36/38/21/19, sharpness 0, +mode_ref_delta_enabled 1, update 0 — 0 cdef, 0 lr, tx_mode 1, reduced_tx_set 1), +byte-aligning tile data to file offset 20. Our parser reads exactly the same 49 +bits. Two independent msac implementations (ours and a from-spec python one) +read symbol 9 from offset 20 with `partition_cdf[12]`, so the bytes and the +table are both ours-correct — only the *block size* is wrong. + +EVIDENCE: hand-parsed header bits + msac offset probe (both diagnostics reverted after use) | parsed k-64x72.obu, printed per-section bit positions (3/4/16/17/18/47/47/47/49), then decoded the first partition symbol at file offsets 16..24 with `PARTITION_W64[0]` in ours and in a from-spec python msac | both give 9 at offset 20 (aomdec: 3), i.e. same bytes, same table, different alphabet + +## What changed + +- `crates/ec-av1/src/stream.rs:509` — `decode_stream` now REFUSES a sequence + with `use_128x128_superblock` **on a frame larger than 64x64** by name + instead of silently decoding it as 64x64 superblocks (wrong pixels, whole + frame). The scoping is measured, not reasoned: a blanket refusal red-lined + 29 previously pixel-exact gates (29 failed / 318 passed), because at + <= 64x64 a 128x128 superblock decodes identically -- mi (0,0) has neither + `has_rows` nor `has_cols`, so BLOCK_128X128 is a forced SPLIT that reads no + symbol and only one 64x64 child is in frame. Every sibling inter gate at + 64x64 `--cpu-used=0` is exactly that case. +- `crates/ec-av1/src/stream.rs` — new gate + `a_real_aomenc_128x128_superblock_stream_is_refused_by_name`: real aomenc, + 64x72, `--cpu-used=0 --sb-size=128`; asserts the stream's sequence header + really codes `use_128x128_superblock` (knob-reached-the-tool) and then that + the refusal fires. +- `crates/ec-av1/src/stream.rs` — `a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact` + extended with the odd ladder 64x72, 72x64, 64x136, 136x64, 192x136; floor + raised 70 -> 120 pixel-exact attempts. +- `crates/ec-av1/src/refusal_inventory.rs` — the new refusal string pinned. +- `crates/ec-av1/src/stream.rs` — `a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact` + written and left `#[ignore]`d with its measured reason (below). + +## The size ladder (the table the charter asked for) + +`cargo test -p ec-av1 --lib -- a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact`, +10 seeds each, real aomenc at `--cpu-used=4` (= 64x64 superblocks), 8-bit: + +| size | pixel-exact | refused | +|---|---|---| +| 8x8 | 0/10 | 10 (16x16 rect transform, pre-existing) | +| 16x16, 32x32, 16x32, 32x16, 64x64, 48x48, 24x24 | 10/10 each | 0 | +| **64x72, 72x64, 64x136, 136x64, 192x136** | **10/10 each** | 0 | + +EVIDENCE: $HOME/.cache/oddh-suite-r2.log + the run above | 13 sizes x 10 seeds, aomenc -> our decoder -> ffmpeg sample compare | 120 pixel-exact attempts, 0 mismatches, "tiny frame sweep: 120 pixel-exact attempts" + +So odd height/width at 64x64 superblocks is **clean**, including r1's +frame-edge half-strip code on the KEY path. + +## Open / deferred + +- deferred: 128x128 superblock decode — refused by name, not implemented — the + partition tree, `SB_MI`, CDEF/LR/deblock grids and the loop-filter unit size + are all 64-only; that is a lane, not a fix. Unblocked by: a lane that makes + `SB_MI` a parameter and adds the BLOCK_128X128 partition read. +- deferred: the INTER frame-edge half-strip arms r1 added are still UNGATED. + Measured this round at 192x160 (last superblock row 32 tall, so the forced + gathered edge symbol is a 64x32): with `--enable-rect-partitions=0` both bit + depths decode 6 frames **pixel-exact** but `edge_rect_strip_hits = 0` (the + encoder answers the forced symbol SPLIT every time); with rect ON the run + stops at other lanes' gaps — cq 40 "a non-skip rectangular (HORZ/VERT/HORZ_B) + strip needs rectangular residual coding", cq 62 "an INTER 32x32 partition + type this decoder does not code (value=8/9)", min-partition 16 "a HORZ/VERT + intra strip below 16x16 with a split transform". Unblocked by: the rect + inter-residual lane. + +## Suite + +`cargo test -p ec-av1 --lib` (systemd unit, log `$HOME/.cache/oddh-suite-r2.log`): +the blanket-refusal run was 318 passed / 29 failed / 32 ignored, every failure +the new refusal firing on a 64x64 `--cpu-used=0` stream. After scoping the +refusal to frames larger than 64x64, the 7-gate subset covering all of them +plus the three new/extended gates is green (7 passed, 0 failed); the full-suite +rerun on the scoped tree is launched to the same log and is r3's first read. diff --git a/lanes/refstamp-r1.report.md b/lanes/refstamp-r1.report.md new file mode 100644 index 00000000..3fb91685 --- /dev/null +++ b/lanes/refstamp-r1.report.md @@ -0,0 +1,84 @@ +# lane-refstamp r1 — `ref_stamp` vs forward key frames, `av1_copy_frame_mvs` clear, scripted MFMV rungs + +Base: lane-inter4 `49af875` (contains lane-interbis's motion-field fix). Commits `34ae093`, `b03a4d2`. + +## What changed + +- `crates/ec-av1/src/motion_field.rs:270` — `MotionField` gains `is_intra` (the DPB slot's + `frame_type`); `motion_field_projection` now opens with libaom's own first `return 0` + (`start_frame_buf->frame_type == KEY_FRAME || INTRA_ONLY_FRAME`) before the frame-size test. + Previously a forward reference holding a key frame was "projected" (empty field) and reported + success, so it consumed the `ref_stamp` slot that ALTREF/LAST2 should have had. +- `crates/ec-av1/src/motion_field.rs:335` — `setup_motion_field` ports + `if (!order_hint_info->enable_order_hint) return;` (empty `TplField` when `order_hint_bits == 0`) + and counts the frames that take the intra-forward-ref `ref_stamp` path + (`refstamp_intra_frames() -> (>=1, >=2)`). +- `crates/ec-av1/src/motion_field.rs:296` — `MotionField::set` now takes `Option`; + `crates/ec-av1/src/decode.rs:1772` `build_motion_field` ports `av1_copy_frame_mvs`'s leading + CLEAR (`mv->ref_frame = NONE_FRAME; mv->mv.as_int = 0;`), which runs for every block of an + inter frame — intra blocks, and inter blocks whose every slot is other-side/over-REFMVS_LIMIT, + now wipe their 8x8 cells instead of `continue`ing. Latent until sub-8x8 leaves (only they share + a cell), ported now. +- `crates/ec-av1/src/stream.rs:614` — the key-frame DPB slot is constructed with `is_intra: true`. +- `crates/ec-av1/src/gate_coverage.rs:221,272` — the 10-bit `enable-ref-frame-mvs` / + `enable-fwd-kf` coverage holes are closed by the new gate; entries deleted, 8-bit reasons reworded. +- `scripts/instrument-aom-oracle.sh` — new **rung 14**: `EC_TRACE_TPL` (`EC_TPL ... mfmv0=(..,..) + rfo=..` / `INVALID` in `add_tpl_ref_mv`) and the per-entry `EC_STACK` dump under rung 4's + `EC_TRACE_MODE`. Both existed only as hand edits in `~/.cache/aom-oracle/src` (lane-interbis) + and would have vanished on the next oracle rebuild. + +## Gate + +`a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact` +(`crates/ec-av1/src/stream.rs:4900`): 192x128, 24 frames of translating structure, +`--enable-fwd-kf=1 --fwd-kf-dist=8 --lag-in-frames=16 --auto-alt-ref=1 --arnr-maxframes=0 +--enable-ref-frame-mvs=1 --enable-order-hint=1` (overrides last, aomenc keeps the last flag), +2 attempts (cq 34 / 45), 8-bit AND 10-bit, every decoded frame — hidden alt-refs included — +compared to the oracle IN DECODE ORDER via `decode_all_frames_vs_oracle`. A decode error is only +tolerated as a named `unsupported` refusal and is counted, never SKIPped; three hard asserts +(`compared > 0`, temporal candidates `> 0`, key/intra-forward-ref frames `> 0`). + +Run: `EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-refstamp +cargo test -p ec-av1 --lib forward_keyframes -- --nocapture` + +EVIDENCE: /home/user/.cache/refstamp-suite.log | aomenc fwd-kf recipe, 2 attempts x 2 depths, decode-order compare incl. hidden frames | 8-bit: 26 frames (2 hidden) pixel-exact, temporal candidates=524, key/intra-forward-ref frames=6; 10-bit: 26 frames (2 hidden) pixel-exact, candidates=514, frames=6; attempt 0 (cq 34) refuses by name ("an intra-coded HORZ/VERT strip needs rectangular intra prediction") + +MUTATION: removing the `if start.is_intra { return false; }` early return (pre-fix behaviour) makes +the gate FAIL, not skip: +EVIDENCE: /tmp/ec-av1-a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact-8bit-attempt1-703199/in.obu | mutate motion_field.rs early return to a no-op, rerun the gate | "decode-order frame 15 of 26 (24 shown, 2 hidden) differs from the oracle at byte 6686 (ours 179 vs 178), 160 bytes differ" + +Rung 14 verification: applied to a scratch tree (pristine `mvref_common.c` from the oracle's git +HEAD + a rung-13-state `decodemv.c`) and byte-compared to the live hand-patched oracle sources. +EVIDENCE: scratchpad/rung14/av1/{common/mvref_common.c,decoder/decodemv.c} | `SRC= bash rung14.sh`, then `diff` vs ~/.cache/aom-oracle/src | both files IDENTICAL to the live oracle; re-running on the live oracle prints "already applied (no-op)" twice (idempotent); `bash -n` clean + +## Refusals + +None lifted this round (no refusal guarded this path); `refusal_inventory` / `gate_coverage` +unchanged and green in the suite below. + +## Suite + +`cargo test -p ec-av1 --lib` (systemd unit, MemoryMax=10G): **326 passed, 0 failed, 31 ignored** +(`$HOME/.cache/refstamp-suite2.log`). The first run on the same tree failed exactly 2 tests -- +`gate_coverage::never_exercised_10bit_matches_the_gate_recipes` and `never_on_10bit_...` -- because +the new gate CLOSED two 10-bit coverage holes (`enable-ref-frame-mvs`, `enable-fwd-kf`); commit +`00d37d3` deletes those entries and reworded the two 8-bit reasons (`is_ten_bit` classifies a +dual-depth gate as 10-bit only, so the 8-bit lists keep the tools with an accurate reason). +Siblings all green in that run: `..._temporal_mv_candidates_...`, `..._altref_sequence_hidden_frames_...`, +every `..._inter_sequence_...`, `..._obmc_...`, `..._warped_motion_...`, `refusal_inventory` (3/3), +`gate_coverage` (9/9). + +EVIDENCE: /home/user/.cache/refstamp-suite2.log | systemd-run unit, cargo test -p ec-av1 --lib -j3 | "test result: ok. 326 passed; 0 failed; 31 ignored" in 379 s + +## Residue + +- The gate's frames all have exactly ONE key/intra forward reference (`two or more: 0`) — the + charter's ">=2 forward refs are key/intra" phrasing is not what `--enable-fwd-kf` produces at + `--fwd-kf-dist=8`; one is already sufficient to move `ref_stamp` (it changes whether LAST2 and + ALTREF are projected), and the mutation proves the gate is sensitive to exactly that. + accepted. +- `--enable-fwd-kf=1` at cq 34 still stops at the intra HORZ/VERT rect-strip refusal (attempt 0); + cq 45 decodes fully. deferred(lane owning rectangular intra prediction) — not this lane's path. +- The `av1_copy_frame_mvs` clear is unexercised by any gate today (needs a sub-8x8 inter leaf, + which still refuses by name). deferred(the sub8 lane's 4x4 inter leaves) — ported now because + the same block that lifts that refusal would otherwise silently inherit the old behaviour. diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh index 23f715e9..ec513d84 100755 --- a/scripts/instrument-aom-oracle.sh +++ b/scripts/instrument-aom-oracle.sh @@ -761,3 +761,74 @@ s = s.replace(anchor, anchor + probe, 1) open(path, "w").write(s) print("decodemv rung 13 (EC_MODE_MV + EC_MODE_VAL stack=) instrumented") PYMV + +# --- rung 14: temporal-MV (MFMV) ground truth (lane-interbis, scripted by ---- +# --- lane-refstamp r1) ----------------------------------------------------- +# lane-interbis patched the live oracle tree BY HAND for its motion-field hunt, +# so these two probes lived only in ~/.cache/aom-oracle/src and a rebuild from +# this script would have dropped them (class: instrument that lives only in a +# build tree -- same reason rung 13 exists). +# * EC_TRACE_TPL=1 -> "EC_TPL mi_row=.. mi_col=.. blk=(..,..) mfmv0=(..,..) +# rfo=.." (or ".. INVALID") for every temporal candidate `add_tpl_ref_mv` +# probes -- the reference's own projected motion field, cell by cell, to +# compare against ours (EC_TRACE_TPL on our side). +# * the resolved MV STACK itself, one "EC_STACK mi_row=.. mi_col=.. ref=.. +# i=.. this=(..,..) comp=(..,..) w=.." line per entry, printed under rung +# 4's EC_TRACE_MODE right after EC_MODE_VAL (rung 13 only prints the +# stack DEPTH). +python3 - "$SRC/av1/common/mvref_common.c" <<'PYT' +import sys +path = sys.argv[1] +s = open(path).read() +if "EC_TRACE_TPL" in s: + print("mvref_common rung 14 already applied (no-op)") + sys.exit(0) +old = " if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) return 0;\n" +assert old in s, "add_tpl_ref_mv's INVALID_MV early return moved" +new = """ if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) { + if (getenv("EC_TRACE_TPL")) + fprintf(stderr, "EC_TPL mi_row=%d mi_col=%d blk=(%d,%d) INVALID\\n", + mi_row, mi_col, blk_row, blk_col); + return 0; + } + if (getenv("EC_TRACE_TPL")) + fprintf(stderr, + "EC_TPL mi_row=%d mi_col=%d blk=(%d,%d) mfmv0=(%d,%d) rfo=%d\\n", + mi_row, mi_col, blk_row, blk_col, prev_frame_mvs->mfmv0.as_mv.row, + prev_frame_mvs->mfmv0.as_mv.col, prev_frame_mvs->ref_frame_offset); +""" +s = s.replace(old, new, 1) +open(path, "w").write(s) +print("mvref_common rung 14 (EC_TPL) instrumented") +PYT + +python3 - "$SRC/av1/decoder/decodemv.c" <<'PYST' +import sys +path = sys.argv[1] +s = open(path).read() +if "EC_STACK mi_row" in s: + print("decodemv rung 14 already applied (no-op)") + sys.exit(0) +assert "EC_MODE_MV" in s, "rung 14 needs rung 13 (run this script top to bottom)" +anchor = """ /* EC_STACK */ (int)dcb->ref_mv_count[av1_ref_frame_type(mbmi->ref_frame)], + (unsigned)r->ec.rng); +""" +assert s.count(anchor) == 1, "rung 13's EC_MODE_VAL body moved" +dump = """ /* EC_INSTRUMENTED lane-interbis: the resolved mv stack itself */ + const MV_REFERENCE_FRAME ec_rt = av1_ref_frame_type(mbmi->ref_frame); + for (int ec_i = 0; ec_i < dcb->ref_mv_count[ec_rt]; ec_i++) { + fprintf(stderr, + "EC_STACK mi_row=%d mi_col=%d ref=%d i=%d this=(%d,%d) " + "comp=(%d,%d) w=%d\\n", + ec_xd->mi_row, ec_xd->mi_col, (int)ec_rt, ec_i, + ec_xd->ref_mv_stack[ec_rt][ec_i].this_mv.as_mv.row, + ec_xd->ref_mv_stack[ec_rt][ec_i].this_mv.as_mv.col, + ec_xd->ref_mv_stack[ec_rt][ec_i].comp_mv.as_mv.row, + ec_xd->ref_mv_stack[ec_rt][ec_i].comp_mv.as_mv.col, + ec_xd->weight[ec_rt][ec_i]); + } +""" +s = s.replace(anchor, anchor + dump, 1) +open(path, "w").write(s) +print("decodemv rung 14 (per-entry EC_STACK) instrumented") +PYST