diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index 3a78f5fc..a857dc00 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -35,6 +35,9 @@ fn main() { 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}"); + println!("sub8_inter_split: groups={}", ec_av1::decode::sub8_inter_split_hits()); + let (h84, h48) = ec_av1::decode::sub8_inter_rect_hits(); + println!("sub8_inter_rect: horz8x4={h84} vert4x8={h48}"); let leaf = ec_av1::stream::vartx_rect_leaf_hits(); println!("vartx_rect_leaf: 32x16={} 16x32={}", leaf[0], leaf[1]); // lane-inter16ab r1: the 16x16-level inter AB arms, so a recipe sweep diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 89334535..19c9b910 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -230,6 +230,22 @@ pub(crate) enum TxbSet { /// counterpart: `EXT_TX_SET_DTT4_IDTX_1DDCT`, the seven-symbol `TX_4X4` /// row [`LumaRect4x8Set1`](TxbSet::LumaRect4x8Set1) reads. LumaRect16x4Set1, + /// The luma 8x4/4x8 transform of an INTER `PARTITION_HORZ`/`PARTITION_VERT` + /// leaf under an 8x8 block (lane-intersub8 r3): every coefficient table is + /// [`LumaRect4x8`](TxbSet::LumaRect4x8)'s (`get_txsize_entropy_ctx` squares + /// `TX_8X4` up to the 8x8 class, 32-position `eob_pt`), with the INTER + /// `tx_type` alphabet in its place. Under `reduced_tx_set` + /// `av1_get_ext_tx_set_type` (`tx_size_sqr_up == TX_8X8`, `is_inter`) + /// returns `EXT_TX_SET_DCT_IDTX`, whose row is + /// `default_inter_ext_tx_cdf[?][txsize_sqr_map[TX_8X4] == TX_4X4]` -- the + /// same `TX_4X4` inter row [`Luma4Inter`](TxbSet::Luma4Inter) reads. + LumaRect8x4Inter, + /// [`LumaRect8x4Inter`](TxbSet::LumaRect8x4Inter)'s `reduced_tx_set: false` + /// counterpart: `tx_size_sqr == TX_4X4` with `tx_size_sqr_up == TX_8X8`, so + /// `av1_ext_tx_set_lookup[is_inter=1][...]` is `EXT_TX_SET_ALL16` -- sixteen + /// symbols at the `TX_4X4` inter row, the table + /// [`Luma4InterSet1`](TxbSet::Luma4InterSet1) also reads. + LumaRect8x4InterSet1, } /// The tables one transform block is coded with, borrowed from the state for @@ -1792,6 +1808,30 @@ impl Cdfs { tx_type: Some(self.intra_tx_type_4[mode].as_mut_slice()), eob_pt_class1: Some(&mut self.eob_pt_32_luma_class1), }, + TxbSet::LumaRect8x4Inter => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_32_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_4.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_32_luma_class1), + }, + TxbSet::LumaRect8x4InterSet1 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_32_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_4_set1.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_32_luma_class1), + }, TxbSet::LumaRect4x8Set1 => TxbTables { side: 8, txb_skip: &mut self.txb_skip_luma_8, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 4b6f4671..531e1066 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -171,6 +171,26 @@ pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize { INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get()) } +// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside +// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm +// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and +// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block. +thread_local! { + static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf +/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`]. +pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) { + ( + INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()), + INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()), + INTRA_IN_INTER8_UV_CFL_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) @@ -1743,6 +1763,32 @@ thread_local! { static OBMC_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; } +// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter` +// pair whose two directions differ (`enable_dual_filter` only -- with dual +// filter off both directions take the single symbol, so this can never fire). +// A gate asserting it proves the stream really carries dual-filter blocks. +thread_local! { + static DUAL_FILTER_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own +// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf +// used to skip it entirely, losing a symbol and stamping the `[3, 3]` +// no-filter sentinel that made a neighbouring OBMC block panic). +thread_local! { + static COMPOUND8_FILTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`DUAL_FILTER_DIFF_HITS`]. +pub(crate) fn dual_filter_diff_hits() -> usize { + DUAL_FILTER_DIFF_HITS.with(|c| c.get()) +} + +/// Current value of [`COMPOUND8_FILTER_HITS`]. +pub(crate) fn compound8_filter_hits() -> usize { + COMPOUND8_FILTER_HITS.with(|c| c.get()) +} + // lane-warp round 1: how many blocks resolved `motion_mode_allowed` to // `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under // `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL` @@ -1774,6 +1820,20 @@ pub(crate) fn compound_warp_hits() -> usize { COMPOUND_WARP_HITS.with(|c| c.get()) } +// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound +// arm ([`decode_inter_block8`]) -- that arm predicted both taps +// translationally until r3, so a gate needs to tell a warped 8x8 compound +// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]). +thread_local! { + static COMPOUND_WARP_HITS_8: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`COMPOUND_WARP_HITS_8`]. +pub(crate) fn compound_warp_hits_8() -> usize { + COMPOUND_WARP_HITS_8.with(|c| c.get()) +} + // lane-gmaffine r1: how many blocks built their prediction from a // SIX-parameter (`AFFINE`) global-motion model through // `crate::warp::global_warp_params` -- the gate's proof that a stream really @@ -2597,6 +2657,43 @@ pub(crate) fn tx_class1_hits() -> usize { // coincidentally landing on `PARTITION_NONE`. thread_local! { static SUB8_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter + /// sub-blocks (lane-intersub8). + static SUB8_INTER_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8 + /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4), + /// `[1] = VERT` (two BLOCK_4X8). + static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; +} + +/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`. +pub fn sub8_inter_rect_hits() -> (usize, usize) { + SUB8_INTER_RECT_HITS.with(|c| { + let h = c.get(); + (h[0], h[1]) + }) +} + +// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all +// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38` +// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how +// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all. +// (b) was 0 for every stream before this round -- the leaf path never touched +// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got +// filtered where libaom skips it. A gate asserts both are non-zero. +thread_local! { + static CDEF_SKIPPED_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER8_SKIP_BAND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of `CDEF_SKIPPED_UNITS`. +pub(crate) fn cdef_skipped_units() -> usize { + CDEF_SKIPPED_UNITS.with(|c| c.get()) +} + +/// Current value of `INTER8_SKIP_BAND_HITS`. +pub(crate) fn inter8_skip_band_hits() -> usize { + INTER8_SKIP_BAND_HITS.with(|c| c.get()) } /// Current value of [`SUB8_SPLIT_HITS`]. @@ -2604,6 +2701,11 @@ pub(crate) fn sub8_split_hits() -> usize { SUB8_SPLIT_HITS.with(|c| c.get()) } +/// Current value of [`SUB8_INTER_SPLIT_HITS`]. +pub fn sub8_inter_split_hits() -> usize { + SUB8_INTER_SPLIT_HITS.with(|c| c.get()) +} + // How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ` // of an 8x8 block) this thread's decode reconstructed with REAL coefficients // -- a skipped leaf exercises the prediction and the mi bookkeeping but never @@ -8901,8 +9003,7 @@ fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, // LAST frame, so a mid-sequence divergence could not be read out at all. static STAGE16_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); if let Ok(path) = std::env::var(var) - && let idx = STAGE16_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst) - && let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) { for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] { for row in 0..h { @@ -8916,10 +9017,25 @@ fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, } } +/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a +/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so +/// every frame overwrote the previous one and only the LAST frame survived, +/// which silently defeats any per-frame filter-stage bisection. +fn dump_stage_idx(var: &str) -> usize { + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + static IDX: OnceLock>> = OnceLock::new(); + let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + let e = m.entry(var.to_string()).or_insert(0); + let i = *e; + *e += 1; + i +} + fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) { use std::io::Write; if let Ok(path) = std::env::var(var) - && let Ok(mut f) = std::fs::File::create(format!("{path}.f0")) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) { for p in [y, u, v] { let narrow: Vec = p.data.iter().map(|&s| s as u8).collect(); @@ -10432,6 +10548,7 @@ fn decode_leaf8( neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]); neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]); } + INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1)); neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 8, 0); neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); @@ -12787,6 +12904,9 @@ fn apply_cdef( while mi_r < skip_grid.mi_rows { let mut mi_c = 0usize; while mi_c < skip_grid.mi_cols { + if skip_grid.is_skip_txfm(mi_r, mi_c) { + CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1)); + } if !skip_grid.is_skip_txfm(mi_r, mi_c) { let sidx = strength_idx(mi_r, mi_c); let (ox, oy) = (mi_c * 4, mi_r * 4); @@ -12799,10 +12919,15 @@ fn apply_cdef( i32::from(src_y[ny as usize * y_stride + nx as usize]) } }; - let (dir, var) = cdef_find_dir(coeff_shift, |r, c| { - let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1)); - i32::from(src_y[ny * y_stride + nx]) - }); + // lane-cdef r1: the direction search reads the SAME padded + // block the taps do -- libaom runs `cdef_find_dir` on the + // prepared filter block (`cdef_block.c:296-320` over + // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns + // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE. + // Clamping to the last real sample instead made every straddling + // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence + // a different `adjust_strength`, hence a +-1 band at the crop edge. + let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32)); // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0` // -- each plane zeroes the shared direction when *its own* @@ -12812,6 +12937,12 @@ fn apply_cdef( let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift; let y_dir = if y_pri_strength != 0 { dir } else { 0 }; let t = cdef_adjust_strength(y_pri_strength, var); + // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit. + if std::env::var_os("EC_AV1_CDEF_DBG").is_some() { + eprintln!( + "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}" + ); + } let enable_primary = t != 0; let enable_secondary = y_sec_strength != 0; if enable_primary || enable_secondary { @@ -14868,6 +14999,13 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. + if std::env::var_os("EC_OBMC").is_some() || std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_PICT idx={}", + PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) + ); + } dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; @@ -15072,6 +15210,15 @@ fn resolve_interp_filter( } else { sym0 }; + if enable_dual_filter && sym0 != sym1 { + DUAL_FILTER_DIFF_HITS.with(|c| c.set(c.get() + 1)); + } + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}", + dec.debug_state().0 + ); + } ( mc::InterpFilterKind::from_switchable_symbol(sym1 as usize), mc::InterpFilterKind::from_switchable_symbol(sym0 as usize), @@ -15731,14 +15878,25 @@ fn obmc_mask(len: usize) -> &'static [u8] { fn neighbour_filter( interp_fixed: Option, sym: [u8; 2], -) -> (mc::InterpFilterKind, mc::InterpFilterKind) { +) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> { if let Some(kind) = interp_fixed { - return (kind, kind); + return Ok((kind, kind)); + } + // lane-interp3 r1: the `[3, 3]` sentinel reaching here is a DEFECT in + // whatever path recorded the neighbour (an inter block that never stored + // its own switchable symbols), and it used to abort the process through + // `from_switchable_symbol`'s panic. A decoder must never crash on a real + // stream: it stops by name instead, so the frame is refused and the + // stream is pinned like every other unsupported case. + if sym[0] > 2 || sym[1] > 2 { + return Err(unsupported( + "an OBMC neighbour whose interp filter was never recorded (no switchable symbol for that block)", + )); } - ( + Ok(( mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize), mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize), - ) + )) } /// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh @@ -15918,6 +16076,71 @@ fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, } } +/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block -- +/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to +/// the instrumented aomdec's `backup_mbmi.bsize`. +fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 { + match (w4, h4) { + (1, 1) => 0, + (1, 2) => 1, + (2, 1) => 2, + (2, 2) => 3, + (2, 4) => 4, + (4, 2) => 5, + (4, 4) => 6, + (4, 8) => 7, + (8, 4) => 8, + (8, 8) => 9, + (8, 16) => 10, + (16, 8) => 11, + (16, 16) => 12, + (1, 4) => 16, + (4, 1) => 17, + (2, 8) => 18, + (8, 2) => 19, + (4, 16) => 20, + (16, 4) => 21, + _ => -1, + } +} + +/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented +/// aomdec's own byte format (`decodeframe.c` +/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC +/// neighbour lists diff line for line. `filt` is libaom's packed +/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`. +#[allow(clippy::too_many_arguments)] +fn ec_obmc_trace( + dir: &str, + mi_row: usize, + mi_col: usize, + write_w: usize, + write_h: usize, + rel: usize, + op: usize, + nb: &MiInfo, + h_kind: mc::InterpFilterKind, + v_kind: mc::InterpFilterKind, +) { + if std::env::var_os("EC_OBMC").is_none() { + return; + } + let sym = |k: mc::InterpFilterKind| match k { + mc::InterpFilterKind::Smooth => 1u32, + mc::InterpFilterKind::Sharp => 2, + _ => 0, + }; + eprintln!( + "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \ +nbmv=({},{}) nbref={} nbbsize={} filt={}", + nb.mv.0, + nb.mv.1, + nb.ref_frame, + ec_obmc_bsize(nb.size, nb.size_h), + sym(v_kind) | (sym(h_kind) << 16), + ); +} + /// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts /// the overlap strip against each bordering above/left inter neighbour's own /// mv/ref/filter and blends it into this block's just-built single-reference @@ -16016,7 +16239,8 @@ fn obmc_blend( let (h_kind, v_kind) = neighbour_filter( interp_fixed, neighbours.above_filter[mi_col + off4], - ); + )?; + ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind); let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?; let nb_scale = mc::scale_factor(ny.width, frame_width); let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4); @@ -16035,7 +16259,8 @@ fn obmc_blend( let (h_kind, v_kind) = neighbour_filter( interp_fixed, neighbours.left_filter[mi_row + off4], - ); + )?; + ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind); let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?; let nb_scale = mc::scale_factor(ny.width, frame_width); let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4); @@ -16060,6 +16285,67 @@ fn is_any_masked_compound_used_here(side: usize) -> bool { side.min(side) >= 8 } +/// libaom's `BLOCK_SIZES_ALL` index of a `w`x`h` block (`common_data.h`'s own +/// enum order) -- the row every bsize-indexed CDF (`compound_type_cdf`, +/// `wedge_idx_cdf`) is read at. lane-intersub8 r4: these two used to be +/// indexed by the caller's SQUARE envelope, so a 16x8 compound block read +/// `BLOCK_16X16`'s row (class table-indexed-by-raw-size) and desynced the +/// tile at its first masked-compound rect block. +fn bsize_index(w: usize, h: usize) -> Option { + Some(match (w, h) { + (4, 4) => 0, + (4, 8) => 1, + (8, 4) => 2, + (8, 8) => 3, + (8, 16) => 4, + (16, 8) => 5, + (16, 16) => 6, + (16, 32) => 7, + (32, 16) => 8, + (32, 32) => 9, + (32, 64) => 10, + (64, 32) => 11, + (64, 64) => 12, + (64, 128) => 13, + (128, 64) => 14, + (128, 128) => 15, + (4, 16) => 16, + (16, 4) => 17, + (8, 32) => 18, + (32, 8) => 19, + (16, 64) => 20, + (64, 16) => 21, + _ => return None, + }) +} + +/// `is_any_masked_compound_used` (libaom `reconinter.h`) on the block's TRUE +/// footprint: `is_comp_ref_allowed` is `AOMMIN(bw, bh) >= 8`, and every +/// shape that clears it has either a wedge or a DIFFWTD compound available. +fn masked_compound_used_wh(w: usize, h: usize) -> bool { + w.min(h) >= 8 +} + +/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`): +/// the shapes whose `compound_type` symbol is really coded. Everything else +/// with a compound mask infers `COMPOUND_DIFFWTD` without a symbol. +fn wedge_used_wh(w: usize, h: usize) -> bool { + matches!( + (w, h), + (8, 8) + | (8, 16) + | (16, 8) + | (16, 16) + | (16, 32) + | (32, 16) + | (32, 32) + | (8, 32) + | (32, 8) + | (16, 64) + | (64, 16) + ) +} + /// Whether a compound reference pair is unidirectional (both references on /// the same temporal side of the current frame) -- `has_uni_comp_refs` /// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition: @@ -16849,12 +17135,18 @@ fn decode_inter_block( let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side); let comp_group_idx = if !skip_mode && enable_masked_compound - && is_any_masked_compound_used_here(side) + && masked_compound_used_wh(write_w, write_h) { dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) } else { 0 }; + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}", + dec.debug_state().0 + ); + } // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup) // for a `COMPOUND_WEDGE` block -- exactly one of the two is set @@ -16876,12 +17168,11 @@ fn decode_inter_block( // writes NO `compound_type` symbol there and INFERS // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal // follows. `None` here is exactly that inferred arm. - let wedge_bsize = match side { - 8 => Some(3), - 16 => Some(6), - 32 => Some(9), - _ => None, - }; + // lane-intersub8 r4: the block's TRUE footprint, not the + // square envelope -- `compound_type_cdf`/`wedge_idx_cdf` are + // `BLOCK_SIZES_ALL`-indexed. + let wedge_bsize = + bsize_index(write_w, write_h).filter(|_| wedge_used_wh(write_w, write_h)); let compound_type = match wedge_bsize { Some(b) => dec.symbol(&mut cdfs.compound_type[b]), None => 1, @@ -16889,6 +17180,14 @@ fn decode_inter_block( if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) { // COMPOUND_WEDGE: lane-wedge r3, codebook checksum- // verified vs independent C dump (wedge.rs). + if write_w != write_h { + // lane-intersub8 r4: the wedge codebook here is built + // per SQUARE side only; a rect block's own codebook + // (BLOCK_16X8 etc.) is a different mask set. + return Err(unsupported( + "a COMPOUND_WEDGE mask on a non-square inter block (rect wedge codebook unimplemented)", + )); + } let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]); let wedge_sign = dec.literal(1); WEDGE_HITS.with(|c| c.set(c.get() + 1)); @@ -17120,6 +17419,12 @@ fn decode_inter_block( ref_order_hints[(ref1 - LAST_FRAME) as usize], ); let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}", + dec.debug_state().0 + ); + } if idx == 1 { (8, 8, 1u8) } else { @@ -18748,6 +19053,12 @@ fn decode_inter_block( return Ok(()); } let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]); + if std::env::var_os("EC_IIS").is_some() { + eprintln!( + "TRACE iis px={px} py={py} side={side} w={write_w} h={write_h} sg={} mode={mode} skip={skip}", + size_group_wh(write_w, write_h) + ); + } if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", @@ -19171,30 +19482,47 @@ fn decode_inter_block( Ok(()) } -/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block -/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s -/// exact symbol order: its own skip flag, intra/inter choice and (when -/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack -/// window, or (when intra) `Y_MODE`, then its own luma and two chroma -/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`], -/// same as [`decode_leaf8`]'s coefficient layer but with -/// motion-compensated prediction instead of intra prediction when inter. -/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's -/// skip/intra-inter context, overridden by `prev_leaf` exactly as -/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays -/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag -/// and intra/inter choice, for the next leaf or the caller's final -/// write-back. +/// Decodes one 8x8 group that an inter frame's `partition_w8` symbol split +/// into four `BLOCK_4X4` inter blocks (lane-intersub8: `PARTITION_SPLIT` +/// below 8x8 -- traced live against the oracle `aomdec`'s own `EC_PART_VAL`, +/// which reads `bsize=3 value=3` on real inter frames, so the refusal this +/// replaces was NOT our own desync). +/// +/// The inter counterpart of [`decode_leaf_split4`], and a `BLOCK_4X4`-only +/// cut of [`decode_inter_block8`]: at `min(bw, bh) < 8` libaom switches off +/// half the inter syntax, and every one of those is a symbol NOT read here +/// (`decodemv.c` / `blockd.h`, oracle tree): +/// * `skip_mode`: `read_skip_mode` returns 0 without a symbol when +/// `!is_comp_ref_allowed(bsize)` (`AOMMIN(bw, bh) >= 8`, blockd.h). +/// * `comp_mode`: `read_block_reference_mode` returns `SINGLE_REFERENCE` on +/// the same predicate, so a sub-8x8 block is always single-reference. +/// * `interintra`: `is_interintra_allowed_bsize` starts at `BLOCK_8X8`. +/// * `motion_mode` / `obmc`: `motion_mode_allowed` returns +/// `SIMPLE_TRANSLATION` for `block_size_wide < 8 || block_size_high < 8`, +/// and `is_global_mv_block`'s own size term fails, so no warp either. +/// * tx size: `block_signals_txsize(bsize)` is `bsize > BLOCK_4X4` +/// (blockd.h:1027), so a `BLOCK_4X4` reads neither `tx_depth` nor a +/// `txfm_partition` bit even in `TX_MODE_SELECT` -- the transform is +/// `max_txsize_rect_lookup[BLOCK_4X4]` = `TX_4X4` +/// (`decodeframe.c:1164-1177`). +/// +/// Chroma is coded ONCE for the whole 8x8 group, on the last sub-block +/// (`is_chroma_reference`: `(mi_row & 1) && (mi_col & 1)` in 4:2:0), as one +/// `TX_4X4` unit per plane -- same rule and same neighbour-context tail as +/// [`decode_leaf_split4`]. Its PREDICTION is the sub8x8 one +/// (`dec_build_inter_predictors`'s `is_sub8x8` branch, `decodeframe.c`; spec +/// 7.11.3.1's `candRow`/`candCol` loop): four 2x2 chroma pieces, each built +/// from its own luma sub-block's reference, motion vector and interpolation +/// filters, never from the last sub-block's mv alone. #[allow(clippy::too_many_arguments)] -fn decode_inter_block8( +fn decode_inter_sub8_split4( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, neighbours: &mut Neighbours, grid: &mut MiGrid, + group_mi: (usize, usize), mi_cols: u32, mi_rows: u32, - outer_at: (usize, usize), - leaf_mi: (usize, usize), y: &mut PlaneBuf, u: &mut PlaneBuf, v: &mut PlaneBuf, @@ -19202,147 +19530,1064 @@ fn decode_inter_block8( ref_u: &PlaneBuf, ref_v: &PlaneBuf, other_refs: &RefSlots, + sign_bias_table: &SignBiasTable, + global_motion: &[ec_av1_syntax::WarpParams; 7], base_q_idx: u8, - scan8: &[u16], scan4: &[u16], allow_high_precision_mv: bool, force_integer_mv: bool, - // lane-gmaffine r1: this frame header's own `global_motion` table (spec - // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table - // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code - // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing - // candidates with the gm mv (gm r6's root cause) and build a global - // warp prediction. - global_motion: &[ec_av1_syntax::WarpParams; 7], - // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit, - // for the leaf's own `read_mb_interp_filter` below. - enable_dual_filter: bool, - // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path - // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no - // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s - // context uses that same approximation. - reference_select: bool, - enable_masked_compound: bool, - // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is - // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate - // drops the `side` check entirely. - enable_interintra_compound: bool, - enable_jnt_comp: bool, - order_hint_bits: u32, - order_hint: u32, - ref_order_hints: [u32; 7], - // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this - // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either, - // so its `skip_mode` context reuses the same [`SUB`]-grid - // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot - // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation - // just above). - skip_mode_present: bool, - skip_mode_frame: [u8; 2], - // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see - // [`decode_inter_frame_tile_with_cdfs`]'s own doc. - reduced_tx_set: bool, - // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/ - // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus - // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour - // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own - // prediction is always `Regular` (documented corner-cut, `mc::predict` - // has no filter param), but an OBMC neighbour can be a real 16x16+ - // block that DID resolve a switchable filter. interp_fixed: Option, - switchable_motion_mode: bool, - allow_warped_motion: bool, - // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a - // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16 - // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own - // `compound_ctx` local, just handed back instead of applied here (this - // fn's `neighbours` recording happens once for the whole straddling - // 16x16 block, after every leaf). - // lane-screen r2: see [`decode_inter_block`]'s own copy of this param -- - // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`- - // eligible (`bsize >= BLOCK_8X8`). - allow_screen_content_tools: bool, - // lane-inter8 r1: the leaf's mv stacks used to be built without the - // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`] - // one level up passed it -- it changes the candidate list and with it - // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read. - // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's - // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot - // 8x8-split gate). - sign_bias_table: &SignBiasTable, - // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which - // [`decode_inter_block`] one level up has always passed and this leaf - // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds - // fewer candidates here than in the reference decoder, which changes the - // mode contexts AND the number of `drl_mode` bits read (class parsed - // then discarded). + enable_dual_filter: bool, tpl_frame: Option<&TplFrameArgs>, - // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3), - // for the scaled-reference MC this leaf's own single-ref/compound/OBMC - // predictions take when a stored reference was coded at another width - // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param. + reduced_tx_set: bool, frame_width: usize, -) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option))> { +) -> Result<()> { const LAST_FRAME: i8 = 1; - // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back - // so the caller stamps them into `Neighbours` instead of the `[3, 3]` - // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an - // OBMC blend that picks such a neighbour up feeds it to - // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) -- - // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]` - // on the intra and compound paths. - let mut leaf_filter_syms = [3u8; 2]; - // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's - // missing-candidate fallback both come from the frame's global motion - // evaluated at THIS block's centre (gm r6's root cause). - let gm_table = build_gm_mv_table( - global_motion, - leaf_mi.0, - leaf_mi.1, - 2, - 2, - allow_high_precision_mv, - force_integer_mv, - ); - /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`). - const SIZE_GROUP_8: usize = 1; - - let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); - let (cpx, cpy) = (px / 2, py / 2); - // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took - // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) -- - // read back by the luma residual read and the tail's neighbour/loop-filter - // bookkeeping. Always `false` outside a `TxMode::Select` inter frame. - let mut split8 = false; - const SIDE: usize = 8; - const CHROMA_SIDE: usize = 4; - - let (r, c) = outer_at; - let _ = (r, c); - // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's -- - // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the - // left column of a 16x16's second leaf ROW is the previous 16x16 block's - // bottom leaf, neither of which a SUB-grid slot can name. - let (rmi, cmi) = leaf_mi; - // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps - // its own 2x2-mi span into the bands right after it decodes (the caller's - // `record_inter_rect_mi`), so a plain mi read already names the correct - // neighbour, including one belonging to the previous 16x16 block. - let above_skip = neighbours.above_skip[cmi]; - let left_skip = neighbours.left_skip[rmi]; - let above_inter = neighbours.above_inter[cmi]; - let left_inter = neighbours.left_inter[rmi]; - let above_ref0 = neighbours.above_ref[cmi]; - let above_ref1 = neighbours.above_ref1[cmi]; - let left_ref0 = neighbours.left_ref[rmi]; - let left_ref1 = neighbours.left_ref1[rmi]; - let skip_mode_ctx = - usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]); - // Same two `inter_segment_id` positions as [`decode_inter_block`]; this - // leaf is always `BLOCK_8X8`, i.e. 2x2 mi. - inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true); - let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; - if skip_mode { + const B4: usize = 4; + SUB8_INTER_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + let (gr, gc) = group_mi; + let (gpx, gpy) = (gc * MI, gr * MI); + let (cpx, cpy) = (gpx / 2, gpy / 2); + // Per-sub-block state the group's chroma prediction needs (spec + // 7.11.3.1's candRow/candCol loop reads each sub-block's OWN mv/ref/ + // filters), indexed `dr * 2 + dc`. + let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] = + [None; 4]; + let mut first_tx_type = TxType::DctDct; + let mut last_skip = true; + for i in 0..4usize { + let (dr, dc) = (i / 2, i % 2); + let lmi = (gr + dr, gc + dc); + if lmi.0 >= mi_rows as usize || lmi.1 >= mi_cols as usize { + continue; + } + let (rmi, cmi) = lmi; + let (px, py) = (cmi * MI, rmi * MI); + inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, false, true); + // No `skip_mode` symbol: `is_comp_ref_allowed(BLOCK_4X4)` is false. + let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); + let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false); + maybe_read_cdef_idx(dec, rmi, cmi, skip); + maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip); + maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip); + let (has_above, has_left) = ( + rmi > neighbours.tile_row0_mi, + cmi > neighbours.tile_col0_mi, + ); + let ii_ctx = intra_inter_ctx( + has_above, + has_left, + neighbours.above_inter[cmi], + neighbours.left_inter[rmi], + ); + let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; + if !is_inter { + return Err(unsupported( + "an intra 4x4 block inside an inter frame's sub-8x8 split (this decoder codes \ + only inter 4x4 sub-blocks there)", + )); + } + // Same print point as the oracle's `EC_MODE` (entry of + // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the + // two range ladders line up element for element. + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE mi_row={rmi} mi_col={cmi} rng={}", + dec.debug_state().0 + ); + } + let ref_frame = read_single_ref( + dec, + cdfs, + neighbours.above_ref[cmi], + neighbours.above_ref1[cmi], + neighbours.left_ref[rmi], + neighbours.left_ref1[rmi], + ); + let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + if mc::scale_factor(sref_y.width, frame_width) != mc::REF_NO_SCALE { + return Err(unsupported( + "a sub-8x8 inter block under a scaled reference (superres, unimplemented)", + )); + } + let gm_table = build_gm_mv_table( + global_motion, + rmi, + cmi, + 1, + 1, + allow_high_precision_mv, + force_integer_mv, + ); + let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { + field: t.field, + cur_offset_0: crate::motion_field::get_relative_dist( + t.order_hint_bits, + t.order_hint, + t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], + ), + allow_high_precision_mv, + }); + let stack = crate::mvstack::find_mv_stack_with_sign_bias( + grid, + rmi, + cmi, + 1, + 1, + ref_frame, + mi_cols as usize, + mi_rows as usize, + sign_bias_table, + &gm_table, + tpl, + ); + let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; + let mut is_globalmv = false; + let (mv, is_new_mv) = if !not_new { + let mut idx = 0usize; + while idx < 2 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + ( + read_mv( + dec, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + base_mv, + allow_high_precision_mv, + force_integer_mv, + ), + true, + ) + } else { + let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; + is_globalmv = !not_zero; + let mv = if !not_zero { + gm_table[(ref_frame - LAST_FRAME) as usize] + } else { + let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + if nearest { + stack.nearest_mv + } else { + let mut idx = 1usize; + while idx < 3 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) + } + }; + (mv, false) + }; + // Same print point as the oracle's `EC_MODE_MV` (right after + // `assign_mv`), the second rung of the sub-8x8 range ladder. + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}", + mv.0, + mv.1, + dec.debug_state().0 + ); + } + // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see + // this function's own doc); `read_mb_interp_filter` still runs. + let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; + let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame + || neighbours.above_ref1[cmi] == Some(ref_frame) + { + neighbours.above_filter[cmi] + } else { + [3, 3] + }; + let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame + || neighbours.left_ref1[rmi] == Some(ref_frame) + { + neighbours.left_filter[rmi] + } else { + [3, 3] + }; + if std::env::var_os("EC_AV1_IFDBG").is_some() { + eprintln!( + "IFDBG4 mi=({rmi},{cmi}) ref={ref_frame} above_ref={} above_ref1={:?} \ + above_filt={:?} left_ref={} left_ref1={:?} left_filt={:?}", + neighbours.above_ref[cmi], + neighbours.above_ref1[cmi], + neighbours.above_filter[cmi], + neighbours.left_ref[rmi], + neighbours.left_ref1[rmi], + neighbours.left_filter[rmi], + ); + } + let gm_nontrans = is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation; + let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( + dec, + cdfs, + interp_fixed, + enable_dual_filter, + gm_nontrans, + above_filter_ctx, + left_filter_ctx, + false, + ); + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE_VAL4 mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \ + ref0={ref_frame} mv0=({},{}) stack={} rng={}", + mv.0, + mv.1, + stack.entries.len(), + dec.debug_state().0 + ); + } + grid.set( + rmi, + cmi, + MiInfo { + is_inter: true, + ref_frame, + ref_frame1: None, + mv1: None, + mv, + is_new_mv, + size: 1, + size_h: 1, + is_global_mv0: false, + is_global_mv1: false, + }, + ); + piece[i] = Some((ref_frame, mv, h_filter, v_filter)); + let mut pred_y = vec![0u16; B4 * B4]; + mc::predict_with_filters( + &sref_y.data, + sref_y.width, + sref_y.true_width, + sref_y.true_height, + mv_to_q4(px, mv.1, true), + mv_to_q4(py, mv.0, true), + B4, + B4, + h_filter, + v_filter, + &mut pred_y, + ); + // `BLOCK_4X4` never signals a transform size, so the luma unit is the + // whole block and `get_txb_ctx` takes its `plane_bsize == + // txsize_to_bsize[tx_size]` branch (`txb_skip_ctx = 0`, which + // `read_inter_plane`'s `plane_idx == 0` arm already assumes). + if skip { + y.reconstruct_mc(px, py, B4, &pred_y, &vec![0i32; B4 * B4]); + neighbours.record_mi_luma_rect(lmi, B4, B4, &vec![0i32; B4 * B4]); + } else { + let around = neighbours.around_mi(lmi, B4); + let (luma_grid, tx_type) = read_inter_plane( + dec, + cdfs, + if reduced_tx_set { + TxbSet::Luma4Inter + } else { + TxbSet::Luma4InterSet1 + }, + scan4, + 0, + around[0], + 0, + y, + px, + py, + B4, + base_q_idx, + &pred_y, + None, + None, + )?; + if i == 0 { + // `av1_get_tx_type`: an inter block's chroma inherits the + // tx_type of the CO-LOCATED luma position, which for the + // group's one chroma unit is luma (0, 0) -- the FIRST + // sub-block, not the last. + first_tx_type = tx_type; + } + neighbours.record_mi_luma_rect(lmi, B4, B4, &luma_grid); + } + neighbours.record_mode_mi(rmi, cmi, 1, 1, DC_PRED); + neighbours.record_inter_rect_mi(lmi, 1, 1, skip, true, ref_frame, resolved_filter, false); + neighbours.fill_skip_grid_rect(lmi, 1, 1, skip); + neighbours.fill_lf_grid_rect(lmi, 1, 1, B4 as u8, B4 as u8, ref_frame.max(LAST_FRAME)); + last_skip = skip; + } + // Chroma, once for the whole group, on the last sub-block's own `skip` + // flag -- prediction from all four sub-blocks (2x2 pieces), residual as + // one TX_4X4 unit per plane. + let mut pred_u = vec![0u16; B4 * B4]; + let mut pred_v = vec![0u16; B4 * B4]; + for i in 0..4usize { + let (dr, dc) = (i / 2, i % 2); + let Some((ref_frame, mv, h_filter, v_filter)) = piece[i] else { + continue; + }; + let (_, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (ox, oy) = (cpx + dc * 2, cpy + dr * 2); + for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { + let mut buf = vec![0u16; 4]; + mc::predict_with_filters( + &plane.data, + plane.width, + plane.true_width, + plane.true_height, + mv_to_q4(ox, mv.1, false), + mv_to_q4(oy, mv.0, false), + 2, + 2, + h_filter, + v_filter, + &mut buf, + ); + for row in 0..2 { + for col in 0..2 { + dst[(dr * 2 + row) * B4 + dc * 2 + col] = buf[row * 2 + col]; + } + } + } + } + let (u_grid, v_grid) = if last_skip { + u.reconstruct_mc(cpx, cpy, B4, &pred_u, &vec![0i32; B4 * B4]); + v.reconstruct_mc(cpx, cpy, B4, &pred_v, &vec![0i32; B4 * B4]); + (vec![0i32; B4 * B4], vec![0i32; B4 * B4]) + } else { + let around = neighbours.around_mi(group_mi, 8); + let ug = read_inter_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], 0, u, cpx, cpy, B4, base_q_idx, + &pred_u, Some(first_tx_type), None, + )? + .0; + let vg = read_inter_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], 0, v, cpx, cpy, B4, base_q_idx, + &pred_v, Some(first_tx_type), None, + )? + .0; + (ug, vg) + }; + neighbours.record_uv_mode_mi(gr, gc, 2, 2, DC_PRED); + // Same two neighbour tails [`decode_leaf_split4`] runs: the partition + // context of a `BLOCK_4X4` subsize (`partition_context_lookup` bit 0 = 1, + // reached by `side_mi = 4` here) and the group's chroma coefficient state. + for cell in 0..2usize { + neighbours.left_side_mi[gr + cell] = 4; + neighbours.above_side_mi[gc + cell] = 4; + } + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let bound_h = round_up_even(neighbours.mi_rows); + let bound_w = round_up_even(neighbours.mi_cols); + let u_state = neighbour_state(&u_grid); + let v_state = neighbour_state(&v_grid); + for cell in 0..2usize { + if cell < 2usize.min(bound_h.saturating_sub(gr)) { + neighbours.left[gr + cell][1] = u_state; + neighbours.left[gr + cell][2] = v_state; + } + if cell < 2usize.min(bound_w.saturating_sub(gc)) { + neighbours.above[gc + cell][1] = u_state; + neighbours.above[gc + cell][2] = v_state; + } + } + Ok(()) +} + +/// Decodes a `PARTITION_HORZ`/`PARTITION_VERT` of one 8x8 INTER block into two +/// `BLOCK_8X4`/`BLOCK_4X8` inter leaves (lane-intersub8 r3) -- the inter twin of +/// [`decode_leaf_rect8`] and the rectangular sibling of +/// [`decode_inter_sub8_split4`], whose element order it follows exactly. +/// Per sub-block, in libaom `decodemv.c` `read_inter_frame_mode_info` order: +/// +/// * `segment_id`, `skip`, `cdef`/`delta_q`/`delta_lf`, `intra_inter`; +/// * NO `skip_mode` symbol: `is_comp_ref_allowed(BLOCK_8X4)` is false +/// (`av1_is_comp_ref_allowed` needs both sides >= 8), so +/// `read_skip_mode` returns 0 without reading and `comp_mode` is never read +/// either (`read_ref_frames`' `is_comp_ref_allowed` guard) -- single +/// reference only; +/// * NO `interintra` and NO `motion_mode`/OBMC/warp symbol: every one of those +/// gates needs `block_size_wide >= 8 && block_size_high >= 8` +/// (`is_interintra_allowed_bsize`, `motion_mode_allowed`), and one side is 4; +/// * `read_mb_interp_filter` DOES run for both sub-blocks. +/// +/// The shape's own differences from the four-way split: +/// +/// * `block_signals_txsize(BLOCK_8X4)` is true (`bsize > BLOCK_4X4`, +/// blockd.h:1027), so a non-skipped sub-block reads ONE `txfm_partition` +/// symbol under `TX_MODE_SELECT` at `max_txsize_rect_lookup[BLOCK_8X4] == +/// TX_8X4` ([`read_var_tx_size`]); split resolves to two `TX_4X4` units +/// (`sub_tx_size_map[TX_8X4] == TX_4X4`, libaom's early return), no split to +/// the whole-leaf `TX_8X4`; +/// * the luma coefficient set is [`TxbSet::LumaRect8x4Inter`] (the 8x8 +/// coefficient class with a 32-position `eob_pt` and the INTER `TX_4X4` +/// `tx_type` row) for the whole-leaf unit, and the square +/// [`TxbSet::Luma4Inter`] for a split `TX_4X4` unit; +/// * chroma is coded ONCE, on the sub-block that is the chroma reference: +/// `is_chroma_reference` (`av1_common_int.h`) is +/// `((mi_row & 1) || !(bh4 & 1) || !ss_y) && ((mi_col & 1) || !(bw4 & 1) || +/// !ss_x)`, i.e. under 4:2:0 the BOTTOM 8x4 (`bh4 == 1`, odd) and the RIGHT +/// 4x8 (`bw4 == 1`) -- always the second sub-block here; +/// * that chroma unit's prediction is the sub8x8 one (`reconinter.c` +/// `build_inter_predictors_sub8x8`: `row_start = -(block_size_high == 4 && +/// ss_y)`, `col_start = -(block_size_wide == 4 && ss_x)`), two 4x2 (HORZ) or +/// 2x4 (VERT) chroma pieces, each from its OWN sub-block's reference, mv and +/// interpolation filters. +#[allow(clippy::too_many_arguments)] +fn decode_inter_sub8_rect2( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + grid: &mut MiGrid, + group_mi: (usize, usize), + vert: bool, + mi_cols: u32, + mi_rows: u32, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + ref_y: &PlaneBuf, + ref_u: &PlaneBuf, + ref_v: &PlaneBuf, + other_refs: &RefSlots, + sign_bias_table: &SignBiasTable, + global_motion: &[ec_av1_syntax::WarpParams; 7], + base_q_idx: u8, + scan4: &[u16], + allow_high_precision_mv: bool, + force_integer_mv: bool, + interp_fixed: Option, + enable_dual_filter: bool, + tpl_frame: Option<&TplFrameArgs>, + reduced_tx_set: bool, + frame_width: usize, +) -> Result<()> { + const LAST_FRAME: i8 = 1; + // The 8x8 group's own square stride: both leaves' prediction buffers are + // laid out at it, as every other rect inter unit here is. + const SIDE: usize = 8; + let (bw, bh) = if vert { (4usize, 8usize) } else { (8usize, 4usize) }; + let (w_mi, h_mi) = (bw / MI, bh / MI); + SUB8_INTER_RECT_HITS.with(|c| { + let mut h = c.get(); + h[usize::from(vert)] += 1; + c.set(h); + }); + let (gr, gc) = group_mi; + let (gpx, gpy) = (gc * MI, gr * MI); + let (cpx, cpy) = (gpx / 2, gpy / 2); + // Per-sub-block state the group's one chroma unit predicts from. + let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] = + [None; 2]; + let mut first_tx_type = TxType::DctDct; + let mut last_skip = true; + for i in 0..2usize { + let lmi = if vert { (gr, gc + i) } else { (gr + i, gc) }; + if lmi.0 >= mi_rows as usize || lmi.1 >= mi_cols as usize { + continue; + } + let (rmi, cmi) = lmi; + let (px, py) = (cmi * MI, rmi * MI); + inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, false, true); + let skip_ctx = + usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); + let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, skip, false); + maybe_read_cdef_idx(dec, rmi, cmi, skip); + maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip); + maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip); + let (has_above, has_left) = ( + rmi > neighbours.tile_row0_mi, + cmi > neighbours.tile_col0_mi, + ); + let ii_ctx = intra_inter_ctx( + has_above, + has_left, + neighbours.above_inter[cmi], + neighbours.left_inter[rmi], + ); + let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; + if !is_inter { + return Err(unsupported( + "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition \ + (this decoder codes only inter sub-blocks there)", + )); + } + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE mi_row={rmi} mi_col={cmi} rng={}", + dec.debug_state().0 + ); + } + let ref_frame = read_single_ref( + dec, + cdfs, + neighbours.above_ref[cmi], + neighbours.above_ref1[cmi], + neighbours.left_ref[rmi], + neighbours.left_ref1[rmi], + ); + let (sref_y, _, _) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + if mc::scale_factor(sref_y.width, frame_width) != mc::REF_NO_SCALE { + return Err(unsupported( + "a sub-8x8 inter block under a scaled reference (superres, unimplemented)", + )); + } + let gm_table = build_gm_mv_table( + global_motion, + rmi, + cmi, + w_mi, + h_mi, + allow_high_precision_mv, + force_integer_mv, + ); + let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { + field: t.field, + cur_offset_0: crate::motion_field::get_relative_dist( + t.order_hint_bits, + t.order_hint, + t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], + ), + allow_high_precision_mv, + }); + let stack = crate::mvstack::find_mv_stack_with_sign_bias( + grid, + rmi, + cmi, + w_mi, + h_mi, + ref_frame, + mi_cols as usize, + mi_rows as usize, + sign_bias_table, + &gm_table, + tpl, + ); + let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; + let mut is_globalmv = false; + let (mv, is_new_mv) = if !not_new { + let mut idx = 0usize; + while idx < 2 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + ( + read_mv( + dec, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + base_mv, + allow_high_precision_mv, + force_integer_mv, + ), + true, + ) + } else { + let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; + is_globalmv = !not_zero; + let mv = if !not_zero { + gm_table[(ref_frame - LAST_FRAME) as usize] + } else { + let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + if nearest { + stack.nearest_mv + } else { + let mut idx = 1usize; + while idx < 3 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) + } + }; + (mv, false) + }; + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}", + mv.0, + mv.1, + dec.debug_state().0 + ); + } + let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; + let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame + || neighbours.above_ref1[cmi] == Some(ref_frame) + { + neighbours.above_filter[cmi] + } else { + [3, 3] + }; + let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame + || neighbours.left_ref1[rmi] == Some(ref_frame) + { + neighbours.left_filter[rmi] + } else { + [3, 3] + }; + let gm_nontrans = is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation; + let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( + dec, + cdfs, + interp_fixed, + enable_dual_filter, + gm_nontrans, + above_filter_ctx, + left_filter_ctx, + false, + ); + // `read_block_tx_size` (libaom `decodeframe.c`): unlike a `BLOCK_4X4`, + // this shape signals its transform size. A non-skipped inter block + // walks the var-tx tree from `max_txsize_rect_lookup[BLOCK_8X4]`; a + // skipped one codes nothing and records its BLOCK size in both txfm + // contexts (`set_txfm_ctxs`' `skip_inter` arm). + let mut leaves: Vec<(usize, usize, usize, usize)> = Vec::new(); + if TX_SELECT_INTER.with(std::cell::Cell::get) && !skip { + let max_w_mi = w_mi.min((mi_cols as usize).saturating_sub(cmi)); + let max_h_mi = h_mi.min((mi_rows as usize).saturating_sub(rmi)); + read_var_tx_size( + dec, + cdfs, + neighbours, + lmi, + SIDE, + (max_w_mi, max_h_mi), + (bw, bh), + 0, + 0, + 0, + &mut leaves, + ); + } else { + leaves.push((0, 0, bw, bh)); + set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip); + } + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE_VALR mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \ + ref0={ref_frame} mv0=({},{}) stack={} leaves={} rng={}", + mv.0, + mv.1, + stack.entries.len(), + leaves.len(), + dec.debug_state().0 + ); + } + grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv); + piece[i] = Some((ref_frame, mv, h_filter, v_filter)); + // Prediction over the leaf's true footprint, laid out at the group's + // square stride (what `reconstruct_mc_rect` and `read_inter_plane_rect` + // index with). + let mut pred_y = vec![0u16; SIDE * SIDE]; + { + let mut dense = vec![0u16; bw * bh]; + mc::predict_with_filters( + &sref_y.data, + sref_y.width, + sref_y.true_width, + sref_y.true_height, + mv_to_q4(px, mv.1, true), + mv_to_q4(py, mv.0, true), + bw, + bh, + h_filter, + v_filter, + &mut dense, + ); + for row in 0..bh { + pred_y[row * SIDE..][..bw].copy_from_slice(&dense[row * bw..][..bw]); + } + } + if skip { + y.reconstruct_mc_rect(px, py, SIDE, bw, bh, &pred_y, &vec![0i32; SIDE * SIDE]); + neighbours.record_mi_luma_rect(lmi, bw, bh, &vec![0i32; bw * bh]); + neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, bw as u8, bh as u8, ref_frame.max(LAST_FRAME)); + } else { + let (mut last_tw, mut last_th) = (bw, bh); + for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() { + let tu_mi = (rmi + row, cmi + col); + let (tu_px, tu_py) = (px + col * MI, py + row * MI); + let (tu_grid, tu_tx_type) = if tw == th { + // A split `TX_4X4` unit: square reader, its own + // `get_txb_ctx_general` neighbour context (the unit is + // smaller than its plane block, so the lone-TU 0 does not + // apply). + let mut tu_pred = Vec::with_capacity(tw * th); + for rr in 0..th { + let start = (row * MI + rr) * SIDE + col * MI; + tu_pred.extend_from_slice(&pred_y[start..start + tw]); + } + let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); + read_inter_plane( + dec, + cdfs, + if reduced_tx_set { + TxbSet::Luma4Inter + } else { + TxbSet::Luma4InterSet1 + }, + scan4, + 0, + neighbours.around_mi(tu_mi, tw)[0], + 0, + y, + tu_px, + tu_py, + tw, + base_q_idx, + &tu_pred, + None, + Some(tu_skip_ctx), + )? + } else { + // The whole leaf as one `TX_8X4`/`TX_4X8` unit: it IS the + // plane block, so `get_txb_ctx_general` fixes `txb_skip_ctx` + // at 0 (`luma_skip_ctx: None`). + let start = row * MI * SIDE + col * MI; + read_inter_plane_rect( + dec, + cdfs, + if reduced_tx_set { + TxbSet::LumaRect8x4Inter + } else { + TxbSet::LumaRect8x4InterSet1 + }, + (tw, th), + SIDE, + 0, + neighbours.around_mi_rect(tu_mi, tw, th)[0], + 0, + y, + tu_px, + tu_py, + &pred_y[start..], + None, + None, + )? + }; + if idx == 0 { + // `av1_get_tx_type`: the group's one chroma unit scales + // back to luma (0, 0), i.e. the FIRST sub-block's first + // transform unit. + first_tx_type = tu_tx_type; + } + neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid); + (last_tw, last_th) = (tw, th); + } + neighbours.fill_lf_grid_rect( + lmi, + w_mi, + h_mi, + last_tw as u8, + last_th as u8, + ref_frame.max(LAST_FRAME), + ); + } + neighbours.record_mode_mi(rmi, cmi, w_mi, h_mi, DC_PRED); + neighbours.record_inter_rect_mi(lmi, w_mi, h_mi, skip, true, ref_frame, resolved_filter, false); + neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); + last_skip = skip; + } + // The group's single 4x4 chroma unit per plane, on the chroma-reference + // (second) sub-block's own skip flag. + const B4: usize = 4; + let mut pred_u = vec![0u16; B4 * B4]; + let mut pred_v = vec![0u16; B4 * B4]; + let (piece_w, piece_h) = if vert { (2usize, 4usize) } else { (4usize, 2usize) }; + for i in 0..2usize { + let Some((ref_frame, mv, h_filter, v_filter)) = piece[i] else { + continue; + }; + let (_, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (ox, oy) = if vert { + (cpx + i * piece_w, cpy) + } else { + (cpx, cpy + i * piece_h) + }; + let (dc, dr) = if vert { (i * piece_w, 0) } else { (0, i * piece_h) }; + for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] { + let mut buf = vec![0u16; piece_w * piece_h]; + mc::predict_with_filters( + &plane.data, + plane.width, + plane.true_width, + plane.true_height, + mv_to_q4(ox, mv.1, false), + mv_to_q4(oy, mv.0, false), + piece_w, + piece_h, + h_filter, + v_filter, + &mut buf, + ); + for row in 0..piece_h { + for col in 0..piece_w { + dst[(dr + row) * B4 + dc + col] = buf[row * piece_w + col]; + } + } + } + } + let (u_grid, v_grid) = if last_skip { + u.reconstruct_mc(cpx, cpy, B4, &pred_u, &vec![0i32; B4 * B4]); + v.reconstruct_mc(cpx, cpy, B4, &pred_v, &vec![0i32; B4 * B4]); + (vec![0i32; B4 * B4], vec![0i32; B4 * B4]) + } else { + let around = neighbours.around_mi(group_mi, 8); + let ug = read_inter_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], 0, u, cpx, cpy, B4, base_q_idx, + &pred_u, Some(first_tx_type), None, + )? + .0; + let vg = read_inter_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], 0, v, cpx, cpy, B4, base_q_idx, + &pred_v, Some(first_tx_type), None, + )? + .0; + (ug, vg) + }; + neighbours.record_uv_mode_mi(gr, gc, 2, 2, DC_PRED); + // `update_partition_context` writes `partition_context_lookup[subsize]` + // over the whole 8x8 span -- BLOCK_4X8's width above and height left, the + // same values [`decode_leaf_rect8`] writes for the intra shape. + for cell in 0..2usize { + neighbours.above_side_mi[gc + cell] = bw; + neighbours.left_side_mi[gr + cell] = bh; + } + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let bound_h = round_up_even(neighbours.mi_rows); + let bound_w = round_up_even(neighbours.mi_cols); + let u_state = neighbour_state(&u_grid); + let v_state = neighbour_state(&v_grid); + for cell in 0..2usize { + if cell < 2usize.min(bound_h.saturating_sub(gr)) { + neighbours.left[gr + cell][1] = u_state; + neighbours.left[gr + cell][2] = v_state; + } + if cell < 2usize.min(bound_w.saturating_sub(gc)) { + neighbours.above[gc + cell][1] = u_state; + neighbours.above[gc + cell][2] = v_state; + } + } + Ok(()) +} + +/// Stamps one sub-8x8 inter leaf into every mi cell of its true `w_mi`x`h_mi` +/// footprint (class: a rect block's grid span is its own, never a square guess). +fn grid_stamp_rect( + grid: &mut MiGrid, + mi_row: usize, + mi_col: usize, + w_mi: usize, + h_mi: usize, + ref_frame: i8, + mv: (i32, i32), + is_new_mv: bool, +) { + for dr in 0..h_mi { + for dc in 0..w_mi { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: true, + ref_frame, + ref_frame1: None, + mv1: None, + mv, + is_new_mv, + size: w_mi, + size_h: h_mi, + is_global_mv0: false, + is_global_mv1: false, + }, + ); + } + } +} + +/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block +/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s +/// exact symbol order: its own skip flag, intra/inter choice and (when +/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack +/// window, or (when intra) `Y_MODE`, then its own luma and two chroma +/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`], +/// same as [`decode_leaf8`]'s coefficient layer but with +/// motion-compensated prediction instead of intra prediction when inter. +/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's +/// skip/intra-inter context, overridden by `prev_leaf` exactly as +/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays +/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag +/// and intra/inter choice, for the next leaf or the caller's final +/// write-back. +#[allow(clippy::too_many_arguments)] +fn decode_inter_block8( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + grid: &mut MiGrid, + mi_cols: u32, + mi_rows: u32, + outer_at: (usize, usize), + leaf_mi: (usize, usize), + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + ref_y: &PlaneBuf, + ref_u: &PlaneBuf, + ref_v: &PlaneBuf, + other_refs: &RefSlots, + base_q_idx: u8, + scan8: &[u16], + scan4: &[u16], + allow_high_precision_mv: bool, + force_integer_mv: bool, + // lane-gmaffine r1: this frame header's own `global_motion` table (spec + // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table + // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code + // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing + // candidates with the gm mv (gm r6's root cause) and build a global + // warp prediction. + global_motion: &[ec_av1_syntax::WarpParams; 7], + // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit, + // for the leaf's own `read_mb_interp_filter` below. + enable_dual_filter: bool, + // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path + // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no + // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s + // context uses that same approximation. + reference_select: bool, + enable_masked_compound: bool, + // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is + // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate + // drops the `side` check entirely. + enable_interintra_compound: bool, + enable_jnt_comp: bool, + order_hint_bits: u32, + order_hint: u32, + ref_order_hints: [u32; 7], + // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this + // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either, + // so its `skip_mode` context reuses the same [`SUB`]-grid + // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot + // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation + // just above). + skip_mode_present: bool, + skip_mode_frame: [u8; 2], + // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see + // [`decode_inter_frame_tile_with_cdfs`]'s own doc. + reduced_tx_set: bool, + // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/ + // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus + // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour + // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own + // prediction is always `Regular` (documented corner-cut, `mc::predict` + // has no filter param), but an OBMC neighbour can be a real 16x16+ + // block that DID resolve a switchable filter. + interp_fixed: Option, + switchable_motion_mode: bool, + allow_warped_motion: bool, + // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a + // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16 + // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own + // `compound_ctx` local, just handed back instead of applied here (this + // fn's `neighbours` recording happens once for the whole straddling + // 16x16 block, after every leaf). + // lane-screen r2: see [`decode_inter_block`]'s own copy of this param -- + // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`- + // eligible (`bsize >= BLOCK_8X8`). + allow_screen_content_tools: bool, + // lane-inter8 r1: the leaf's mv stacks used to be built without the + // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`] + // one level up passed it -- it changes the candidate list and with it + // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read. + // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's + // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot + // 8x8-split gate). + sign_bias_table: &SignBiasTable, + // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which + // [`decode_inter_block`] one level up has always passed and this leaf + // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds + // fewer candidates here than in the reference decoder, which changes the + // mode contexts AND the number of `drl_mode` bits read (class parsed + // then discarded). + tpl_frame: Option<&TplFrameArgs>, + // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3), + // for the scaled-reference MC this leaf's own single-ref/compound/OBMC + // predictions take when a stored reference was coded at another width + // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param. + frame_width: usize, +) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option))> { + const LAST_FRAME: i8 = 1; + // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back + // so the caller stamps them into `Neighbours` instead of the `[3, 3]` + // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an + // OBMC blend that picks such a neighbour up feeds it to + // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) -- + // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]` + // on the intra and compound paths. + let mut leaf_filter_syms = [3u8; 2]; + // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's + // missing-candidate fallback both come from the frame's global motion + // evaluated at THIS block's centre (gm r6's root cause). + let gm_table = build_gm_mv_table( + global_motion, + leaf_mi.0, + leaf_mi.1, + 2, + 2, + allow_high_precision_mv, + force_integer_mv, + ); + /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`). + const SIZE_GROUP_8: usize = 1; + + let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); + let (cpx, cpy) = (px / 2, py / 2); + // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took + // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) -- + // read back by the luma residual read and the tail's neighbour/loop-filter + // bookkeeping. Always `false` outside a `TxMode::Select` inter frame. + let mut split8 = false; + const SIDE: usize = 8; + const CHROMA_SIDE: usize = 4; + + let (r, c) = outer_at; + // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's -- + // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the + // left column of a 16x16's second leaf ROW is the previous 16x16 block's + // bottom leaf, neither of which a SUB-grid slot can name. + let (rmi, cmi) = leaf_mi; + // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps + // its own 2x2-mi span into the bands right after it decodes (the caller's + // `record_inter_rect_mi`), so a plain mi read already names the correct + // neighbour, including one belonging to the previous 16x16 block. + let above_skip = neighbours.above_skip[cmi]; + let left_skip = neighbours.left_skip[rmi]; + let above_inter = neighbours.above_inter[cmi]; + let left_inter = neighbours.left_inter[rmi]; + let above_ref0 = neighbours.above_ref[cmi]; + let above_ref1 = neighbours.above_ref1[cmi]; + let left_ref0 = neighbours.left_ref[rmi]; + let left_ref1 = neighbours.left_ref1[rmi]; + let skip_mode_ctx = + usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]); + // Same two `inter_segment_id` positions as [`decode_inter_block`]; this + // leaf is always `BLOCK_8X8`, i.e. 2x2 mi. + inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true); + let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; + if skip_mode { SKIP_MODE_HITS.with(|c| c.set(c.get() + 1)); } @@ -19373,6 +20618,10 @@ fn decode_inter_block8( } let mode_for_tx; + // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the + // coded `uv_mode`), for the neighbour bands at the tail. An INTER leaf + // stores `UV_DC_PRED`, exactly as [`decode_inter_block`] one level up. + let mut uv_predict_mode = DC_PRED; let (luma_grid, u_grid, v_grid); let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None; // lane-inter8 r1: this leaf's own resolved references, handed back so the @@ -19405,21 +20654,24 @@ fn decode_inter_block8( let (ref0, ref1) = if skip_mode { (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8) } else { + // lane-interp3 r2 (class twin-functions-drift): this leaf + // passed a hard-coded `LAST_FRAME` for every inter + // neighbour -- the old "coarse LAST_FRAME-or-intra" + // approximation -- while the side bands have carried the + // neighbour's REAL reference per mi since lane-inter8 r2. + // Every `av1_collect_neighbors_ref_counts` vote below + // (`uni_comp_ref_p1`, `comp_ref`, `comp_bwdref`, ...) was + // therefore taken off the wrong CDF row. Same two args + // [`decode_inter_block`]'s own compound arm passes + // (`-1` when the band is unavailable is start_tile's / + // start_row's own reset value, so no `has_above` guard). read_compound_ref_frames( dec, cdfs, above_nbr, left_nbr, - if has_above && above_inter { - LAST_FRAME - } else { - -1 - }, - if has_left && left_inter { - LAST_FRAME - } else { - -1 - }, + above_ref0, + left_ref0, ) }; leaf_refs = (ref0, Some(ref1)); @@ -19600,6 +20852,58 @@ fn decode_inter_block8( ); } + // lane-interp3 r1: `read_mb_interp_filter` (libaom + // `decodemv.c` 1575, the tail of + // `read_inter_block_mode_info`) runs for EVERY inter block, + // compound included, right AFTER `read_compound_type` -- this + // leaf read no filter symbol at all, so a SWITCHABLE-filter + // stream lost one symbol (two under `enable_dual_filter`) at + // every compound 8x8 leaf, and the leaf recorded the `[3, 3]` + // "no filter" sentinel, which made a neighbouring OBMC block's + // `neighbour_filter` PANIC instead of blending. + // `av1_is_interp_needed` suppression terms for this arm: + // `skip_mode`, and `is_nontrans_global_motion` (mode + // GLOBAL_GLOBALMV with BOTH refs' models non-TRANSLATION) -- + // WARPED_CAUSAL cannot occur on a compound block. + let gm_nontrans_c = compound_mode == 6 + && global_motion[(ref0 - LAST_FRAME) as usize].model + != ec_av1_syntax::WarpModel::Translation + && global_motion[(ref1 - LAST_FRAME) as usize].model + != ec_av1_syntax::WarpModel::Translation; + // spec `get_ref_filter_type`, keyed on this block's ref0 and + // matching EITHER of the neighbour's references -- same shape + // as [`decode_inter_block`]'s compound arm. Same corner-cut as + // this leaf's single-ref arm below: the context comes from the + // enclosing 16x16's coarse slot. + let above_filter_ctx = if neighbours.above_ref[cmi] == ref0 + || neighbours.above_ref1[cmi] == Some(ref0) + { + neighbours.above_filter[cmi] + } else { + [3, 3] + }; + let left_filter_ctx = if neighbours.left_ref[rmi] == ref0 + || neighbours.left_ref1[rmi] == Some(ref0) + { + neighbours.left_filter[rmi] + } else { + [3, 3] + }; + let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( + dec, + cdfs, + interp_fixed, + enable_dual_filter, + gm_nontrans_c || skip_mode, + above_filter_ctx, + left_filter_ctx, + true, + ); + leaf_filter_syms = resolved_filter; + if interp_fixed.is_none() && !(gm_nontrans_c || skip_mode) { + COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1)); + } + let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?; let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?; let scale0 = mc::scale_factor(py0.width, frame_width); @@ -19609,6 +20913,54 @@ fn decode_inter_block8( SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1)); } + // lane-interp3 r2 (class twin-functions-drift): both slots + // used to be stamped `false`, while [`decode_inter_block`]'s + // compound arm computes libaom's PER-SLOT `is_global_mv_block` + // (blockd.h:421-429 -- mode GLOBAL_GLOBALMV, block >= 8x8 + // (always true for this leaf) and THAT slot's own gm model > + // TRANSLATION). A neighbour carrying the flag makes + // `setup_ref_mv_list` substitute the READER's global mv for + // the neighbour's stored one, so a cleared flag fed the next + // block's stack a stored mv where libaom has the global + // candidate -- a wrong mv stack, wrong mode contexts, and a + // desync one block later. + let is_globalmv_c = compound_mode == 6; + let is_global_mv0_c = is_globalmv_c + && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1; + let is_global_mv1_c = is_globalmv_c + && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1; + // lane-interp3 r3 (class twin-functions-drift, second + // instance): libaom applies `allow_warp`'s GLOBAL branch + // (`reconinter.c:33-55`, reached from `av1_init_warp_params` + // inside `build_inter_predictors_8x8_and_bigger`'s per-`ref` + // loop) to EVERY `is_global_mv_block` slot, compound + // included and independently of `motion_mode` -- the 16x16+ + // compound arm has done this since lane-cwarp r1, this leaf + // predicted both taps translationally, so a GLOBAL_GLOBALMV + // 8x8 compound leaf under a non-TRANSLATION model drifted by + // a few luma levels, growing away from the block origin. + // `force_integer_mv` short-circuits `av1_init_warp_params` + // before `allow_warp`; chroma is 4x4 here, below + // `av1_init_warp_params`'s own 8px per-plane bound, so only + // luma warps (same rule as this leaf's single-ref arm). + let leaf_compound_warp = |ref_frame: i8, eligible: bool| { + if eligible + && !force_integer_mv + && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid + { + crate::warp::global_warp_params( + global_motion[(ref_frame - LAST_FRAME) as usize].params, + ) + } else { + None + } + }; + let warp0_c = leaf_compound_warp(ref0, is_global_mv0_c); + let warp1_c = leaf_compound_warp(ref1, is_global_mv1_c); + if warp0_c.is_some() || warp1_c.is_some() { + COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1)); + COMPOUND_WARP_HITS_8.with(|c| c.set(c.get() + 1)); + } for dr in 0..2 { for dc in 0..2 { grid.set( @@ -19623,19 +20975,14 @@ fn decode_inter_block8( is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), size: 2, size_h: 2, - is_global_mv0: false, - is_global_mv1: false, + is_global_mv0: is_global_mv0_c, + is_global_mv1: is_global_mv1_c, }, ); } } mode_for_tx = 0; - // lane-av1comp corner-cut, matching this leaf's single-ref - // arm below (`mc::predict`'s own fixed-Regular default): - // `decode_inter_block8` never resolves a switchable filter, - // so both compound taps use `Regular` too. - use mc::InterpFilterKind::Regular; let mut inter0_y = vec![0i32; SIDE * SIDE]; mc::predict_compound_intermediate( &py0.data, @@ -19647,10 +20994,17 @@ fn decode_inter_block8( scale0, SIDE, SIDE, - Regular, - Regular, + h_filter, + v_filter, &mut inter0_y, ); + if let Some(wp) = &warp0_c { + crate::warp::warp_affine_compound( + wp, &py0.data, py0.true_width as i32, py0.true_height as i32, + py0.width as i32, &mut inter0_y, px as i32, py as i32, SIDE as i32, + SIDE as i32, SIDE as i32, 0, 0, + ); + } let mut inter1_y = vec![0i32; SIDE * SIDE]; mc::predict_compound_intermediate( &py1.data, @@ -19662,10 +21016,17 @@ fn decode_inter_block8( scale1, SIDE, SIDE, - Regular, - Regular, + h_filter, + v_filter, &mut inter1_y, ); + if let Some(wp) = &warp1_c { + crate::warp::warp_affine_compound( + wp, &py1.data, py1.true_width as i32, py1.true_height as i32, + py1.width as i32, &mut inter1_y, px as i32, py as i32, SIDE as i32, + SIDE as i32, SIDE as i32, 0, 0, + ); + } let mut pred_y = vec![0u16; SIDE * SIDE]; let mut diffwtd_mask_y = Vec::new(); let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type { @@ -19695,8 +21056,8 @@ fn decode_inter_block8( scale0, CHROMA_SIDE, CHROMA_SIDE, - Regular, - Regular, + h_filter, + v_filter, &mut inter0_u, ); let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; @@ -19710,8 +21071,8 @@ fn decode_inter_block8( scale1, CHROMA_SIDE, CHROMA_SIDE, - Regular, - Regular, + h_filter, + v_filter, &mut inter1_u, ); let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE]; @@ -19741,8 +21102,8 @@ fn decode_inter_block8( scale0, CHROMA_SIDE, CHROMA_SIDE, - Regular, - Regular, + h_filter, + v_filter, &mut inter0_v, ); let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; @@ -19756,8 +21117,8 @@ fn decode_inter_block8( scale1, CHROMA_SIDE, CHROMA_SIDE, - Regular, - Regular, + h_filter, + v_filter, &mut inter1_v, ); let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE]; @@ -19873,6 +21234,14 @@ fn decode_inter_block8( // so the 16x16 below a split block read partition ctx 0 // instead of 1 and mis-read PARTITION_SPLIT as NONE. neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); + // lane-cdef r1: ... and the CDEF skip band too. `apply_cdef`'s + // `is_8x8_block_skip` (libaom `cdef.c:29-38`) reads all four mi + // cells of the 8x8; this leaf wrote none of them, so a 64x64 + // whose bottom-right 16x16 is an all-skip 8x8-leaf group kept + // the PREVIOUS frame's flags and got filtered where libaom's + // dlist excludes it (3 luma samples on a 192x128 inter frame). + INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1)); + neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid( leaf_mi, 2, @@ -19931,6 +21300,17 @@ fn decode_inter_block8( &gm_table, tpl, ); + // lane-interp3 r2: same per-entry EC_STACK ladder + // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack + // diffs line for line against the oracle's. + 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 + ); + } + } let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; @@ -20452,12 +21832,62 @@ fn decode_inter_block8( this leaf with one; the >=16x16 arm decodes deltas)", )); } + // lane-uv8 r1: the delta'd angle decides the intra edge filter, and a + // directional luma mode is already legal on this leaf -- the arm + // passed a hardcoded `false` where [`decode_leaf8`] reads the + // mi-exact neighbour modes (`get_intra_edge_filter_type`, spec + // 7.11.2). + let (above_mode, left_mode) = + neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, neighbours.modes_above_left(r, c)); + let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); + // lane-uv8 r1: libaom `read_intra_block_mode_info` (decodemv.c:1198-1207) + // -- `uv_mode` over the CFL-allowed alphabet (`is_cfl_allowed`: a + // BLOCK_8X8 leaf is inside the 32x32 bound), then `read_cfl_alphas` + // for `UV_CFL_PRED`, then `angle_delta_uv` off the MAPPED uv mode's + // row (`get_uv_mode`, identity over `V_PRED..=D67_PRED`). Every value + // but `DC_PRED` was refused here, which is what blocked the low-cq + // CDEF arms and the 10-bit gates. let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); - if uv_mode != DC_PRED { - return Err(unsupported( - "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)", - )); + if std::env::var_os("EC_TRACE_MODE_STEP").is_some() { + eprintln!( + "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}", + leaf_mi.0, + leaf_mi.1, + ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get), + dec.debug_state().0 + ); + } + if (9..=12).contains(&uv_mode) { + SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); + INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.set(c.get() + 1)); + } + let alpha = if uv_mode == UV_CFL_PRED { + INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.set(c.get() + 1)); + Some(read_cfl_alphas(dec, cdfs)) + } else { + None + }; + let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); + INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.set(c.get() + 1)); + read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) + } else { + 0 + }; + 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)); } + // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED`. + uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; + // The CHROMA neighbour's own `uv_mode` decides the chroma edge filter + // strength (`get_intra_edge_filter_type`, reconintra.c:974), never the + // luma one -- same read [`decode_leaf8`] does. + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/ // `uv_mode` are both effectively `DC_PRED`-gated already on this // leaf (a nonzero `mode` still passes, but `uv_mode` is forced @@ -20469,7 +21899,10 @@ fn decode_inter_block8( "a block that actually uses a palette (Y) -- reconstruction is out of scope", )); } - if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 { + // lane-uv8 r1: `read_palette_mode_info` reads the UV symbol only + // when `uv_mode == UV_DC_PRED` (decodemv.c) -- unconditional here + // while every non-DC uv_mode was refused a few lines above. + if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 { return Err(unsupported( "a block that actually uses a palette (UV) -- reconstruction is out of scope", )); @@ -20484,14 +21917,39 @@ fn decode_inter_block8( // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied: // a real palette-Y block already returned above. let mut filter_intra = None; + // lane-uv8 r2: the oracle's `EC_ISTEP` ladder (`EC_TRACE_MODE_STEP`) + // prints `use_filter_intra` for an intra block inside an INTER frame + // and nothing else, so this leaf needs the same two lines for a + // range-ladder diff against it. + let ec_istep8 = std::env::var_os("EC_TRACE_MODE_STEP").is_some(); if mode == DC_PRED && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get) && let Some(class) = filter_intra_size_class(SIDE) - && dec.symbol(&mut cdfs.filter_intra[class]) != 0 { - FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1)); - INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1)); - filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); + let use_fi = dec.symbol(&mut cdfs.filter_intra[class]) != 0; + if ec_istep8 { + eprintln!( + "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={} rng={}", + leaf_mi.0, + leaf_mi.1, + u8::from(use_fi), + dec.debug_state().0 + ); + } + if use_fi { + FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1)); + INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1)); + let fi = dec.symbol(&mut cdfs.filter_intra_mode); + if ec_istep8 { + eprintln!( + "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}", + leaf_mi.0, + leaf_mi.1, + dec.debug_state().0 + ); + } + filter_intra = Some(fi); + } } mode_for_tx = mode; let (mi_row, mi_col) = leaf_mi; @@ -20550,31 +22008,34 @@ fn decode_inter_block8( &vec![0i32; SIDE * SIDE], None, filter_intra, - false, + smooth_neighbor, ); + // CfL's AC contribution is the luma this leaf just reconstructed, + // averaged over the 4x4 chroma block (`cfl_ac_q3`, spec 7.11.5). + let ac = alpha.map(|_| cfl_ac_q3(y, px, py, SIDE)); u.reconstruct( cpx, cpy, CHROMA_SIDE, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, - None, - false, + smooth_neighbor_uv, ); v.reconstruct( cpx, cpy, CHROMA_SIDE, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, - None, - false, + smooth_neighbor_uv, ); luma_grid = vec![0i32; SIDE * SIDE]; u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; @@ -20584,7 +22045,15 @@ fn decode_inter_block8( luma_grid = read_plane( dec, cdfs, - TxbSet::Luma8, + // lane-uv8 r3: an intra leaf inside an inter frame is + // `is_inter == 0` in `av1_get_ext_tx_set_type`, so its 8x8 + // luma reads the INTRA set -- seven-type + // `EXT_TX_SET_DTT4_IDTX_1DDCT` when `reduced_tx_set == 0`, + // five-type `EXT_TX_SET_DTT4_IDTX` when it is 1. Hardcoding + // the reduced set read the wrong ALPHABET (class + // [[wrong-alphabet-same-value]]) and desynced at the leaf's + // first `tx_type`. + txbset_for(8, reduced_tx_set), scan8, 0, around[0], @@ -20601,8 +22070,9 @@ fn decode_inter_block8( None, filter_intra, None, - false, + smooth_neighbor, )?; + let ac = alpha.map(|_| cfl_ac_q3(y, px, py, SIDE)); u_grid = read_plane( dec, cdfs, @@ -20611,8 +22081,8 @@ fn decode_inter_block8( 1, around[1], mode, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, u, cpx, @@ -20620,10 +22090,10 @@ fn decode_inter_block8( CHROMA_SIDE, TX4, base_q_idx, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, - None, - false, + smooth_neighbor_uv, )?; v_grid = read_plane( dec, @@ -20633,8 +22103,8 @@ fn decode_inter_block8( 2, around[2], mode, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, v, cpx, @@ -20642,10 +22112,10 @@ fn decode_inter_block8( CHROMA_SIDE, TX4, base_q_idx, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, - None, - false, + smooth_neighbor_uv, )?; } } @@ -20667,6 +22137,16 @@ fn decode_inter_block8( ) }); neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); + // lane-uv8 r1: this leaf never stamped a mode band at all, so the block + // below/right of it read whatever block last wrote the coarse [`SUB`] + // slot -- now that an intra leaf here can code a smooth/directional + // `uv_mode`, its chroma neighbours must see it (and an inter leaf must + // stamp `DC_PRED`, what libaom stores for a non-intra block). Same pair + // [`decode_leaf8`] writes, plus the coarse fallback slots. + neighbours.above_uv_mode[c] = uv_predict_mode; + neighbours.left_uv_mode[r] = uv_predict_mode; + neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode_for_tx); + neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); if let Some((left, above)) = saved_luma_ctx { for (cell, state) in left.into_iter().enumerate() { neighbours.left[leaf_mi.0 + cell][0] = state; @@ -20678,6 +22158,10 @@ fn decode_inter_block8( // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test). + // lane-cdef r1: the fall-through twin of the compound arm's skip-band + // write above -- `skip` is one flag for the whole 8x8 leaf (read at + // `decode.rs`'s `skip_ctx` site), `split8` only splits its transform. + neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid( leaf_mi, 2, @@ -21304,10 +22788,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // instead of silently decoding as SPLIT and desyncing. let part64 = match (has_cols, has_rows) { (true, true) => { + if std::env::var_os("EC_TRACE_PART").is_some() { eprintln!("EC_PART mi_row={} mi_col={} bsize=12 ctx={} rng={}", sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize, sb_ctx, dec.debug_state().0); } + let pre_rng = dec.debug_state().0; let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( - "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}", + "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p} pre_rng={pre_rng}", sb_r * SB_MI, sb_c * SB_MI ); @@ -21488,6 +22974,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( dec.debug_state().0 ); } + if std::env::var_os("EC_TRACE_PART").is_some() { eprintln!("EC_PART mi_row={} mi_col={} bsize=9 ctx={} rng={}", (r32 as usize), (c32 as usize), ctx32, dec.debug_state().0); } let p = dec.symbol(&mut cdfs.partition_w32[ctx32]); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( @@ -21600,6 +23087,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // inter leaves through the very same loop the // straddling case has always used. let part16 = if has_cols16 && has_rows16 { + if std::env::var_os("EC_TRACE_PART").is_some() { eprintln!("EC_PART mi_row={} mi_col={} bsize=6 ctx={} rng={}", (sr as usize*SUB_MI as usize), (sc as usize*SUB_MI as usize), ctx16, dec.debug_state().0); } let p = dec.symbol(&mut cdfs.partition_w16[ctx16]); if std::env::var_os("EC_AV1_TRACE").is_some() { let (rng, _) = dec.debug_state(); @@ -21910,12 +23398,104 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( for (mr, mc) in leaf_positions { let leaf_mi = (mr as usize, mc as usize); let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); + if std::env::var_os("EC_TRACE_PART").is_some() { eprintln!("EC_PART mi_row={} mi_col={} bsize=3 ctx={} rng={}", leaf_mi.0, leaf_mi.1, leaf_ctx, dec.debug_state().0); } let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); - if part8 != PARTITION_NONE { + if part8 == PARTITION_SPLIT { + // lane-intersub8: four BLOCK_4X4 inter + // sub-blocks, chroma once per 8x8. + decode_inter_sub8_split4( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + leaf_mi, + 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, + &scan4, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + tpl_frame.as_ref(), + reduced_tx_set, + frame_width as usize, + )?; + continue; + } + if part8 == PARTITION_HORZ + && std::env::var_os("EC_AV1_SUB8_HORZ").is_none() + { + // lane-intersub8 r4: the r3 desync IS + // root-caused and fixed (rect masked + // compound read `BLOCK_16X16`'s + // `compound_type`/`wedge_idx` CDF row + // for a 16x8 block); every mode-info + // range on the 28-arm transposed + // sweep now matches aomdec element + // for element. What is left is a + // POST-ENTROPY pixel band: 3 of 28 + // arms (8-bit cq32 sp9, 10-bit cq12 + // sp3, 10-bit cq16 sp3) differ by + // |d| <= 2 in luma only, scattered + // over the bottom-left corner + // (x < 48, y >= 112) from the first + // frame that references an 8x4 group + // -- a filter/reconstruction defect, + // not a desync. Still refused by name + // rather than shipped as silent pixel + // drift; `EC_AV1_SUB8_HORZ=1` decodes + // it for the r5 bisect. return Err(unsupported( - "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", + "an inter 8x8 HORZ partition (two BLOCK_8X4 inter leaves; entropy-exact now, but a measured sweep still drifts |d|<=2 in luma after the filters)", )); } + if part8 == PARTITION_VERT || part8 == PARTITION_HORZ { + // lane-intersub8 r3/r4: two BLOCK_8X4 + // (HORZ) / BLOCK_4X8 (VERT) inter + // leaves, chroma once per 8x8 on the + // second of them. + decode_inter_sub8_rect2( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + leaf_mi, + part8 == PARTITION_VERT, + 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, + &scan4, + allow_high_precision_mv, + force_integer_mv, + interp_fixed, + enable_dual_filter, + tpl_frame.as_ref(), + reduced_tx_set, + frame_width as usize, + )?; + continue; + } + // `partition_w8` is a 4-symbol alphabet + // (NONE/HORZ/VERT/SPLIT), all four handled. let ( skip, is_inter, @@ -22940,6 +24520,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. + if std::env::var_os("EC_OBMC").is_some() || std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_PICT idx={}", + PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) + ); + } dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; @@ -23310,6 +24897,30 @@ mod tests { /// always cleared to `None` by `record_inter`, so the next block's own /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it /// -- could never see a real compound neighbour). + /// lane-interp3 r1: a decoder must never abort the process on + /// stream-derived state. `neighbour_filter` used to feed the `[3, 3]` + /// "no filter recorded" sentinel straight into + /// `InterpFilterKind::from_switchable_symbol`, whose `panic!` ("...alphabet + /// is exactly 3 symbols") crashed on a real aomenc dual-filter + OBMC + /// stream. It now refuses by name; the real symbols still decode. + #[test] + fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() { + assert!( + neighbour_filter(None, [3, 3]) + .unwrap_err() + .to_string() + .contains("an OBMC neighbour whose interp filter was never recorded"), + "the [3, 3] sentinel must refuse by name, never panic" + ); + assert!(neighbour_filter(None, [3, 0]).is_err()); + let (h, v) = neighbour_filter(None, [0, 2]).expect("real symbols decode"); + assert_eq!(h, mc::InterpFilterKind::Sharp, "sym[1] is the horizontal kernel"); + assert_eq!(v, mc::InterpFilterKind::Regular, "sym[0] is the vertical kernel"); + let (h, v) = neighbour_filter(Some(mc::InterpFilterKind::Smooth), [3, 3]) + .expect("a fixed-filter frame never reads a symbol"); + assert_eq!((h, v), (mc::InterpFilterKind::Smooth, mc::InterpFilterKind::Smooth)); + } + #[test] fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() { let mut n = Neighbours::new(4, 4, 16, 16); diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 51718261..cf7376e1 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -25,7 +25,6 @@ #[cfg(test)] const CAPABILITY_CLAIMS: &[&str] = &[ "filter intra on a superblock-level HORZ/VERT strip (never expected -- av1_filter_intra_allowed_bsize caps at 32x32)", - "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)", ]; #[cfg(test)] @@ -33,7 +32,12 @@ 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)", + "an OBMC neighbour whose interp filter was never recorded (no switchable symbol for that block)", + "an intra 4x4 block inside an inter frame's sub-8x8 split (this decoder codes only inter 4x4 sub-blocks there)", + "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition (this decoder codes only inter sub-blocks there)", + "a sub-8x8 inter block under a scaled reference (superres, unimplemented)", + "an inter 8x8 HORZ partition (two BLOCK_8X4 inter leaves; entropy-exact now, but a measured sweep still drifts |d|<=2 in luma after the filters)", + "a COMPOUND_WEDGE mask on a non-square inter block (rect wedge codebook unimplemented)", "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 6c2e97f8..e719d3c9 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -5685,6 +5685,283 @@ mod tests { ); } + /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] + + /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with + /// 8x8 partitions and full chroma intra tooling + /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1 + /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8 + /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf + /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode` + /// symbol and refused every value but `DC_PRED` -- "this encoder never + /// writes one" was a claim, and this gate is what contradicts it. Hard- + /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth, + /// CfL, counted on THIS leaf only); an attempt that never produced one + /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP. + #[test] + fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() { + uv_mode_in_inter8_gate(8, 1); + } + + /// The 10-bit arm (both of the user's films are `yuv420p10le`). + #[test] + fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() { + uv_mode_in_inter8_gate(10, 1); + } + + /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round + /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must + /// be tile-relative. + #[test] + fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() + { + uv_mode_in_inter8_gate(8, 2); + } + + fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) { + let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})"); + 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, 8usize); + let mut refusals = Vec::new(); + let mut uncounted_exact = 0u32; + let mut totals = (0usize, 0usize, 0usize); + for attempt in 0..30u32 { + let seed = 42 + attempt; + // A zooming fractal with a hard CUT at frame 4 (`overlay` + // switching a second, unrelated fractal on): after the cut a block + // is unpredictable from the reference, which is what makes aomenc + // code INTRA blocks inside an inter frame. Chroma is NOT + // desaturated here (every sibling inter gate passes `hue=s=0`) -- + // real chroma detail is exactly what pushes the chroma RD off + // DC_PRED. `noise` carries its own explicit seed (lavfi + // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]). + let source = format!( + "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)',noise=alls=12:allf=t+u:all_seed={seed}", + 5.0 - f64::from(attempt) * 0.06, + 0.9 + f64::from(attempt) * 0.11 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }, + "-strict", + "-1", + "-t", + "0.32", + "-f", + "yuv4mpegpipe", + "-strict", + "-1", + "-", + ]) + .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) + ); + // A coarser quantiser is what pushes the chroma RD to a cheap + // non-DC mode on a small block; sweep 12..40 (the low end is what + // lane-cdef's cq12 arm needs). + let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7); + let depth_args: &[&str] = if bit_depth == 10 { + &["-b", "10", "--input-bit-depth=10"] + } else { + &[] + }; + let tiles = format!("--tile-columns={}", tile_columns - 1); + // The y4m goes through a FILE, not aomenc's stdin: this gate's + // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that + // is still being fed on stdin blocks writing its stdout and the + // test blocks writing its stdin -- a hard deadlock (measured + // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]). + // The path is PID-keyed (class [[pid-keyed-temp-path]]). + let y4m_path = std::env::temp_dir().join(format!( + "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m", + std::process::id() + )); + std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture"); + let child = Command::new(aomenc_path()) + .args(depth_args) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq, + "--cpu-used=0", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--kf-max-dist=9999", + "--kf-min-dist=9999", + "--threads=1", + "--row-mt=0", + &tiles, + "--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-cdef=0", + "--enable-restoration=0", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-ref-frame-mvs=0", + // Per-arm overrides go LAST (aomenc keeps the LAST + // occurrence of a repeated --enable-* flag). The three + // chroma intra tools this gate is about, plus the fences + // that keep the leaf's SIBLING refusals (its TX_4X4 + // split, a nonzero angle delta, sub-16 rect inter leaves) + // out of the way. + "--enable-cfl-intra=1", + "--enable-smooth-intra=1", + "--enable-paeth-intra=1", + "--enable-directional-intra=1", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-rect-partitions=0", + "--min-partition-size=8", + "--max-partition-size=32", + "--obu", + "-o", + "-", + ]) + .arg(&y4m_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + let out = child.wait_with_output().expect("aomenc failed to run"); + let _ = std::fs::remove_file(&y4m_path); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::intra_in_inter8_uv_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{name} decode failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + }; + let now = decode::intra_in_inter8_uv_hits(); + // class [[counter-from-refused-stream]]: per-attempt deltas, and + // only for an attempt that decoded to the end and is pixel- + // compared below. + let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2); + totals = ( + totals.0 + fired.0, + totals.1 + fired.1, + totals.2 + fired.2, + ); + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared; the counter only decides whether the + // attempt counts as firing. + // lane-uv8 r3: every one of the three chroma classes this gate + // exists for (directional, smooth/paeth, CfL) must fire on the + // SAME pixel-compared attempt -- a sum-nonzero predicate would + // pass on an attempt that only ever hit DC-adjacent CfL. + let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0; + if !counted { + uncounted_exact += 1; + refusals.push(format!( + "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \ + frame carried a non-DC uv_mode" + )); + } + 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} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \ + directional {}, smooth/paeth {}, CfL {}", + fired.0, fired.1, fired.2 + ); + 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 non-DC uv_mode on an 8x8 intra leaf in an inter frame \ + (totals dir/smooth/cfl {totals:?}):\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- @@ -6193,6 +6470,9 @@ mod tests { // aomenc silently codes one tile column and the arm is vacuous. extra: &[&str], width: usize, + // lane-interp3 r1: sequence length -- a compound block needs several + // already-coded references, which a 4-frame sequence never has. + frame_count: usize, ) { if !have_ffmpeg() { eprintln!("SKIP {name}: no ffmpeg"); @@ -6202,7 +6482,8 @@ mod tests { eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display()); return; } - let (height, frame_count) = (64usize, 4usize); + let height = 64usize; + let duration = format!("{:.2}", frame_count as f64 / 25.0); // A deterministic synthetic source with real motion (a static source // codes every inter frame as skip and never exercises the residual // path); bounded with `-t` (class gate-loader-slurps-whole-file). @@ -6215,7 +6496,7 @@ mod tests { "-i", &format!("mandelbrot=size={width}x{height}:rate=25"), "-t", - "0.16", + &duration, "-pix_fmt", if ten_bit { "yuv420p10le" } else { "yuv420p" }, // y4m calls 10-bit unofficial (same as the 10-bit key-frame @@ -6342,6 +6623,7 @@ mod tests { "whole-superblock inter PARTITION_NONE", &[], 64, + 4, ); } @@ -6356,6 +6638,7 @@ mod tests { "whole-superblock inter PARTITION_NONE", &[], 64, + 4, ); } @@ -6398,6 +6681,88 @@ mod tests { "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves", &["--tile-columns=1"], 128, + 4, + ); + } + + /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and + /// warped motion on. `read_mb_interp_filter` runs for every inter block + /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8 + /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol + /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which + /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on + /// his data, not a named refusal). The three hard asserts prove the flags + /// arrived: a compound 8x8 leaf that really read the filter, a block whose + /// two dual-filter directions DIFFER (impossible with dual filter off), + /// and an 8x8 OBMC blend. + // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full + // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL` + // element's msac RANGE matches the instrumented aomdec's line for line + // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in + // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was + // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of + // the real per-mi band, and the grid stamp cleared both per-slot + // `is_global_mv_block` flags. + // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED + // and this gate is GREEN. Third instance of the same twin-drift class: + // libaom applies `allow_warp`'s GLOBAL branch to every + // `is_global_mv_block` reference slot, compound included and independent + // of `motion_mode` (`av1_init_warp_params` inside + // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+ + // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm + // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound + // leaf under a non-TRANSLATION model drifted a few luma levels, growing + // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this + // round added to `decode.rs` diffs 325/325 lines against the instrumented + // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with + // zero differences. + #[test] + fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact"; + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); + return; + } + let before_dual = decode::dual_filter_diff_hits(); + let before_obmc = decode::obmc_hits_8(); + let before_cwarp8 = decode::compound_warp_hits_8(); + inter_sb_none_gate( + NAME, + false, + "8", + "16", + decode::compound8_filter_hits, + "a compound 8x8 leaf reading its own switchable interp_filter", + &[ + "--enable-dual-filter=1", + "--enable-obmc=1", + "--enable-warped-motion=1", + "--enable-onesided-comp=1", + ], + 64, + // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound + // block needs several coded references, so the sequence is longer + // than the other arms' 4 frames. + std::env::var("EC_INTERP3_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16), + ); + assert!( + decode::dual_filter_diff_hits() > before_dual, + "{NAME}: no block read two DIFFERENT dual-filter directions -- \ + --enable-dual-filter=1 did not arrive or aomenc declined it" + ); + assert!( + decode::obmc_hits_8() > before_obmc, + "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive" + ); + assert!( + decode::compound_warp_hits_8() > before_cwarp8, + "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \ + warp -- the r3 root-cause path never fired, so this stream no longer \ + proves it" ); } @@ -6412,6 +6777,7 @@ mod tests { "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves", &[], 64, + 4, ); } @@ -6435,6 +6801,7 @@ mod tests { "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves", &[], 64, + 4, ); } @@ -7133,14 +7500,169 @@ mod tests { }; 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" + "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", + "--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::decode::nocfl_uv_mode_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 hits = crate::decode::nocfl_uv_mode_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); + if hits == 0 { + // No 64-axis intra block in this stream: still compared + // (a mismatch here is a defect, never a pass), just not + // proof of this gate's shape. + carried_none += 1; + } + 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, hits={hits})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"); + } + if hits > 0 { + matched += 1; + total_hits += hits; + } + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ + attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \ + {carried_none} attempts carried none" + ); + assert!( + matched > 0 && total_hits > 0, + "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \ + no-CFL uv_mode alphabet was never exercised -- gate proved nothing \ + ({named_refusals} refusals, {carried_none} attempts carried none)" + ); + } + } + /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate + /// above. With `--enable-rect-partitions=0` the encoder codes only + /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD + /// eventually hands one whole 64x64 superblock of an INTER frame to an + /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must + /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's + /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it. + /// + /// Before the fix this decoder read the 14-symbol CFL alphabet there: the + /// same `DC_PRED` value, a different interval, and the tile desynced from + /// that block on. r1 measured the damage on the pinned 192x128 stream + /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact, + /// frame 4 luma 3540 samples wrong over exactly the last superblock + /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder + /// did not even report a mismatch, it reported an intra-rect-strip refusal + /// read out of the already-desynced stream (class `refusal-from-own-desync`; + /// aomdec's own partition histogram over that stream is rect-free). + /// After the fix the same stream is byte-exact on all 8 frames. + /// + /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE + /// really is a whole superblock), `--min-partition-size=16`, natural + /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames + /// of drift so a desync that survives one frame still fails here. Every + /// decode-order frame of every attempt is compared against ffmpeg, so a + /// mismatch of ANY shape fails; the gate never turns one into a SKIP. + #[test] + fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact() + { + const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_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, 8usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32); + let mut total_hits = 0usize; + for attempt in 0..4u32 { + // r1's pinned recipe is (start_scale 4.76, cq 55); the other + // three points move the detail level and the quantiser, which + // is what moves WHICH superblock the RD codes intra. + let start_scale = ["4.76", "3.20"][(attempt % 2) as usize]; + let cq = [55, 45][(attempt / 2) as usize]; + let duration = frame_count as f64 / 25.0; + let source = format!( + "mandelbrot=size={width}x{height}:start_scale={start_scale}:\ + end_scale=0.004:end_pts=8: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", "-", + "-v", "error", "-f", "lavfi", "-i", &source, "-vf", "hue=s=0", + "-t", &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1", + "-f", "yuv4mpegpipe", "-strict", "-1", "-", ]) .stdin(Stdio::null()) .stdout(Stdio::piped()) @@ -7156,14 +7678,22 @@ mod tests { 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", + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=1", "--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", - "--enable-rect-partitions=1", "--enable-ab-partitions=0", - "--enable-1to4-partitions=1", "--min-partition-size=32", - "--max-partition-size=64", + "--lag-in-frames=0", "--auto-alt-ref=0", + "--kf-min-dist=1000", "--kf-max-dist=1000", + "--enable-rect-partitions=0", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=64", "--enable-tx-size-search=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-filter-intra=0", + "--enable-smooth-intra=0", "--enable-paeth-intra=0", + "--enable-directional-intra=0", "--enable-angle-delta=0", + "--enable-cdef=0", "--enable-restoration=0", "--enable-palette=0", + "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0", "--obu", "-o", "-", "-", ]; let mut child = Command::new(aomenc_path()) @@ -7209,9 +7739,6 @@ mod tests { }; assert_eq!(frames.len(), frame_count); if hits == 0 { - // No 64-axis intra block in this stream: still compared - // (a mismatch here is a defect, never a pass), just not - // proof of this gate's shape. carried_none += 1; } for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { @@ -7226,14 +7753,14 @@ mod tests { } eprintln!( "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ - attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \ + attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \ {carried_none} attempts carried none" ); assert!( matched > 0 && total_hits > 0, - "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \ - no-CFL uv_mode alphabet was never exercised -- gate proved nothing \ - ({named_refusals} refusals, {carried_none} attempts carried none)" + "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \ + inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \ + gate proved nothing ({named_refusals} refusals, {carried_none} carried none)" ); } } @@ -7726,6 +8253,194 @@ mod tests { } } + /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four + /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane, + /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv, + /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape + /// was established BEFORE the code (class refusal-from-own-desync): the + /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3` + /// on this recipe's inter frames. + /// + /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only + /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on, + /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT + /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the + /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name + /// (lane-intersub8 r3: a measured sweep desyncs the block to its right). + #[test] + fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_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); + let mut fired = 0u32; + // lane-intersub8 r3: attempts 8..15 repeat the same schedule with + // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below + // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted + // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name. + let mut rect_fired = 0u32; + let mut refusals: Vec = Vec::new(); + let mut out_of_scope_mismatch = 0u32; + for bit_depth in [8u32, 10u32] { + for attempt in 0..16u32 { + let rect = attempt / 8; + let rect_arg = format!("--enable-rect-partitions={rect}"); + // lane-intersub8 r2, measured schedule (sweep of cq + // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths, + // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg + // rawvideo compare): sub-8x8 inter SPLIT groups fire at + // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) = + // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at + // those quantizers this recipe also carries a CDEF defect of + // another shape -- three luma samples of |d| = 1 on + // decode-order frames 3/4, zero sub-8x8 inter split groups, + // and the identical recipe re-encoded with `--enable-cdef=0` + // decodes all six frames exact. Deferred to a CDEF lane + // rather than hidden: cq 16..20 are all exact, so this gate + // is not selecting quantizers that hide a defect of its own + // shape. + let cq = [12, 14][(attempt % 2) as usize]; + let sp = 3 + ((attempt % 8) / 2) * 3; + 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='128+58*sin((X+N*{sp})/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 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", + "--lag-in-frames=0", "--enable-obmc=0", "--enable-tx-size-search=1", + // Per-arm overrides last (aomenc keeps the LAST occurrence). + "--enable-rect-partitions=0", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=4", + "--max-partition-size=16", + &rect_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(), + "{NAME}: aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::sub8_inter_split_hits(); + let before_rect = decode::sub8_inter_rect_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}" + ); + refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + let split_groups = decode::sub8_inter_split_hits() - before; + let rect_now = decode::sub8_inter_rect_hits(); + let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1); + let groups = split_groups + rect_groups; + 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 groups == 0 { + // Out of scope: no sub-8x8 inter split in this attempt. + if mismatched { + out_of_scope_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \ + sub-8x8 inter group -- another shape's defect" + ); + } + refusals.push(format!( + "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split" + )); + continue; + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \ + inter split groups)" + ); + assert_eq!(got.u, want.u, "U frame {i} ({bit_depth}-bit attempt {attempt})"); + assert_eq!(got.v, want.v, "V frame {i} ({bit_depth}-bit attempt {attempt})"); + } + fired += 1; + if rect_groups > 0 { + rect_fired += 1; + } + } + } + assert_eq!( + out_of_scope_mismatch, 0, + "{NAME}: attempts mismatched with no sub-8x8 inter group" + ); + assert!( + fired >= 2, + "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}", + refusals.join("\n") + ); + assert!( + rect_fired >= 2, + "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \ + inter leaf (4x8):\n{}", + refusals.join("\n") + ); + } + #[test] // 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 @@ -15863,6 +16578,151 @@ mod tests { ); } + /// lane-cdef r1: CDEF's per-8x8 skip band under sub-16x16 inter leaves. + /// + /// `apply_cdef` excludes an 8x8 luma unit whose four mi cells are all + /// `skip_txfm` (libaom `cdef.c:29-38 is_8x8_block_skip`, called from + /// `av1_cdef_compute_sb_list`'s dlist loop). `decode_inter_block8` -- the + /// leaf path `--min-partition-size=4` makes aomenc pick for a 16x16 group + /// -- wrote the loop-filter grid but never that skip band, so an all-skip + /// group kept the PREVIOUS frame's flags and got filtered where libaom + /// skips it (3 luma samples, decode-order frames 3 and 4 of the 192x128 + /// cq-8 stream below, at the frame's last 8x8 column). + /// + /// Both counters are hard asserts per compared attempt: `cdef_skipped_units` + /// proves the all-skip dlist exclusion was actually reached, and + /// `inter8_skip_band_hits` proves the 8x8 leaf path (the writer that used + /// to be missing) ran on the same stream. + #[test] + fn a_real_aomenc_stream_with_cdef_and_sub16_inter_leaves_decodes_pixel_exact() { + if !have_aomenc() { + return; + } + let (width, height, frames) = (192usize, 128usize, 6usize); + let mut refusals: Vec = Vec::new(); + let mut fired = 0u32; + for (depth, cq, sp) in [(8u32, 8u32, 3u32), (8, 10, 3), (8, 12, 6), (10, 8, 3), (10, 12, 6)] { + let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let src = format!( + "color=c=gray:s={width}x{height}:d=0.24:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p" + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &src, "-t", "0.24", "-pix_fmt", pix, + "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &format!("--cq-level={cq}"), + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + &format!("--bit-depth={depth}"), + &format!("--input-bit-depth={depth}"), + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--lag-in-frames=0", + "--enable-obmc=0", + "--enable-tx-size-search=1", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=4", + "--max-partition-size=16", + // Last occurrence of a repeated --enable-* flag wins + // (aomenc-last-flag-wins): CDEF stays ON, and the two + // counters below prove the filter really ran. + "--enable-cdef=1", + "--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 (depth={depth} cq={cq})" + ); + let stream = out.stdout; + let skipped_before = decode::cdef_skipped_units(); + let leaves_before = decode::inter8_skip_band_hits(); + let decoded = match decode_stream(&stream) { + Ok(f) => f, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.starts_with("unsupported: "), + "decode error that is not a named refusal \ + (depth={depth} cq={cq}): {msg}" + ); + refusals.push(format!("depth={depth} cq={cq}: {msg}")); + continue; + } + }; + assert_eq!(decoded.len(), frames, "frame count (depth={depth} cq={cq})"); + assert!( + decode::cdef_skipped_units() > skipped_before, + "no 8x8 CDEF unit was excluded by the all-skip rule \ + (depth={depth} cq={cq})" + ); + assert!( + decode::inter8_skip_band_hits() > leaves_before, + "no sub-16x16 inter leaf wrote the CDEF skip band \ + (depth={depth} cq={cq})" + ); + let reference = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames) + }; + for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() { + assert_eq!(ours.y, theirs.y, "luma frame {i} (depth={depth} cq={cq})"); + assert_eq!(ours.u, theirs.u, "U frame {i} (depth={depth} cq={cq})"); + assert_eq!(ours.v, theirs.v, "V frame {i} (depth={depth} cq={cq})"); + } + fired += 1; + } + // Three of the five arms land on OTHER open refusals (a non-DC chroma + // mode on an 8x8 inter leaf; inter partitions below 8x8) -- the two + // 8-bit cq 8/10 arms ARE the streams the defect was found on, and each + // hard-asserts both counters plus all six frames on all three planes. + assert!( + fired >= 2, + "fewer than 2 firing+pixel-exact attempts:\n{}", + refusals.join("\n") + ); + } + /// lane-sub8 r1: `--min-partition-size=4` on fine-detail noisy gradients /// at low cq reliably makes aomenc split an 8x8 block all the way to /// four `BLOCK_4X4` leaves (`PARTITION_SPLIT` below 8x8, spec diff --git a/lanes/cdef-r1.handoff.md b/lanes/cdef-r1.handoff.md new file mode 100644 index 00000000..a6479dec --- /dev/null +++ b/lanes/cdef-r1.handoff.md @@ -0,0 +1,66 @@ +# lane-cdef r1 -- HANDOFF (2 CDEF defects rooted, both fixed, gate GREEN; one residue open) + +Base: main 48b35ab. Suite unit `cdef-suite-1788330834.service` -> `$HOME/.cache/cdef-suite-r1.log` +(started at the turn cap; FIRST THING NEXT ROUND: `grep -E "^test result|FAILED" $HOME/.cache/cdef-suite-r1.log`). + +## Defect A -- per-8x8 CDEF skip band never written by the 8x8 inter leaf (charter hypothesis (a), variant) + +* Stream: `~/.cache/cdef-tmp/a0_8.obu`, sha256 `aa40f17f6e49eca2bb8c9d9ab99a175312134bdcf45c39b8a76b6757d8536751` + (hashed twice, identical), `~/.cache/cdef-tmp/gen.sh 8 3 8 a0_8.obu` = lane-intersub8's recipe, + 192x128, 6 frames, `--min-partition-size=4`, cq 8, 8-bit. +* Stage attribution: reconstruction and post-deblock are EXACT (`EC_AV1_POSTDEBLOCK_DUMP` ours vs + the instrumented aomdec: 0/24576 luma on decode-order frame 3); the 3 samples enter at CDEF. + NOTE: aomdec's `EC_AV1_PREFILT_DUMP` is ALREADY POST-DEBLOCK on this build (r_pre.fN == r_pd.fN + for 5 of 6 frames) -- ours is genuinely pre-deblock, so the two rungs are NOT the same stage. +* Root cause: `decode_inter_block8` (decode.rs, the leaf path `--min-partition-size=4` picks for a + 16x16 group) wrote `record_mi` + `fill_lf_grid` at both exits but NEVER `fill_skip_grid`. The + bottom-right 16x16 of decode-order frame 3 was therefore judged by the PREVIOUS frame's flags: + our 8x8 units at mi(28,46)/(30,46) read skip=false and were filtered, while libaom's + `is_8x8_block_skip` (cdef.c:29-38, called from `av1_cdef_compute_sb_list` cdef.c:40-71) excludes + an all-skip 8x8 from the dlist. Proof: a python model of `cdef_block.c` reproduces the reference + for all 16 units of the last column at (sec=1,damp=3) EXCEPT those two, where only "unfiltered" + matches; frame-3 fill log showed 0 of 95 skip fills covering mi(28,44)+16x16. +* Fix: `neighbours.fill_skip_grid(leaf_mi, 2, skip)` at both `decode_inter_block8` exits (compound + early return + fall-through), each bumping `INTER8_SKIP_BAND_HITS`. +* Before/after on the pinned stream: frames 3 and 4 had 3 luma samples |d|=1 each + ((189,116/120/124) and (186,116/120/124)); after, all 6 frames pixel-exact on Y/U/V. + +## Defect B -- CDEF direction search clamped at the crop edge instead of reading CDEF_VERY_LARGE + +* Stream: `~/.cache/golomb-tmp/s68.obu` (68x192, 5 frames, 8-bit, cq 35) -- lane-golomb r9's + deferred "straddle band". +* Root cause: `apply_cdef`'s `cdef_find_dir` closure clamped to `true_w-1`/`true_h-1`, but libaom + runs `cdef_find_dir` over `cdef_prepare_fb`'s buffer (cdef.c:249-256 `frame_boundary[RIGHT]` + fill, cdef_block.c:296-320), whose columns/rows past the mi-rounded extent are CDEF_VERY_LARGE. + With odd `mi_cols` (68 px -> 17 mi) the last 8x8 straddles, so var/`adjust_strength` differed. +* Fix: the direction search now reads the SAME padded `sample_y` the taps use (one line). +* Before/after: frame 1 luma 145 diffs -> **0**; all 5 frames luma exact. +* RESIDUE (open, NOT fixed): the same stream still differs in CHROMA from frame 1 on + (U/V 194/401/466/551 samples, |d| up to 6, spread over ~37 chroma 4x4 units, frame 0 exact). + Not attributable yet: `EC_AV1_DEBUG_SKIP_CDEF=1` cannot bisect inter frames (it also breaks the + reference frames), so the postdeblock rung is only valid for frame 0 here. Next step: dump + per-4x4 chroma CDEF params (uv pri/sec, damping-1, shared luma dir) for frame 1's first + differing unit and model it against `cdef_block.c` the way defect A was modelled + (`~/.cache/cdef-tmp/model.py` is a complete python port of cdef_block.c + find_dir + adjust). + +## Gate +`stream.rs::a_real_aomenc_stream_with_cdef_and_sub16_inter_leaves_decodes_pixel_exact` -- real +aomenc, `--min-partition-size=4 --enable-cdef=1` (last flag wins), 5 arms (8-bit cq 8/10/12, +10-bit cq 8/12), every decode-order frame compared on Y/U/V, hard asserts +`decode::cdef_skipped_units()` (an 8x8 unit really excluded by the all-skip rule) and +`decode::inter8_skip_band_hits()` (the leaf that used to write nothing) both grew per compared +attempt. 2 of 5 arms fire; the other 3 hit UNRELATED open refusals (non-DC chroma mode on an 8x8 +inter leaf; inter partition below 8x8) -- widening to 10-bit needs those lifted first. +`cargo test -p ec-av1 --lib cdef_and_sub16` -> ok, 1 passed / 0 failed. + +## Other +* `dump_stage`/`dump_stage16` wrote `.f0` for EVERY frame (each overwrote the last), so + `EC_AV1_POSTDEBLOCK_DUMP`/`POSTCDEF_DUMP` were unusable for per-frame bisection. Now indexed + per env var (`dump_stage_idx`), matching aomdec's own `.fN`. +* New rung `EC_AV1_CDEF_DBG=1`: one line per filtered 8x8 luma unit + (`EC_CDEF mi_r= mi_c= x= y= sidx= dir= var= t= pri= sec= damp=`). +* Class sweep for "per-8x8 map read at the top-left mi only under sub-8x8 partitions": the skip + grid is written by every OTHER leaf path (grep `fill_skip_grid`), `decode_inter_block8` was the + only writer missing; `is_skip_txfm` already gathers all four cells; the deblock/tx grid has a + `fill_lf_grid` at every one of those sites including both `decode_inter_block8` exits. +* Not done: `--tile-columns=1` arm on the new gate (COMMON neighbour-map rule) -- deferred. diff --git a/lanes/interp3-r1.report.md b/lanes/interp3-r1.report.md new file mode 100644 index 00000000..9b9906d0 --- /dev/null +++ b/lanes/interp3-r1.report.md @@ -0,0 +1,96 @@ +# lane-interp3 r1 -- the `switchable_interp` PANIC: the compound 8x8 leaf never read its filter + +## Root cause (cited) + +libaom `decodemv.c:1575` (`read_inter_block_mode_info`) calls `read_mb_interp_filter` +for **every** inter block, compound ones included, right after `read_compound_type`. +`decode_leaf8`'s COMPOUND arm (`crates/ec-av1/src/decode.rs`, the branch that returns at +the old line 19589) called `resolve_interp_filter` **not at all**: it predicted both taps +with a hard-coded `Regular` and returned the `[3, 3]` "no filter recorded" sentinel as the +leaf's `leaf_filter_syms`. Two consequences, both real on his data: + +1. **Entropy**: on a `SWITCHABLE`-filter frame one symbol (two under `enable_dual_filter`) + is left unread at every compound 8x8 leaf -- silent desync. +2. **Crash**: the sentinel is stamped into `Neighbours::above_filter`/`left_filter`, and a + neighbouring OBMC block's `neighbour_filter` fed it to + `mc::InterpFilterKind::from_switchable_symbol`, whose `panic!("switchable_interp's + alphabet is exactly 3 symbols")` aborted the process. That is the panic lane-r14 r3 + flagged (its `--enable-dual-filter=1 --enable-obmc=1` 192x128 cq30 stream). The same + shape was already fixed once for the SINGLE-ref 8x8 leaf (lane-gmaffine r3, decode.rs + ~21509 comment) -- the compound arm was the surviving sibling instance. + +## Changed + +- `crates/ec-av1/src/decode.rs` (compound 8x8 leaf, after the `comp_group_idx`/ + `compound_idx` reads): reads `interp_filter` in libaom's order, with `get_ref_filter_type` + neighbour contexts keyed on `ref0` and `is_compound = true`; suppression term is + `skip_mode || is_nontrans_global_motion` (GLOBAL_GLOBALMV + both refs' models non- + TRANSLATION; WARPED_CAUSAL cannot occur on compound). The 12 `predict_compound_intermediate` + taps now use the resolved `h_filter`/`v_filter` instead of `Regular`. +- `crates/ec-av1/src/decode.rs` `neighbour_filter`: returns `Result`; the `[3, 3]` sentinel + is now the named refusal `an OBMC neighbour whose interp filter was never recorded (no + switchable symbol for that block)` -- **never a panic**. Both OBMC call sites `?` it. +- `crates/ec-av1/src/decode.rs`: counters `DUAL_FILTER_DIFF_HITS` (a block whose two + dual-filter directions differ -- impossible with dual filter off) and + `COMPOUND8_FILTER_HITS`. +- `crates/ec-av1/src/refusal_inventory.rs`: the new refusal listed (inventory test green). +- `crates/ec-av1/src/stream.rs`: `inter_sb_none_gate` takes a `frame_count` + (4 frames never code a compound block); new gate + `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` + (`--enable-dual-filter=1 --enable-obmc=1 --enable-warped-motion=1 --enable-onesided-comp=1` + on the `--min-partition-size=8 --enable-ab-partitions=0 --enable-1to4-partitions=0` + recipe, every frame compared Y/U/V vs ffmpeg, hard asserts on all three counters). +- `crates/ec-av1/src/decode.rs` test + `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking`. + +## Gate: RED, `#[ignore]`d with the measurement, not deleted + +`EC_INTERP3_FRAMES=4` -> aomenc codes no compound block, stream decodes. +From 5 frames on it does, and the decode stops at a refusal that the recipe makes +impossible: `an inter 16x16-level AB or 1:4 partition` WITH this round's filter read, and +`an inter partition below 8x8` WITHOUT it (measured by ablating the read behind a temporary +env switch, since removed). `--enable-ab-partitions=0 --enable-1to4-partitions=0 +--min-partition-size=8` cannot emit either -- so both are our own desync +(class `refusal-from-own-desync`): the compound 8x8 leaf carries at least one more +missing/misplaced symbol beyond the interp filter. The fix is therefore **necessary but not +sufficient** and is not claimed as pixel-proven. + +EVIDENCE: $HOME/.cache/interp3-suite-r1.log | `cargo test -p ec-av1 --lib -j3` under a +systemd user unit, MemoryMax=10G | totals below +EVIDENCE: gate run `EC_INTERP3_FRAMES=5..16 cargo test -p ec-av1 --lib a_real_aomenc_dual_filter_obmc_8x8` with and without the new read | 6 encodes x 2 arms | refusal string differs per arm (AB/1:4 vs below-8x8), 0 frames compared either way -- gate RED, ignored +EVIDENCE: `cargo test -p ec-av1 --lib an_obmc_neighbour_with_no_recorded` | direct call with the `[3, 3]` sentinel | 1 passed: refuses by name, no panic + +## Panic sweep of the decode path (charter clause) + +`neighbour_filter` was the only `panic!` reachable from a *stream-derived value* on the OBMC +path; converted. The rest of `decode.rs`'s 57 `panic!/unreachable!/unwrap/expect` sites, +inspected: `2733, 11268, 11617, 11636, 11683, 11996, 12015, 12052, 13820, 13998, 15225, +15533` are `unreachable!` on values a CDF alphabet or an earlier refusal already bounds +(cannot fire on any stream); `5238, 5282, 6043, 6110, 7310, 7311, 7777, 7778, 10479, 10535, +10679, 10888` are `unwrap/expect` on this decoder's own just-built state; everything above +line 22700 is inside `#[cfg(test)]`. Two remain flagged, not converted (they need a `Result` +in a counter/table helper and no stream is known to reach them): +`decode.rs:2486` `panic!("ref_hits: no per-reference counter for ref_frame {other}")` and +`decode.rs:3247` `panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry")`. +`mc.rs:203`/`:220` stay as documented invariants -- both callers now check first. + +## Residue + +- fix-now(next round): the remaining compound-8x8 desync. Method: `EC_TRACE=1` aomdec range + ladder against ours on the FIRST compound leaf of frame 5 of the gate's stream, comparing + msac RANGE element by element (never `tell()`). +- deferred(needs that fix): the 10-bit arm of the new gate, and the counter-proving + pixel-exact claim. + +## Suite + +`systemd-run --user --unit=interp3-suite-r1 -p MemoryMax=10G --same-dir bash -lc 'EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-interp3 nice -n 10 cargo test -p ec-av1 --lib -j3 > $HOME/.cache/interp3-suite-r1.log 2>&1'` + +**372 passed; 0 failed; 33 ignored; 1208.18s** (main's 371/0/32 plus this round's +`an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking`, plus the new +gate ignored). Every OBMC/compound sibling gate green on this tip, including +`a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, +`a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact`, +`a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`, +`a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact` +and both `..._8x8_leaf_split_...` arms -- the entropy change did not move any of them. diff --git a/lanes/interp3-r2.handoff.md b/lanes/interp3-r2.handoff.md new file mode 100644 index 00000000..85064061 --- /dev/null +++ b/lanes/interp3-r2.handoff.md @@ -0,0 +1,48 @@ +# lane-interp3 r2 HANDOFF (turn cap) + +Tip: see `git log -1` on branch `lane-interp3` (r2 fix commit + report commit). +Base: r1 b702853 + `git merge main` (4eff3a1, lane-mvtwin mvstack fixes). Merge touched +only mvstack.rs / stream.rs / lanes/mvtwin-r1.report.md; cdf.rs untouched both sides. + +## Phase table + divergences: see lanes/interp3-r2.report.md (complete, 17 rows) +Two divergences found in `decode_inter_block8`'s compound arm, both FIXED: +1. decode.rs:19151 `read_compound_ref_frames` got a hard-coded `LAST_FRAME` (or -1) + for the above/left neighbour reference instead of the real per-mi bands + (`above_ref0`/`left_ref0`, what `decode_inter_block` passes) -> every + `av1_collect_neighbors_ref_counts` vote off the wrong CDF row. +2. decode.rs:19410 the leaf's grid stamp cleared BOTH per-slot `is_global_mv_block` + flags; now computed as libaom blockd.h:421-429 (mode GLOBAL_GLOBALMV + that slot's + gm model > TRANSLATION). +Also added: decode.rs:19726 per-entry `EC_STACK` print in the leaf's SINGLE-ref arm. + +## Ladder (EC_TRACE_MODE=1, ours vs instrumented aomdec, RANGE never tell) +- Before fix 1, frames=5 stream: first divergence at compound leaf mi (10,2) -- + both enter the mode info at rng=61097; aomdec reads refs (LAST,GOLDEN) mode + NEAREST_NEARESTMV -> rng 49516; ours read (LAST,LAST2) NEW_NEWMV -> rng 50496. +- Before fix 2, frames=16 stream: first divergence at single-ref 8x8 leaf mi (8,8), + entry rng=43099 both; aomdec stack = [(-1,-1) w648, (0,0) w644] (2 entries), + ours = [(0,0) w644, (2,-4) w644, (-1,-1) w4] (3) -- the extra (2,-4) is the + neighbour's stored mv1 where libaom substitutes the reader's global mv. +- AFTER both fixes: 570 vs 570 mode elements, `diff` EMPTY, no refusal. + +## Gate state +`a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` still +`#[ignore]`d (ignore text updated with this measurement). Now RED on RECONSTRUCTION, +not entropy: luma-only, frames 0-6 byte-exact, frame 7 = 36 Y wrong (max |d| 5, first +(42,15), the 8x8 leaf at mi (10,4), 1-px spill across its left/bottom deblock edges), +propagating to 222 Y + 4 U + 1 V at frame 15. +Artifacts: scratchpad .../{pin.obu (5 frames), pin16.obu==mm.obu (16), aom16.trace, +ours16e.trace, mm.aom.yuv, mm.ours.yuv, aom.obmc}. + +## Suite +Unit `interp3-suite-r2-1788327820.service`, log `$HOME/.cache/interp3-suite-r2.log`. +Armed at the r2 fix commit; still running at the cap -- read the log's `test result:` +line, do not re-run blindly. + +## EXACT NEXT STEP +Build an `EC_OBMC` emitter in decode.rs (both OBMC call sites) printing the oracle's +own byte format -- `EC_OBMC above|left mi=(r,c) wh=(WxH) rel=%d op=%d nbmv=(y,x) +nbref=%d nbbsize=%d filt=%d` -- then diff it against the 325 lines of +`EC_OBMC=1 aomdec --rawvideo -o /dev/null mm.obu`, starting at `mi=(10,4)`. The leaf +now records a REAL filter pair where it used to record the [3,3] sentinel, so an OBMC +blend over a compound neighbour is the first suspect for the residue. diff --git a/lanes/interp3-r2.report.md b/lanes/interp3-r2.report.md new file mode 100644 index 00000000..9e5333bc --- /dev/null +++ b/lanes/interp3-r2.report.md @@ -0,0 +1,88 @@ +# lane-interp3 r2 -- the compound 8x8 leaf's ENTROPY desync is closed (two twin drifts); gate now RED on a small luma reconstruction residue + +Base: b702853 (r1) + `git merge main` (4eff3a1, brings lane-mvtwin's mvstack fixes). +Merge diffstat: `crates/ec-av1/src/mvstack.rs`, `crates/ec-av1/src/stream.rs`, +`lanes/mvtwin-r1.report.md` only -- `cdf.rs` untouched by either side (byte-compare +trivially clean), no fixtures churn, no conflicts. + +## Phase table -- libaom `read_inter_block_mode_info` (decodemv.c ~1400-1600) + +`IB` = `decode_inter_block` compound arm, `L8` = `decode_inter_block8` compound arm +(both in `crates/ec-av1/src/decode.rs`; line numbers are this commit's). + +| # | phase (libaom) | IB | L8 | verdict | +|---|---|---|---|---| +| 1 | `skip_mode` (ctx = above+left skip_mode) | 16363 | 19087 | matches | +| 2 | `skip` | 16375 | 19093 | matches | +| 3 | cdef / delta_q / delta_lf | 16377-16382 | (16x16 slot's, per this fn's doc) | matches (leaf never a delta root) | +| 4 | `is_inter` (`intra_inter_ctx`) | 16389 | 19105 | matches | +| 5 | `comp_mode` (`read_comp_mode`, ref-count ctx) | 16475 | 19147 | matches (`skip_mode \|\| (reference_select && ...)` vs `reference_select \|\| skip_mode` then `skip_mode \|\| ...` -- same predicate) | +| 6 | `read_ref_frames`: `comp_ref_type`, uni/bi trees | 16480 | 19151 | **DIFFERENT -> FIXED**: L8 passed a hard-coded `LAST_FRAME` (or `-1`) as the above/left reference; IB passes the real `neighbours.above_ref[cmi]`/`left_ref[rmi]` | +| 7 | `av1_find_mv_refs` (`find_mv_stack_compound`, sign bias + gm table + tpl) | 16519 | 19195 | matches (L8's doc comment claiming "no sign-bias table nor tpl_frame" is stale -- both are passed) | +| 8 | `compound_mode` CDF (`COMPOUND_MODE_CTX_MAP`) | 16532 | 19205 | matches | +| 9 | drl + `read_mv` per ref (`assign_compound_mv`, has_nearmv/have_newmv rules) | 16537 | 19226 | matches (one shared fn) | +| 10 | `interintra` | n/a compound | n/a | matches (never read on compound -- correct) | +| 11 | `read_motion_mode` | n/a compound | n/a | matches (`has_second_ref` -> SIMPLE_TRANSLATION) | +| 12 | `comp_group_idx` (neighbour ctx) | 16675 | 19263 | matches | +| 13 | `compound_type` -> wedge idx+sign / diffwtd `mask_type` | 16710 | 19279 | matches | +| 14 | `compound_idx` (distance-weight ctx) | 16936 | 19310 | matches | +| 15 | `read_mb_interp_filter` (after `read_compound_type`; suppressed by `skip_mode` / `is_nontrans_global_motion`; `get_ref_filter_type` on ref0 matching EITHER neighbour ref) | 16980 | 19383 | matches (landed r1) | +| 16 | tail: grid `MiInfo` stamp -- per-slot `is_global_mv_block` | 16577+16660 | 19424 | **DIFFERENT -> FIXED**: L8 stamped `is_global_mv0/1 = false` unconditionally | +| 17 | tail: `record_inter_rect_mi` + `record_compound_ctx_rect_mi` (skip/skip_mode/inter/ref/ref1/filter/comp_group_idx/compound_idx bands) | 18870 | via `compound_ctx8` + caller, 19000 | matches -- verified by the range ladder staying exact for the whole stream | + +Root causes 6 and 16 are the round's fix. Both are the same class the charter named +(twin functions drift), and both are invisible to any value-only check: (6) changes a +CDF ROW, (16) changes a LATER block's mv-stack composition. + +## Changed (path:line) + +- `crates/ec-av1/src/decode.rs:19151` -- `read_compound_ref_frames` now gets + `above_ref0`/`left_ref0` (the per-mi bands the leaf already reads at 19078-19081) + instead of `LAST_FRAME`/`-1`. `-1` on an unavailable band is `start_tile`'s / + `start_row`'s own reset value, so no `has_above` guard is needed (IB has none either). +- `crates/ec-av1/src/decode.rs:19410` -- the leaf's grid stamp computes libaom's + per-slot `is_global_mv_block` (mode `GLOBAL_GLOBALMV`, that slot's gm model > + TRANSLATION; the >= 8x8 size predicate is always true for this leaf). +- `crates/ec-av1/src/decode.rs:19726` -- the leaf's SINGLE-ref arm prints the same + per-entry `EC_STACK` ladder `decode_inter_block`'s single-ref arm prints (this is + the instrument that isolated cause 16). +- `crates/ec-av1/src/stream.rs:6315` -- the gate's ignore reason + comment replaced + with this round's measurement (entropy closed, pixel residue open). + +## Gate: still RED, still `#[ignore]`d -- but on a different, much smaller failure + +`a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` +(`--enable-dual-filter=1 --enable-obmc=1 --enable-warped-motion=1 +--enable-onesided-comp=1`, `--min-partition-size=8 --enable-ab-partitions=0 +--enable-1to4-partitions=0`, 16 frames, 64x64). + +- r1: decode STOPPED at a bogus refusal at frame 5 (0 frames ever compared). +- r2: the whole 16-frame stream parses; the failure is now + `frame 7 mismatch vs ffmpeg` -- a reconstruction residue, luma-only, + |delta| <= 8, first sample (42,15) inside/around the 8x8 leaf at mi (10,4), + spilling 1 px across that leaf's left and bottom deblock edges. It grows by pure + propagation to 222 Y + 4 U + 1 V samples at frame 15 (chroma stays exact until + frame 14). + +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/{aom16.trace,ours16e.trace} | `EC_TRACE_MODE=1 aomdec --rawvideo` and `EC_TRACE_MODE=1 decode_probe` on the pinned 16-frame stream, `diff` of every `EC_MODE`/`EC_MODE_VAL` line (mi + msac RANGE, never tell) | 570 vs 570 elements, diff EMPTY, no refusal (before the fix: ours stopped at 347 elements, first RANGE divergence at the 8x8 leaf mi (8,8), stack 3 entries vs libaom's 2) +EVIDENCE: same dir, `pin.obu` (EC_INTERP3_FRAMES=5) | ladder before fix 1 | ours read refs (LAST,LAST2) + NEW_NEWMV at leaf mi (10,2) where aomdec reads (LAST,GOLDEN) + NEAREST_NEARESTMV -- the two differ only in a CDF row of `uni_comp_ref` +EVIDENCE: same dir, `mm.{aom,ours}.yuv` | `aomdec --rawvideo` vs `decode_probe` on the pinned mismatch stream, per-frame per-plane sample compare | frames 0-6 byte-exact; frame 7: 36 Y / 0 U / 0 V wrong, max |delta| 5; frame 15: 222 Y / 4 U / 1 V, max |delta| 8 + +## Refusals + +None lifted this round (the r1 refusal `an OBMC neighbour whose interp filter was +never recorded` stays; `refusal_inventory` unchanged). Two refusals this stream used +to hit -- `an inter 16x16-level AB or 1:4 partition` and `an inter partition below +8x8` -- were our own desync (class refusal-from-own-desync) and no longer fire on it. + +## Residue + +- fix-now(next round): the luma reconstruction residue above. First suspect is the + OBMC blend over a COMPOUND neighbour -- the leaf now records a real filter pair + where it used to record the `[3,3]` sentinel, and the oracle's `EC_OBMC` rung + prints `nbmv`/`nbref`/`nbbsize`/`filt` per neighbour while THIS decoder has no + `EC_OBMC` emitter at all. Build that emitter first (instrument-before-excuse), then + diff the 325 oracle `EC_OBMC` lines of `mm.obu` against ours. +- deferred(needs that fix): the gate's counter asserts (compound-8x8 filter reads, + dual-filter differing directions, 8x8 OBMC blends) are never reached while the + pixel compare fails first; the 10-bit arm; a `--tile-columns=1` arm. diff --git a/lanes/interp3-r3.handoff.md b/lanes/interp3-r3.handoff.md new file mode 100644 index 00000000..0c238b81 --- /dev/null +++ b/lanes/interp3-r3.handoff.md @@ -0,0 +1,88 @@ +# lane-interp3 r3 HANDOFF (turn cap) -- root cause FOUND and FIXED, suite still running + +Tip: `f36be26` on branch `lane-interp3` (fix) + this handoff/report commit. + +## Suite state +- r2 suite (unit `interp3-suite-r2-1788327820.service`, log `$HOME/.cache/interp3-suite-r2.log`), + armed at the r2 commit, FINISHED: + `test result: ok. 378 passed; 0 failed; 34 ignored; 0 measured; 0 filtered out; finished in 742.50s` +- r3 suite FINISHED GREEN at f36be26 (unit `interp3-suite-r3-1788328778.service`): + `test result: ok. 379 passed; 0 failed; 33 ignored; 0 measured; 0 filtered out; finished in 1031.33s` + (old text below is superseded) +- r3 suite armed at f36be26: unit `interp3-suite-r3-1788328778.service`, + log `$HOME/.cache/interp3-suite-r3.log`. At the cap it had 258 `... ok`, ZERO + `FAILED`/`panicked`, no `test result:` line yet. READ THAT LINE, do not re-run + blindly, then paste it into `lanes/interp3-r3.report.md` where + `EVIDENCE: SUITE_LINE_PLACEHOLDER` sits. + +## Stage attribution of the frame-7 residue (done FIRST, as chartered) +`EC_AV1_PREFILT_DUMP` on both decoders over the pinned 16-frame stream +(`.../scratchpad/mm.obu`), byte compare per decode-order frame: +frames 0-6 identical, frame 7 = 35 differing luma bytes, 8..15 grow to 224. +=> PRE-FILTER, i.e. prediction/reconstruction, never the loop filter/CDEF/LR. +All 35 sit in luma rows 42-47, cols 16-23, i.e. the block at mi (10,4); +rows 40-41 of that same block are EXACT and the error grows downward. + +## What the OBMC comparison actually said (emitter built, class swept, CLEAN) +Before writing the emitter, the hand comparison against libaom found NO mismatch: +`overlappable_above`/`overlappable_left` stepping and `max_neighbor_obmc` +(`{0,1,2,3,4,4}`, 8x8 -> 1 per pass) match `obmc.h:20-55`; overlap sizes +(4 luma rows above / 4 luma cols left at 8x8, chroma 2) match +`build_obmc_inter_pred_{above,left}`; `av1_skip_u4x4_pred_in_obmc` chroma-above +skip matches; `obmc_mask_1/2/4/8/16/32` are byte-identical to +`reconinter.c:752-765`; OBMC never warps (`if (!build_for_obmc) av1_init_warp_params`). +One real divergence candidate was left un-ported and is still a documented +corner-cut, not a defect on this content: `obmc.h`'s `mi_step == 1` 4-wide pair +merge, and libaom's `op_mi_size = AOMMIN(xd->width, mi_step)` which can exceed +the remaining span while ours clips with `.min(end_col - col)` (only reachable +for a 2nd neighbour with a wide step). + +Emitter: `decode.rs:15806` `ec_obmc_bsize()` + `decode.rs:15828` `ec_obmc_trace()`, +called at both passes in `obmc_blend`. Format is aomdec's own bytes: +`EC_OBMC above|left mi=(r,c) wh=(WxH) rel=N op=N nbmv=(y,x) nbref=N nbbsize=N filt=N` +(`filt` = packed `interp_filters.as_int` = `y | (x << 16)`). +`diff` of the 325 oracle lines vs our 325: EMPTY. OBMC is exonerated. + +Also added `decode.rs:14682` + `:22658` `EC_PICT idx=` (decode-order frame +marker under `EC_OBMC`/`EC_TRACE_MODE`). REQUIRED: the marker prints AFTER the +frame's own trace lines, so `awk` must count markers seen, not read the value on +the preceding line -- attributing by the preceding `EC_PICT` value is off by one +and cost part of this round. + +## Hypotheses ruled out (each by measurement) +- OBMC neighbour fields / masks / overlap: 325/325 identical lines (above). +- Frame 7 has NO OBMC block at mi (10,4) at all -- it is COMPOUND + (SIMPLE_TRANSLATION), so the r2 handoff's "OBMC over a compound neighbour" + suspect could not have been it. +- Residual/entropy: r2's range ladder is exact end to end; `EC_MCDUMP` (a + temporary rung, removed before commit) showed aom_recon - our_residual + reproduces our PREDICTION in rows 40-41 and diverges below => prediction. +- Wrong dual-filter x/y assignment: a swap would err in every row, not only the + lower ones. + +## Root cause (FIXED, gate GREEN) +`decode_inter_block8`'s COMPOUND arm predicted BOTH taps translationally. +libaom applies `allow_warp`'s GLOBAL branch to every `is_global_mv_block` +reference slot -- compound included, independent of `motion_mode` +(`av1_init_warp_params` inside `build_inter_predictors_8x8_and_bigger`'s per-`ref` +loop; `reconinter.c:33-55`). `decode_inter_block`'s compound arm has done this +since lane-cwarp r1 (`decode.rs:16691`). Third twin-functions-drift instance in +this lane. Frame 7 mi (10,4): GLOBAL_GLOBALMV, ref0=GOLDEN mv (0,0), +ref1=ALTREF mv (-3,4), comp_group_idx=1. +Fix: `decode.rs:19513` (`leaf_compound_warp`, `warp0_c`/`warp1_c`), +`decode.rs:19596`/`:19618` (`warp_affine_compound` per luma tap; chroma is 4x4, +below `av1_init_warp_params`'s 8px per-plane bound, so it stays translational). +Counter `COMPOUND_WARP_HITS_8` / `compound_warp_hits_8()` at `decode.rs:1786`. +After the fix ALL 16 decode-order frames are byte-identical pre-filter. + +## Gate +`a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` +(`stream.rs:6332`) is UN-IGNORED and GREEN with four hard asserts (compound-8x8 +filter read, differing dual-filter directions, 8x8 OBMC blend, 8x8 compound +GLOBAL warp). `$HOME/.cache/interp3-gate-r3.log`: `1 passed; 0 failed`. + +## EXACT NEXT STEP +1. DONE (suite green, report filled). Nothing owed here. +2. Then the lane's open residue is only the two deferrals in the report + (10-bit arm blocked by lane-inter8's 10-bit 8x8-leaf desync; `--tile-columns=1` + arm blocked by the SB-level rect-partition refusal). diff --git a/lanes/interp3-r3.report.md b/lanes/interp3-r3.report.md new file mode 100644 index 00000000..05fac697 --- /dev/null +++ b/lanes/interp3-r3.report.md @@ -0,0 +1,106 @@ +# lane-interp3 r3 -- the 8x8 COMPOUND leaf never applied the per-ref GLOBAL warp; gate is GREEN and un-ignored + +Base: d06d93f (r2 handoff, already merged with main). + +## Root cause (one line) + +`decode_inter_block8`'s COMPOUND arm predicted **both** reference taps +translationally, while libaom applies `allow_warp`'s GLOBAL branch to every +`is_global_mv_block` reference slot -- compound included and independently of +`motion_mode` (`av1_init_warp_params` is called inside +`build_inter_predictors_8x8_and_bigger`'s per-`ref` loop, `reconinter.c:33-55` +for `allow_warp` itself). The 16x16+ compound arm has done this since +lane-cwarp r1 (`decode.rs:16691`); the 8x8 leaf is its twin and drifted. +Third instance in this lane of the class **twin functions drift**. + +Effect on the pinned stream: the GLOBAL_GLOBALMV compound 8x8 leaf at +mi (10,4) of decode-order frame 7 (ref0=GOLDEN mv (0,0), ref1=ALTREF mv +(-3,4), `comp_group_idx=1` masked compound) was predicted with a pure +translation, so its prediction error was 0 at the block's top rows and grew +downward to |delta| 5 -- then propagated through every later frame. + +## It was NOT the OBMC blend (the r2 handoff's first suspect, disproved) + +An `EC_OBMC` emitter was added to both OBMC passes in `decode.rs`, printing the +instrumented aomdec's own byte format +(`EC_OBMC above|left mi=() wh=() rel= op= nbmv=() nbref= nbbsize= filt=`, +`decodeframe.c` `dec_build_prediction_by_{above,left}_pred`). The two decoders +emit **325 identical lines** on the pinned 16-frame stream -- neighbour +position, span, mv, reference, bsize and packed dual-filter pair all agree at +every OBMC call. The class sweep the charter asked for (neighbour-side fields +used by OBMC: filter, ref, mv, scale) is therefore CLEAN by measurement, not by +inspection; `obmc_mask_1/2/4/8/16/32` were also byte-compared against +`reconinter.c:752-765` and match. + +Frame 7 has no OBMC block at mi (10,4) at all: it is a compound block, and +compound blocks take SIMPLE_TRANSLATION. + +## Changed (path:line, this commit) + +- `crates/ec-av1/src/decode.rs:19513` -- `leaf_compound_warp` + + `warp0_c`/`warp1_c`, the leaf's per-slot copy of `decode_inter_block`'s + `compound_warp` (`force_integer_mv` short-circuit, `gm.invalid` guard). +- `crates/ec-av1/src/decode.rs:19596,19618` -- `warp::warp_affine_compound` + replaces each luma tap's translational intermediate, exactly as the 16x16+ + arm does at 17130/17155. Chroma is 4x4 at an 8x8 leaf, below + `av1_init_warp_params`'s own per-plane 8px bound, so chroma stays + translational (same rule the leaf's single-ref arm already applied). +- `crates/ec-av1/src/decode.rs:1786` -- `COMPOUND_WARP_HITS_8` + + `compound_warp_hits_8()`: the gate's proof that the warp fired at an 8x8 + LEAF specifically (`COMPOUND_WARP_HITS` alone cannot tell it from a 16x16+). +- `crates/ec-av1/src/decode.rs:15806` (`ec_obmc_bsize`) and `15828` + (`ec_obmc_trace`) + the two call sites in `obmc_blend` -- the `EC_OBMC` rung. +- `crates/ec-av1/src/decode.rs:14682,22658` -- `EC_PICT idx=` decode-order + frame marker (printed under `EC_OBMC`/`EC_TRACE_MODE`), so a trace line can be + attributed to the frame whose `EC_AV1_PREFILT_DUMP` file mismatched. Without + it the r2 hunt mis-attributed every trace line by one frame. +- `crates/ec-av1/src/stream.rs:6332` -- the gate's `#[ignore]` removed, doc + comment carries this round's measurement, and a third hard assert + (`compound_warp_hits_8() > before`) added. + +## Class sweep + +Both inter block decoders are the only prediction sites +(`decode_inter_block` 16309, `decode_inter_block8` 19032); all 12 +`predict_compound_intermediate` calls were audited. Warp coverage is now: +16x16+ single-ref (18235-18253), 16x16+ compound y/u/v x 2 refs +(17130-17300), 8x8 leaf single-ref (20238-20253), 8x8 leaf compound luma x 2 +refs (19596/19618, chroma correctly excluded). No third twin exists. + +## Gate: GREEN, un-ignored + +`a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` +(`--enable-dual-filter=1 --enable-obmc=1 --enable-warped-motion=1 +--enable-onesided-comp=1`, `--min-partition-size=8 --enable-ab-partitions=0 +--enable-1to4-partitions=0`, 64x64, 16 frames). Four hard asserts now: +compound 8x8 leaf reading its own switchable filter, a block whose two +dual-filter directions DIFFER, an 8x8 OBMC blend, and an 8x8 compound leaf +predicted through the per-ref GLOBAL warp. + +Command: +`EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-interp3 cargo test -p ec-av1 --lib a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact` +Result: `test result: ok. 1 passed; 0 failed` (log `$HOME/.cache/interp3-gate-r3.log`). + +## Refusals + +None lifted. The r1 refusal `an OBMC neighbour whose interp filter was never +recorded` stays (it does not fire on this stream); `refusal_inventory.rs` and +`gate_coverage.rs` unchanged. + +## EVIDENCE + +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/{aom.obmc,ours.obmc} | `EC_OBMC=1 aomdec --rawvideo -o /dev/null mm.obu` vs `EC_OBMC=1 decode_probe mm.obu`, `diff` of every EC_OBMC line | 325 vs 325 lines, diff EMPTY -- OBMC neighbour selection/mv/ref/bsize/filter exonerated +EVIDENCE: same dir, pf_a/f.f0..15 vs pf_o/f.f0..15 | `EC_AV1_PREFILT_DUMP` on both decoders, byte compare per decode-order frame BEFORE the fix | frames 0-6 identical, frame 7 35 bytes differ (all inside luma rows 42-47, cols 16-23 = the 8x8 leaf at mi (10,4)), growing to 224 at frame 15 +EVIDENCE: same dir, pf_a vs pf_o2 | identical command AFTER the fix | all 16 decode-order frames byte-identical pre-filter (0 differing bytes) +EVIDENCE: $HOME/.cache/interp3-gate-r3.log | `cargo test -p ec-av1 --lib a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact -- --nocapture` | `test result: ok. 1 passed; 0 failed` with all four counter asserts live (the run would panic if `compound_warp_hits_8` had not moved) +EVIDENCE: $HOME/.cache/interp3-suite-r3.log | `EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-interp3 cargo test -p ec-av1 --lib -j3` under systemd unit `interp3-suite-r3-1788328778.service`, armed at f36be26 | `test result: ok. 379 passed; 0 failed; 33 ignored; 0 measured; 0 filtered out; finished in 1031.33s` (r2 baseline was 378 passed / 34 ignored -- the delta is exactly this gate leaving `#[ignore]`) + +## Residue + +- deferred(lane-inter8's 10-bit 8x8-leaf desync) -- a 10-bit twin of this gate. + Its sibling `a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_...` + is still `#[ignore]`d on an unrelated 10-bit desync (lane-inter8 r2), so a + 10-bit arm of this recipe would go RED on that, not on interp3's own path. +- deferred(needs a multi-tile recipe that reaches an 8x8 leaf) -- a + `--tile-columns=1` arm. lane-inter8 r3 measured that the 128x64 multi-tile + recipe stops at the SB-level rect-partition refusal before any 8x8 leaf. diff --git a/lanes/intersub8-r1.handoff.md b/lanes/intersub8-r1.handoff.md new file mode 100644 index 00000000..57bfe716 --- /dev/null +++ b/lanes/intersub8-r1.handoff.md @@ -0,0 +1,64 @@ +# lane-intersub8 r1 — HANDOFF (RED, code committed, gate red) + +## 1. The refusal is REAL, not our desync (settled, do not re-litigate) +`aomenc` genuinely writes sub-8x8 partitions on INTER frames. +Recipe (192x128, 6 frames, gray ramp `128+58*sin((X+N*8)/6)+18*sin(Y/23)`, cq 8, +`--min-partition-size=4 --max-partition-size=16 --enable-rect-partitions=1 +--enable-ab-partitions=0 --enable-1to4-partitions=0 --enable-obmc=0 +--enable-tx-size-search=1 --sb-size=64 --lag-in-frames=0`), oracle: +`EC_TRACE=1 ~/.cache/aom-oracle/build/aomdec --rawvideo -o /dev/null u8_8.obu 2>ec.log` +`EC_PART_VAL bsize=3` histogram: **v0=68 NONE, v1=28 HORZ, v2=49 VERT, v3=3 SPLIT**. +So 8x4/4x8 dominate; 4x4 SPLIT is rare. `--enable-rect-partitions=0` removes +HORZ/VERT below 8x8 and still yields SPLIT groups (2 per stream at cq 8). + +Side fact worth a sweep: the SAME trace shows `bsize=6 value=6/7` (VERT_A/VERT_B at +16x16) even though `--enable-ab-partitions=0` was on the command line — that is what +the "inter 16x16-level AB or 1:4 partition" refusal fires on for recipes with +`--min-partition-size=4`. Either the flag is not honoured at that size or the +refusal is itself hallucinated; lane-inter16ab should check with this trace. + +## 2. What landed (compiles, `cargo check` clean) +* `crates/ec-av1/src/decode.rs` `decode_inter_sub8_split4` (new fn, above + `decode_inter_block8`): four `BLOCK_4X4` inter sub-blocks of one 8x8 group. + Symbols deliberately NOT read below 8x8, with libaom citations in the doc + comment: `skip_mode` / `comp_mode` (`is_comp_ref_allowed`, blockd.h), + `interintra` (`is_interintra_allowed_bsize`), `motion_mode`/`obmc` + (`motion_mode_allowed`), tx size (`block_signals_txsize`, blockd.h:1027 — + `bsize > BLOCK_4X4`, so `BLOCK_4X4` reads NO tx symbol even in TX_MODE_SELECT, + decodeframe.c:1164-1177). Chroma once per 8x8 on the last sub-block, 4x4 TX, + prediction = four 2x2 chroma pieces each from its own sub-block's mv/ref/filters + (`dec_build_inter_predictors` is_sub8x8; spec 7.11.3.1). Chroma tx_type inherits + the FIRST sub-block's luma tx_type (`av1_get_tx_type` co-located luma 0,0). +* call site: `decode.rs` ~21834, `part8 == PARTITION_SPLIT` dispatches; HORZ/VERT + now refuse under a NARROWED string (rect sub-8x8 inter transform unimplemented). +* counter `SUB8_INTER_SPLIT_HITS` / `decode::sub8_inter_split_hits()`. +* `refusal_inventory.rs`: old string replaced by the 3 new ones. +* gate `stream.rs::a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact`. + +## 3. Gate result: RED (two separate failures) +`cargo test -p ec-av1 --lib sub8x8_inter_split` +* 8-bit attempt 0 (cq 8, sp 3): **MISMATCHES with ZERO sub-8x8 inter split groups** + → a defect this lane did not introduce and does not own (out-of-scope arm). + Suspect: the oracle's 2 `bsize=3 value=3` in that stream are on the KEY frame + (intra `decode_leaf_split4`), i.e. a pre-existing intra sub-8x8 defect on this + recipe, OR our partition read desyncs before reaching them. CHECK FIRST: run the + oracle trace on that exact stream and print the frame index of each b3 v3. +* 8-bit attempt 1 (cq 12, sp 3): 1 split group, luma **frame 5** mismatches. + Frames 0..4 are exact, so the group is late in the sequence — bisect with + `EC_TRACE_MODE` (`EC_MODE_VAL4` line added for the 4x4 sub-block) against the + oracle's `EC_MODE`/`EC_MODE_VAL` at the same mi, comparing msac RANGE. + Prime suspects, in order: (a) the sub-block `skip` context — I used the + mi-granular `above_skip[cmi]`/`left_skip[rmi]` pair like `decode_inter_block8`, + libaom uses `av1_get_skip_txfm_context`; (b) the chroma 2x2 piece offsets / + which sub-block's filters each piece uses; (c) `record_mi_luma_rect` per 4x4 vs + the group-level chroma neighbour tail; (d) `first_tx_type` when sub-block 0 is + skip (libaom memsets tx_type_map to DCT_DCT for skip — we leave DctDct: OK). + +## 4. Still refused after this round +`an inter 8x8 HORZ/VERT partition (8x4/4x8 inter leaves...)` — needs (1) INTER +TxbSet twins for 4x8/8x4 (`LumaRect4x8Inter`/`Set1`: side 8 tables + +`inter_tx_type_4`, copy `LumaRect4x8` and swap the tx_type slice), (2) a +rectangular var-tx read: for BLOCK_8X4/4X8, TX_MODE_SELECT + !skip reads exactly +ONE `txfm_partition` symbol (max_txsize_rect_lookup = TX_8X4/TX_4X8; split → +TX_4X4), our `read_block_tx_size`/`read_var_tx_size` are square-only. +That is the bulk of the remaining work and is why r1 scoped to SPLIT. diff --git a/lanes/intersub8-r2.handoff.md b/lanes/intersub8-r2.handoff.md new file mode 100644 index 00000000..4a1cc7c0 --- /dev/null +++ b/lanes/intersub8-r2.handoff.md @@ -0,0 +1,66 @@ +# lane-intersub8 r2 — HANDOFF (gate GREEN, 8x4/4x8 not started) + +## Merge state +* `c048e29` main (8e9ba81) merged — no conflicts, `cdf.rs` untouched. +* `e8bb7e7` lane-r14 **b86eb38 merged** (it was NOT on main: main only carries the earlier + `6699ce6`/`a2e2e29`). So `read_var_tx_size` here is `(tx_w,tx_h)`-general with the full + `sub_tx_size_map`, and `read_inter_plane_rect` is available. + NOTE (ledger, lane-inter16ab r3): that merge deletes the "split transform on a 16x16-level + 1:4 inter strip" refusal, so a TX_16X4→TX_8X4 split can reach + `rect_inter_residual_supported(8,4)==false` / `rect_inter_luma_set` `unreachable!()`. + The `LumaRect8x4Inter`/`LumaRect4x8Inter` TxbSets (step 3 below) close that too. + +## Attempt-0 (cq 8) zero-group mismatch — ROOT CAUSE IDENTIFIED, out of scope +Not a sub-8x8 defect: **CDEF**. 3 luma samples `|d|=1`, decode-order frames 3 and 4 +(x=189 resp. 186, y=116/120/124), zero sub-8x8 inter split groups in those frames; the +identical recipe re-encoded with `--enable-cdef=0` decodes all six frames pixel-exact +(`~/.cache/intersub8-tmp/gen.sh 8 3 8 a0_nocdef.obu --enable-cdef=0`, then `cmp.py`). +Also reproduces at cq 10. Deferred to a CDEF lane. The gate moved to cq {12,14} instead of +switching CDEF off (cdef=0 changes aomenc RD and then NO attempt fires a split group). + +## Attempt-1 frame-5 ladder — FIXED (`96eff0c`) +First diverging element: the **switchable interp filter** of the 4x4 sub-block mi(14,46). +Ladder vs aomdec `EC_TRACE_MODE` on `~/.cache/intersub8-tmp/a1_8.obu`: +entry `39095` = , post-`assign_mv` `60392` = , after interp filter ours `51740` vs oracle `57815`. +Cause: the **compound 8x8 inter leaf never called `resolve_interp_filter`** — it hard-coded +`Regular` and recorded the `[3, 3]` sentinel in the neighbour filter band. libaom calls +`read_mb_interp_filter` for every inter block right after `read_compound_type`, and when +`av1_is_interp_needed()==0` (`skip_mode`) `set_default_interp_filters` stores +EIGHTTAP_REGULAR **0**. The left neighbour here was a skip_mode compound 8x8 leaf, so our +`av1_get_pred_context_switchable_interp` used 3 instead of 0 → wrong CDF row → desync. +Fix reads the symbols, uses `h_filter`/`v_filter` in all six `predict_compound_*` calls of +that branch, records the real syms. This also removes the old lane-av1comp corner-cut +(a NON-skip compound 8x8 leaf used to skip the symbol entirely = latent desync). +New rungs for the next hunt: `EC_TRACE_MODE` now prints `EC_MODE` + `EC_MODE_MV` on the +sub-8x8 path at the oracle's two print points, and `EC_AV1_IFDBG` prints `IFDBG4` with the +neighbour ref/filter bands. + +## 8x4/4x8 (charter step 3) — NOT STARTED +Still refused by name: `an inter 8x8 HORZ/VERT partition (8x4/4x8 inter leaves; the 4x4 +SPLIT arm decodes, but a rectangular sub-8x8 inter transform is unimplemented)`. +Remaining pieces: `TxbSet::LumaRect8x4Inter{,1}` / `LumaRect4x8Inter{,1}` (copy the key-frame +8x4/4x8 intra sets' scan/ctx, swap in `inter_tx_type_4`; `av1_get_ext_tx_set_type` → +EXT_TX_SET_ALL16 for inter with `sqr_up == TX_8X8`), ONE `txfm_partition` bit at max +TX_8X4/TX_4X8 (r14's general `read_var_tx_size` handles it once max=(8,4)), mode info per +sub-block, chroma once on the LAST sub-block as 4x4 with 2 sub8x8 pieces, per-mi neighbour +writes. Gate arm: same recipe with `--enable-rect-partitions=1` (oracle histogram on the r1 +recipe: bsize=3 v1=28 HORZ, v2=49 VERT, v3=3 SPLIT). + +## Gate state +`cargo test -p ec-av1 --lib sub8x8_inter_split` → **ok, 1 passed / 0 failed** (414 filtered). +Schedule measured by a 56-encode sweep (`~/.cache/intersub8-tmp/sweep.sh`): cq {12,14} × +sp {3,6,9,12} × 8/10-bit. Firing: 8-bit cq12/sp3 = 1 group, 10-bit cq12/sp6 = 3 groups, both +pixel-exact; `out_of_scope_mismatch == 0`; every decode-order frame compared Y/U/V. +`decode_probe` now prints `sub8_inter_split: groups=N`. +`fixtures/realworld/reelb.obu` now stops at the 8x4/4x8 refusal (was: the SPLIT one). + +## Suite +Unit `intersub8-suite-1788328909.service`, log `$HOME/.cache/intersub8-suite-r2.log`. +FINISHED GREEN after this handoff was first written: +`test result: ok. 382 passed; 0 failed; 33 ignored; 0 measured; 0 filtered out; finished in 1018.88s`. +That run IS the sibling sweep for the interp-filter fix (it touches every compound 8x8 leaf). + +## Exact next step +1. Read the suite log (above). 2. Build `LumaRect8x4Inter`/`LumaRect4x8Inter` TxbSets and the +8x4/4x8 leaf, add the `--enable-rect-partitions=1` gate arm plus a `--tile-columns=1` arm +(COMMON neighbour-map rule, still owed), then drop the 8x4/4x8 refusal + inventory line. diff --git a/lanes/intersub8-r2.report.md b/lanes/intersub8-r2.report.md new file mode 100644 index 00000000..59520396 --- /dev/null +++ b/lanes/intersub8-r2.report.md @@ -0,0 +1,70 @@ +# lane-intersub8 r2 — GREEN gate, one root cause, 8x4/4x8 deferred + +## 1. Merges +* `c048e29` main (8e9ba81) into lane-intersub8 — no conflicts, `cdf.rs` untouched. +* `e8bb7e7` lane-r14 (b86eb38) — `read_var_tx_size` is now `(tx_w,tx_h)`-general with the + full `sub_tx_size_map`, plus `read_inter_plane_rect`. `b86eb38` was NOT on main + (`git merge-base --is-ancestor b86eb38 main` → false; main only has the earlier + `6699ce6` merge of `a2e2e29`). + +## 2. Root cause of the frame-5 red (fixed, `96eff0c`) +`crates/ec-av1/src/decode.rs` (8x8 inter leaf, compound arm, ~19940): the branch +**never called `resolve_interp_filter`**. It hard-coded `Regular` for both taps and left +`leaf_filter_syms` at the `[3, 3]` "no filter" sentinel that `Neighbours::record_inter*` +then stored. libaom reads `read_mb_interp_filter` for every inter block right after +`read_compound_type` (`decodemv.c` `read_inter_block_mode_info`), and when +`av1_is_interp_needed` is 0 (`skip_mode`, `WARPED_CAUSAL`, non-translational GLOBALMV) +`set_default_interp_filters` stores **EIGHTTAP_REGULAR (0)**, not a sentinel. Any later +block whose `ref_frame[0]` matches that leaf's ref0 **or ref1** then computes +`av1_get_pred_context_switchable_interp` from 3 instead of 0 → wrong `switchable_interp` +CDF row → tile desync. + +Bisection (class *compare range not tell*): on `a1_8.obu` (192x128, 8-bit, cq 12, sp 3) +the 4x4 sub-block at mi(14,46) matched the oracle at both of aomdec's own print points — +entry `rng=39095`, post-`assign_mv` `rng=60392` — and diverged only across the interp +filter read: ours `51740` vs aomdec `57815`. `IFDBG4` showed `left_ref=1 left_ref1=Some(4) +ref=4 left_filt=[3,3]`: the left neighbour was a **skip_mode compound 8x8 leaf** (its own +`EC_MODE` → `EC_MODE_VAL` range never moved, i.e. zero symbols). + +Fix reads the filter properly (`skip_mode` → `force_regular`, ctx from the same ref-match +rule the other leaves use), feeds `h_filter`/`v_filter` to all six `predict_compound_*` +calls of that branch and records the real symbols. This also removes the long-standing +`lane-av1comp` corner-cut: a **non-skip** compound 8x8 leaf used to skip the symbol +entirely, which was a latent desync for any stream that codes one. + +## 3. Out-of-scope defect found and named (NOT hidden) +Same recipe at **cq 8 / cq 10**: three luma samples of `|d| = 1` on decode-order frames 3 +and 4 (x=189 resp. 186, y=116/120/124), with **zero** sub-8x8 inter split groups in those +frames. Re-encoding the identical recipe with `--enable-cdef=0` decodes all six frames +pixel-exact ⇒ a **CDEF** defect of another shape. +`deferred: CDEF ±1 luma at cq 8/10 on the 192x128 min-partition-4 recipe — belongs to a +CDEF lane, not to sub-8x8 partitions — unblocked by a CDEF-focused gate`. +The gate does not switch CDEF off (that changes aomenc's RD and kills every firing +attempt); it moves to cq {12,14}, where a full sweep shows no mismatch at all. + +## 4. Gate +`cargo test -p ec-av1 --lib sub8x8_inter_split` → +`test result: ok. 1 passed; 0 failed` (414 filtered out). +Schedule measured, not guessed: sweep of cq {8,10,12,14,16,18,20} × sp {3,6,9,12} × 8/10-bit +(`decode_probe`'s new `sub8_inter_split:` counter + an ffmpeg rawvideo compare). +Firing attempts: 8-bit cq12/sp3 = 1 group, 10-bit cq12/sp6 = 3 groups, both pixel-exact, +every decode-order frame compared Y/U/V; `out_of_scope_mismatch == 0`. + +EVIDENCE: ~/.cache/intersub8-tmp/a1_8.obu + ours.if.log + oracle.mode.log | aomenc 192x128 8-bit cq12 min-partition-size=4, our EC_MODE/EC_MODE_MV rungs vs aomdec EC_TRACE_MODE range ladder at mi(14,46), then a full-frame ffmpeg compare | ladder diverged at the interp filter (51740 vs 57815); after the fix all 6 frames byte-identical (`cmp.py` frames 0..5 exact) +EVIDENCE: ~/.cache/intersub8-tmp/sweep.sh output (56 encodes) | cq×sp×depth sweep, decode_probe counter + ffmpeg compare | 2 firing attempts both EXACT, all cq≥12 attempts EXACT or named-refusal, cq 8/10 carry the CDEF ±1 +EVIDENCE: fixtures/realworld/reelb.obu | decode_probe on the merged tree | now stops at "an inter 8x8 HORZ/VERT partition (8x4/4x8 inter leaves...)" — the sub-8x8 SPLIT refusal no longer blocks it + +## 4b. Suite +`intersub8-suite-1788328909.service`, log `$HOME/.cache/intersub8-suite-r2.log`: +`test result: ok. 382 passed; 0 failed; 33 ignored; 0 measured; 0 filtered out; finished in 1018.88s`. +This is the sibling sweep the interp-filter fix owes: it touches every compound 8x8 inter leaf. + +## 5. Not done this round +`deferred: 8x4/4x8 inter leaves (charter step 3) — the turn budget went to the root-cause +hunt and the gate schedule — unblocked by a fresh round on this branch; r14's general +read_var_tx_size is now merged here, so the remaining pieces are the LumaRect8x4Inter / +LumaRect4x8Inter TxbSets (EXT_TX_SET_ALL16, sqr_up TX_8X8) and the 2-sub-block chroma`. +`deferred: a --tile-columns=1 arm on this gate (COMMON neighbour-map rule) — same budget — +unblocked by the next round`. +The `an inter 8x8 HORZ/VERT partition ...` refusal therefore STAYS; no refusal string was +removed this round, and `refusal_inventory`/`gate_coverage` are unchanged. diff --git a/lanes/intersub8-r3.handoff.md b/lanes/intersub8-r3.handoff.md new file mode 100644 index 00000000..c60f00d8 --- /dev/null +++ b/lanes/intersub8-r3.handoff.md @@ -0,0 +1,79 @@ +# lane-intersub8 r3 — HANDOFF (4x8 gated GREEN, 8x4 implemented but refused) + +## What is wired (decode.rs `decode_inter_sub8_rect2`, ~line 19100) +One function serves both shapes (`vert: bool`); the call site +(`part8 == PARTITION_VERT` arm of the sub-16 SPLIT leaf loop, ~decode.rs:22630) currently +only reaches it with `vert = true`. +* mode info per sub-block in `decodemv.c` `read_inter_frame_mode_info` order: segment_id, + skip, cdef/dq/dlf, intra_inter, single ref only (`is_comp_ref_allowed(BLOCK_8X4)` false -> + no skip_mode, no comp_mode), no interintra / motion_mode / OBMC / warp (all need min dim 8), + `read_mb_interp_filter` DOES run. +* tx: `block_signals_txsize(BLOCK_8X4)` true (blockd.h:1027) -> ONE `txfm_partition` symbol + under TX_MODE_SELECT at `max_txsize_rect_lookup[BLOCK_8X4] = TX_8X4`, through r14's general + `read_var_tx_size` with max `(bw,bh)` and `blk_max_px = 8`; `sub_tx_size_map[TX_8X4]=TX_4X4` + so a split resolves to two TX_4X4 units (libaom's early return). Skip -> `set_txfm_ctxs` + skip_inter arm. +* luma sets NEW in cdf_state.rs: `TxbSet::LumaRect8x4Inter` / `LumaRect8x4InterSet1` = + `LumaRect4x8`'s tables (8x8 coefficient class, 32-position eob_pt) with `inter_tx_type_4` / + `inter_tx_type_4_set1` (EXT_TX_SET_ALL16 at the TX_4X4 inter row). Split TX_4X4 units read + `Luma4Inter{,Set1}`. Whole-leaf unit passes `luma_skip_ctx: None` (it IS the plane block, + `get_txb_ctx_general` fixes 0); split units pass `luma_skip_ctx_rect`. +* chroma once, on the SECOND sub-block (`is_chroma_reference` under 4:2:0: bottom 8x4 / + right 4x8), as one TX_4X4 per plane (`TxbSet::Chroma4`), inheriting the FIRST luma TU's + tx_type; prediction is the sub8x8 one (`reconinter.c build_inter_predictors_sub8x8`, + `row_start = -(block_size_high==4 && ss_y)`): two 4x2 (HORZ) / 2x4 (VERT) pieces, each from + its own sub-block's ref/mv/filters. +* neighbour writes per mi: `grid_stamp_rect` (size=w_mi, size_h=h_mi over the true span), + `record_mode_mi`, `record_inter_rect_mi`, `fill_skip_grid_rect`, `fill_lf_grid_rect`, + `record_mi_luma_rect` per TU; partition tail `above_side_mi = bw`, `left_side_mi = bh`. + +## The 8x4 defect (refused by name, NOT fixed) +Stream: `~/.cache/intersub8-tmp/gen_t.sh 14 3 8 d1.obu --enable-rect-partitions=1` +(transposed-structure geq source: `128+58*sin((Y+N*3)/6)+18*sin(X/23)`, 192x128, 6 frames). +Decode-order frame 5 mismatches; frames 0..4 exact. 4 HORZ groups, all at mi rows 30/31, +cols 4 and 6. +Range ladder (`EC_TRACE_PART=1` ours, new gated print at each partition read, vs aomdec +`EC_TRACE=1` `EC_PART`; and `EC_TRACE_MODE` `EC_MODE`; and `EC_TRACE_COEFF` `tag=all_zero`): +* every element matches through the 16x16 partition read at mi(28,8) (ctx 2 == oracle's 6, + entry rng 37489 both) and through `EC_MODE mi_row=30 mi_col=8 rng=46505` (both); +* that slot is PARTITION_HORZ -> two BLOCK_16X8 at (28,8) and (30,8); +* block (30,8)'s LEFT neighbour is our HORZ 8x4 group at (30,6); +* first divergence is INSIDE (30,8)'s mode info, AFTER its `EC_MODE` print (so skip and + intra_inter are still right) and BEFORE its first coefficient TU: our TU entry rng 54923 vs + oracle 61760 (`EC_COEFF plane=0 tx_size=8` = TX_16X8, all_zero=0 both). all_zero #468 of + 470/473. +=> some per-ROW neighbour band our HORZ group leaves at rows 30/31 is wrong. Remaining +suspects, in read order after the print: `left_ref[30]`, the mv stack (MiGrid cells (30,7)/ +(31,7)), `left_filter[30]`, `left_txfm[30]`. All four were transcribed against libaom and +looked right on inspection -- not bisected. NOTE ledger: this oracle's +`EC_AV1_PREFILT_DUMP` is already post-deblock, so pixel-stage bisection is confounded; use +the range ladder only. + +## Provable vs not +* PROVABLE (gated): two-BLOCK_4X8 (PARTITION_VERT) inter leaves. Sweep + `~/.cache/intersub8-tmp/sweep2.sh` (28 arms, cq {8,12,14,16,20,26,32} x sp {3,6,9,12} x + 8/10-bit, original source, rect on): every arm with `vert4x8 > 0` outside the known-bad + cq8 band decoded pixel-exact; the two cq8 mismatches are r2's CDEF |d|=1 defect. +* NOT PROVABLE: 8x4 (HORZ). `sweep3.sh` (transposed source): 4 of 28 arms mismatch with + `horz8x4 > 0` at cq 12/14/16/32, i.e. outside the CDEF band. Refused by name. + +## Gate +`cargo test -p ec-av1 --lib sub8x8_inter_split` -> ok, 1 passed / 0 failed (414 filtered), +28.94s. The test now runs 16 attempts per depth: 0..7 `--enable-rect-partitions=0` (SPLIT), +8..15 `=1` (VERT). Asserts `fired >= 2`, NEW `rect_fired >= 2`, `out_of_scope_mismatch == 0`, +every decode-order frame Y/U/V. `refusal_inventory` 3/3 ok, `gate_coverage` 9/9 ok. + +## Not done +* Full `cargo test -p ec-av1 --lib` suite: NOT RUN this round (turn cap). r2's unit + `intersub8-suite-1788328909` was still running on a stale binary at round start and is now + gone from the unit list; `$HOME/.cache/intersub8-suite-r2.log` has 218 ok / 0 FAILED and no + `test result:` line. Start r3's suite per COMMON's SUITE RUNS recipe, log + `$HOME/.cache/intersub8-suite-r3.log`. +* HG film probe: not run. +* `--tile-columns=1` gate arm: still owed (no NEW per-mi band was added, all reused). + +## Exact next step +1. Start the r3 suite. 2. Bisect the 8x4 defect on `d1.obu` frame 5 block (30,8) by dumping, +one at a time, the four left-band values our HORZ group writes at rows 30/31 and comparing +against an instrumented aomdec print of `xd->left_mbmi`/`left_txfm_context[0]` at that block. +3. Lift the HORZ refusal with a `sweep3.sh`-based arm once green. diff --git a/lanes/intersub8-r4.handoff.md b/lanes/intersub8-r4.handoff.md new file mode 100644 index 00000000..e6888e98 --- /dev/null +++ b/lanes/intersub8-r4.handoff.md @@ -0,0 +1,70 @@ +# lane-intersub8 r4 — RED on the HORZ lift, GREEN on its root cause + +## What changed +* `crates/ec-av1/src/decode.rs:15981+` — new `bsize_index(w,h)` (libaom `BLOCK_SIZES_ALL` + order), `masked_compound_used_wh`, `wedge_used_wh`. +* `crates/ec-av1/src/decode.rs` (`decode_inter_block`, comp-type block) — `comp_group_idx`'s + gate and the `compound_type` / `wedge_idx` CDF ROWS now come from the block's true + `(write_w, write_h)`, not the caller's square `side`. A 16x8 masked-compound block used to + read `BLOCK_16X16`'s row (index 6) where libaom reads `BLOCK_16X8`'s (index 5). + Class: table-indexed-by-raw-size / CDF-row-held-constant. +* Same site — `COMPOUND_WEDGE` on a non-square block is refused by name (the wedge codebook + here is built per square side only); listed in `refusal_inventory.rs`. +* `crates/ec-av1/src/decode.rs` — `EC_TRACE_MODE` gains `EC_CGI` / `EC_CIDX` / `EC_IF` + (comp_group_idx, compound_idx, interp filter: ctx + value + range). These are the rungs + that localized the defect; the oracle has no per-symbol print between `EC_MODE_MV` and + `EC_MODE_VAL`, so ours had to be split. +* Sub-8x8 HORZ call site — still refused, refusal text rewritten to the measured residue, + and `EC_AV1_SUB8_HORZ=1` decodes it anyway for the next round's bisect. + +## Root cause (r3's open defect), proven +`~/.cache/intersub8-tmp/d1.obu` (192x128, 6 frames, 8-bit, transposed geq source, cq14 sp3, +`--enable-rect-partitions=1`), decode-order frame 5, `BLOCK_16X8` at mi(30,8): +| rung | ours before | ours after | aomdec | +|---|---|---|---| +| `EC_MODE` entry | 46505 | 46505 | 46505 | +| after mv (`EC_MODE_MV`) | 58288 | 58288 | 58288 | +| end of mode info (`EC_MODE_VAL`) | 54923 | **61760** | **61760** | +| next block `EC_MODE` mi(28,12) | 33919 | **60694** | **60694** | +The block reads `comp_group_idx=1` (ctx 0, correct — a ctx sweep 0..5 never reproduced the +oracle), then `compound_type` from the wrong CDF row. The 8x4 group to its left was innocent: +it only changed which value `comp_group_idx` took. + +EVIDENCE: ~/.cache/intersub8-tmp/{o5b.log,o6.log,r4.log} | EC_TRACE_MODE ladder on d1.obu before/after the fix vs instrumented aomdec | end-of-mode-info rng 54923 -> 61760 == oracle, and `cmp` of the probe output vs `ffmpeg -pix_fmt yuv420p` is byte-identical for all 6 frames +EVIDENCE: ~/.cache/intersub8-tmp/sweep3.sh output (28 arms, transposed source, cq {8,12,14,16,20,26,32} x sp {3,6,9,12} x 8/10-bit, rect on) | full re-run under `systemd-run --scope` | mismatching arms with horz8x4>0: 4 (r3) -> 3; 8-bit cq14 sp3 (horz=4) and cq20 sp3 (horz=4) went MISMATCH -> EXACT + +## Why the HORZ refusal did NOT lift (RED) +3 of 28 arms still mismatch with `horz8x4 > 0`: 8-bit cq32 sp9 (horz=3), 10-bit cq12 sp3 +(horz=5), 10-bit cq16 sp3 (horz=2). On the 10-bit cq12 sp3 stream the ENTROPY IS EXACT — the +full `EC_MODE` range ladder is identical to aomdec's element for element (the only diff is two +extra `EC_MODE` prints for blocks aomdec's instrumentation does not print). The mismatch is +post-entropy: luma only, `|d| <= 2`, confined to x < 48 / y >= 112 (mi rows 28..31, mi cols +0..11), first appearing on decode-order frame 3 and propagating. Shape says filter (CDEF or +the deblock of the internal 8x4 edge), not reconstruction of the coefficients. +EVIDENCE: ~/.cache/intersub8-tmp/{a.txt,b.txt,m1.ours,m1.ref} | `diff` of the two EC_MODE ladders + per-frame python pixel diff | ladder diff = 2 extra lines, 0 range mismatches; frame 3: 125 differing luma samples, max |d| = 2, all in x<48 y>=112 + +## Gates +* `sub8x8_inter_split` (the r3 gate, SPLIT + VERT arms) unchanged — HORZ arm NOT added, since + the shape is still refused. +* No new gate for the masked-compound fix: measured, the only streams that reach a rect + masked-compound block are HORZ ones, which the refusal blocks. `deferred: gate for the rect + compound_type/wedge_idx row — no non-HORZ recipe found that produces a rect block with + comp_group_idx==1 — unblocked by either the HORZ lift or a `--enable-masked-comp` sweep on + rect-heavy square-only content.` +* Full suite: unit `intersub8-suite-r4-1788331918.service` -> `$HOME/.cache/intersub8-suite-r4.log`, + STILL RUNNING at hand-off (74 ok, 0 FAILED, no `test result:` line yet). NOT a green claim. + r3's unit (`intersub8-suite-1788331066`) was stopped as charter-ordered; its log had 73 ok / + 0 FAILED and no `test result:` line at stop time. + +## Film probe +0.4 s copy-extract at 0 s of the 2160p 10-bit HDR AV1 film yields only 1817 bytes (one OBU +set, no full frame); the probe returns counters (`horz8x4=0`) and no refusal, so the census's +start_s=0 refusal ("an inter partition below 8x8") is NOT reproduced by that extract. +`deferred: HG below-8x8 census probe — the bounded extract is too small to reach the block — +unblocked by extracting from a keyframe offset (census4 reelb4.tsv start_s column).` + +## Residue +* fix-now(next round): the |d|<=2 luma band under HORZ. Reproduce with + `EC_AV1_SUB8_HORZ=1` on `~/.cache/intersub8-tmp/t_10_12_3.obu` (regenerate: + `./gen_t.sh 12 3 10 m1.obu --enable-rect-partitions=1`). +* accepted: `COMPOUND_WEDGE` on a rect block refused (rect wedge codebooks unimplemented). diff --git a/lanes/intersub8-r4.report.md b/lanes/intersub8-r4.report.md new file mode 100644 index 00000000..e6888e98 --- /dev/null +++ b/lanes/intersub8-r4.report.md @@ -0,0 +1,70 @@ +# lane-intersub8 r4 — RED on the HORZ lift, GREEN on its root cause + +## What changed +* `crates/ec-av1/src/decode.rs:15981+` — new `bsize_index(w,h)` (libaom `BLOCK_SIZES_ALL` + order), `masked_compound_used_wh`, `wedge_used_wh`. +* `crates/ec-av1/src/decode.rs` (`decode_inter_block`, comp-type block) — `comp_group_idx`'s + gate and the `compound_type` / `wedge_idx` CDF ROWS now come from the block's true + `(write_w, write_h)`, not the caller's square `side`. A 16x8 masked-compound block used to + read `BLOCK_16X16`'s row (index 6) where libaom reads `BLOCK_16X8`'s (index 5). + Class: table-indexed-by-raw-size / CDF-row-held-constant. +* Same site — `COMPOUND_WEDGE` on a non-square block is refused by name (the wedge codebook + here is built per square side only); listed in `refusal_inventory.rs`. +* `crates/ec-av1/src/decode.rs` — `EC_TRACE_MODE` gains `EC_CGI` / `EC_CIDX` / `EC_IF` + (comp_group_idx, compound_idx, interp filter: ctx + value + range). These are the rungs + that localized the defect; the oracle has no per-symbol print between `EC_MODE_MV` and + `EC_MODE_VAL`, so ours had to be split. +* Sub-8x8 HORZ call site — still refused, refusal text rewritten to the measured residue, + and `EC_AV1_SUB8_HORZ=1` decodes it anyway for the next round's bisect. + +## Root cause (r3's open defect), proven +`~/.cache/intersub8-tmp/d1.obu` (192x128, 6 frames, 8-bit, transposed geq source, cq14 sp3, +`--enable-rect-partitions=1`), decode-order frame 5, `BLOCK_16X8` at mi(30,8): +| rung | ours before | ours after | aomdec | +|---|---|---|---| +| `EC_MODE` entry | 46505 | 46505 | 46505 | +| after mv (`EC_MODE_MV`) | 58288 | 58288 | 58288 | +| end of mode info (`EC_MODE_VAL`) | 54923 | **61760** | **61760** | +| next block `EC_MODE` mi(28,12) | 33919 | **60694** | **60694** | +The block reads `comp_group_idx=1` (ctx 0, correct — a ctx sweep 0..5 never reproduced the +oracle), then `compound_type` from the wrong CDF row. The 8x4 group to its left was innocent: +it only changed which value `comp_group_idx` took. + +EVIDENCE: ~/.cache/intersub8-tmp/{o5b.log,o6.log,r4.log} | EC_TRACE_MODE ladder on d1.obu before/after the fix vs instrumented aomdec | end-of-mode-info rng 54923 -> 61760 == oracle, and `cmp` of the probe output vs `ffmpeg -pix_fmt yuv420p` is byte-identical for all 6 frames +EVIDENCE: ~/.cache/intersub8-tmp/sweep3.sh output (28 arms, transposed source, cq {8,12,14,16,20,26,32} x sp {3,6,9,12} x 8/10-bit, rect on) | full re-run under `systemd-run --scope` | mismatching arms with horz8x4>0: 4 (r3) -> 3; 8-bit cq14 sp3 (horz=4) and cq20 sp3 (horz=4) went MISMATCH -> EXACT + +## Why the HORZ refusal did NOT lift (RED) +3 of 28 arms still mismatch with `horz8x4 > 0`: 8-bit cq32 sp9 (horz=3), 10-bit cq12 sp3 +(horz=5), 10-bit cq16 sp3 (horz=2). On the 10-bit cq12 sp3 stream the ENTROPY IS EXACT — the +full `EC_MODE` range ladder is identical to aomdec's element for element (the only diff is two +extra `EC_MODE` prints for blocks aomdec's instrumentation does not print). The mismatch is +post-entropy: luma only, `|d| <= 2`, confined to x < 48 / y >= 112 (mi rows 28..31, mi cols +0..11), first appearing on decode-order frame 3 and propagating. Shape says filter (CDEF or +the deblock of the internal 8x4 edge), not reconstruction of the coefficients. +EVIDENCE: ~/.cache/intersub8-tmp/{a.txt,b.txt,m1.ours,m1.ref} | `diff` of the two EC_MODE ladders + per-frame python pixel diff | ladder diff = 2 extra lines, 0 range mismatches; frame 3: 125 differing luma samples, max |d| = 2, all in x<48 y>=112 + +## Gates +* `sub8x8_inter_split` (the r3 gate, SPLIT + VERT arms) unchanged — HORZ arm NOT added, since + the shape is still refused. +* No new gate for the masked-compound fix: measured, the only streams that reach a rect + masked-compound block are HORZ ones, which the refusal blocks. `deferred: gate for the rect + compound_type/wedge_idx row — no non-HORZ recipe found that produces a rect block with + comp_group_idx==1 — unblocked by either the HORZ lift or a `--enable-masked-comp` sweep on + rect-heavy square-only content.` +* Full suite: unit `intersub8-suite-r4-1788331918.service` -> `$HOME/.cache/intersub8-suite-r4.log`, + STILL RUNNING at hand-off (74 ok, 0 FAILED, no `test result:` line yet). NOT a green claim. + r3's unit (`intersub8-suite-1788331066`) was stopped as charter-ordered; its log had 73 ok / + 0 FAILED and no `test result:` line at stop time. + +## Film probe +0.4 s copy-extract at 0 s of the 2160p 10-bit HDR AV1 film yields only 1817 bytes (one OBU +set, no full frame); the probe returns counters (`horz8x4=0`) and no refusal, so the census's +start_s=0 refusal ("an inter partition below 8x8") is NOT reproduced by that extract. +`deferred: HG below-8x8 census probe — the bounded extract is too small to reach the block — +unblocked by extracting from a keyframe offset (census4 reelb4.tsv start_s column).` + +## Residue +* fix-now(next round): the |d|<=2 luma band under HORZ. Reproduce with + `EC_AV1_SUB8_HORZ=1` on `~/.cache/intersub8-tmp/t_10_12_3.obu` (regenerate: + `./gen_t.sh 12 3 10 m1.obu --enable-rect-partitions=1`). +* accepted: `COMPOUND_WEDGE` on a rect block refused (rect wedge codebooks unimplemented). diff --git a/lanes/sqdrift-r1.handoff.md b/lanes/sqdrift-r1.handoff.md new file mode 100644 index 00000000..7f93251d --- /dev/null +++ b/lanes/sqdrift-r1.handoff.md @@ -0,0 +1,40 @@ +# lane-sqdrift r1 -> r2 handoff + +Branch `lane-sqdrift` @ 6edd5af (off main 85887c7). Worktree +`/home/user/Documents/Code/Rust/edith_codecs-sqdrift`, `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-sqdrift`. + +## Do NOT redo any of this (all measured, see lanes/sqdrift-r1.report.md for the EVIDENCE lines) +* Stream: `/home/user/.cache/sqdrift/gen.sh` -> `s.obu`, sha256 + `c6af4fb4ebdc3d74dcfa0c945c0ef2d5e1e3a0902891d9e0a97a5608776b5d55`, hashed twice. +* Frames 0-3 byte-exact pre-filter AND post-filter (both dumps). No poisoned reference. +* Frame 4 damage = exactly the last SB, mi(16,32), PARTITION_NONE at 64x64, INTRA in an + inter frame (aomdec prints neither EC_MODE nor EC_IMODE for it). +* We enter that block IN SYNC: our `pre_rng=33730` == aomdec `EC_PART ... rng=33730`. +* TX_64X64 dequant + inverse transform EXONERATED against real libaom (0/4096). +* The stream contains no rect/AB/1:4 partition at all; main's 1:4-strip refusal on it is + a phantom of this desync. +* aomdec's prediction there is none of DC/SMOOTH/SMOOTH_V/SMOOTH_H/PAETH computed from + the true neighbours, so its coefficients differ too -> a SYMBOL diverges, not a predictor. + +## The one open question +Which symbol between `partition_w64` and the end of that block. Ordered suspects: +1. `read_delta_q_params` -- delta_q IS present (base_q_idx 80/110/168) and this is the + only block in the stream with `bsize == sb_size`, libaom's own special case + (`decodemv.c`: `if (bsize != cm->seq_params->sb_size || !mbmi->skip_txfm)`), incl. the + `delta_lf` sub-read. +2. `skip` / `is_inter` ctx at a 64x64 block. +3. `y_mode[size_group_lookup[BLOCK_64X64]=3]` CDF content (adaptation drift; frames 0-3 + never crossed a decision boundary). +4. `tx_depth`: `--enable-tx-size-search=0`, so TX_64X64 must code no depth symbol. +5. The 64x64 luma coefficient read (eob_pt alphabet at TX_64X64, `all_zero` ctx). + +## Instruments already in the tree +* `EC_AV1_TRACE=1` -> `TRACE partition_w64 ... pre_rng=`. +* `EC_IIS=1` -> `TRACE iis px= py= side= w= h= sg= mode= skip=` at the square + intra-in-inter `y_mode` read (decode.rs, right after `cdfs.y_mode[size_group_wh(..)]`). +* `/home/user/.cache/sqdrift/h.c` -- libaom inverse-transform harness. Build: + `gcc -O1 -o h h.c -I$SRC -I$BUILD -I$SRC/apps $BUILD/libaom.a -lm -lpthread`. + MUST call `av1_rtcd(); aom_dsp_rtcd();` first or `av1_idct64` is a NULL fn ptr (segfault). +* The oracle has NO range print inside `read_intra_block_mode_info` / + `read_delta_q_params`. Add one via `scripts/instrument-aom-oracle.sh` into a PRIVATE + build dir; never rebuild the shared `~/.cache/aom-oracle/build/aomdec` in place. diff --git a/lanes/sqdrift-r1.report.md b/lanes/sqdrift-r1.report.md new file mode 100644 index 00000000..bb4645ae --- /dev/null +++ b/lanes/sqdrift-r1.report.md @@ -0,0 +1,100 @@ +# lane-sqdrift r1 -- the square-only silent pixel drift, localised to ONE block + +## Verdict: RED (defect localised and bounded, not yet fixed). No refusal lifted. + +## The stream (pinned, reproducible) + +`/home/user/.cache/sqdrift/gen.sh` (kept; recipe = lane-intra14's gate recipe with +`--enable-rect-partitions=0`): 192x128 8-bit `mandelbrot start_scale=4.76 end_scale=0.004 +end_pts=8 rate=25`, hue=s=0, `-t 0.32`, real `~/.cache/aom-oracle/build/aomenc` +`--cpu-used=1 --cq-level=55 --min-partition-size=16 --max-partition-size=64 +--enable-tx-size-search=0 --kf-min/max-dist=1000 --threads=1 --row-mt=0`, order-hint / +warped / obmc / masked / interintra / dist-wtd / diff-wtd / onesided / ab / 1to4 / +filter-intra / smooth-intra / paeth-intra / directional-intra / angle-delta / cdef / +restoration / palette / intrabc / cfl / ref-frame-mvs ALL `=0`. +sha256 `c6af4fb4ebdc3d74dcfa0c945c0ef2d5e1e3a0902891d9e0a97a5608776b5d55`, hashed twice +from two independent encodes -- reproducible. + +## What is actually wrong (measured, not reasoned) + +1. `aomdec EC_TRACE=1` partition histogram over the whole stream: only + `value=0 (NONE)` and `value=3 (SPLIT)` at bsize 12/9/6. **No rect, no AB, no 1:4 + partition exists in this stream at all** -- so main's refusal + "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path", which this + stream stops at on `main@85887c7`, is a PHANTOM read out of an already-diverged + bitstream (class `refusal-from-own-desync`). +2. Pre-loop-filter dumps, our `EC_AV1_PREFILT_DUMP` vs aomdec's, per decode-order frame: + f0..f3 **byte-exact (luma AND chroma)**; f4 luma 3540 samples wrong, max |d| = 6, + **chroma exact**. Post-filter reference dumps (`EC_AV1_FINAL_DUMP`) f0..f3 exact too, + so no reference frame is poisoned going into f4. +3. The f4 damage is EXACTLY one superblock: bbox x 128..191, y 64..127 -- the last SB, + mi (16,32), which frame 4 codes as `PARTITION_NONE` at 64x64. It is the ONLY + 64x64 PARTITION_NONE block in any inter frame of this stream. +4. Range ladder at that block's entry: our pre-read msac range for its `partition_w64` + symbol is **33730**, identical to aomdec's `EC_PART mi_row=16 mi_col=32 bsize=12 + ctx=15 tell=25598 rng=33730`, and the ctx matches too (aomdec prints `bsl*4+ctx` + = 12+3, ours `ctx=3`). **We enter that block bit-exactly in sync.** +5. The divergence is INSIDE that block. aomdec prints neither `EC_MODE` (= + `read_inter_block_mode_info`) nor `EC_IMODE`, i.e. libaom takes + `read_intra_block_mode_info` -- an INTRA block inside an inter frame. Our decoder + takes the same arm and reads `y_mode[size_group=3] = 0 (DC_PRED)` + (new `EC_IIS=1` rung: `TRACE iis px=128 py=64 side=64 w=64 h=64 sg=3 mode=0 skip=false`). + Our reconstruction there is a FLAT 93, which is exactly + `(sum(above 64) + sum(left 64) + 64) >> 7` -- textbook DC_PRED. aomdec's + reconstruction is not flat. +6. The luma residual is NOT the defect. The block's 5 non-zero levels were pushed + through libaom itself (`av1_inv_txfm2d_add_64x64_c`, real `libaom.a`, dequant + replicated from `decodetxb.c:361-374` with `av1_dc/ac_quant_QTX(80,0,8)` = 74/87 and + `av1_get_tx_scale` shift 2): **0 mismatches** against our own `residual` for those + levels (and 2171 with the axes swapped, so the layout is right too). Our TX_64X64 + dequant + inverse transform is exact. +7. Everything after that block drifts: frame 5's SB0 `partition_w64` still reads 3, SB1 + reads 8 where aomdec reads 3 -- a CDF-state divergence carried across the frame + boundary (frame 5 restarts its own msac, so only the adapted CDFs can carry the + damage). f5..f7 then drift to ~24k samples / max |d| ~220 as they predict from f4. + +So: **the first divergent symbol is in the mode-info or coefficient read of a 64x64 +PARTITION_NONE intra-in-inter block, after `partition_w64` and at/after `y_mode`.** +The candidate set is now tiny: `skip`, `read_delta_q_params` (this is the ONE block in +the stream where `bsize == sb_size`, the exact case libaom's +`read_delta_q_params` special-cases), `is_inter`, `y_mode[3]`, `uv_mode_cfl[0]`, +`tx_depth` (`--enable-tx-size-search=0`, so a TX_64X64 must code no depth symbol), or the +64x64 coefficient read itself. `base_q_idx` in our trace takes three values (80/110/168) +across the stream, i.e. **delta_q IS present in this stream** -- that makes the +`bsize == sb_size` delta-q exception a first-class suspect. + +## What changed (all env-gated instrumentation, no decode behaviour) + +* `crates/ec-av1/src/decode.rs` (`decode_inter_frame_tile_with_cdfs`'s `partition_w64` + read) -- the `EC_AV1_TRACE` line now carries `pre_rng=`, the msac range BEFORE the + symbol, which is what makes it directly comparable to aomdec's `EC_PART ... rng=` + (class `compare-range-not-tell`). This is the measurement that proved fact 4. +* `crates/ec-av1/src/decode.rs` (square intra-in-inter `y_mode` read) -- new `EC_IIS=1` + rung printing `px/py/side/w/h/size_group/mode/skip` for every intra block in an inter + frame. That is fact 5. + +## Gate + +None added -- there is no fix to gate yet. Adding a gate now would pin the defect, not a +capability; the reproducing recipe is `scripts`-free and lives in this report plus +`/home/user/.cache/sqdrift/gen.sh`. + +## EVIDENCE + +EVIDENCE: /home/user/.cache/sqdrift/{op,aom}.f0..f4 | our EC_AV1_PREFILT_DUMP vs aomdec EC_AV1_PREFILT_DUMP on the pinned stream, every decode-order frame compared Y/U/V | f0-f3 0 bad samples; f4 luma 3540 bad, max |d| 6, chroma 0 bad, bbox exactly x128-191 y64-127 +EVIDENCE: /home/user/.cache/sqdrift/{of,af}.f0..f4 | EC_AV1_FINAL_DUMP (post-filter reference buffers) both decoders | f0-f3 0 bad; f4 first bad (145,58), 3848 bad, max 6 -- deblocking only spreads the f4 damage, no reference is poisoned earlier +EVIDENCE: /home/user/.cache/sqdrift/aom.trace | aomdec EC_TRACE=1 partition histogram, whole stream | bsize12 {0:2, 3:46}, bsize9 {0:58, 3:126}, bsize6 {0:504} -- zero rect/AB/1:4 partitions, so main's 1:4-strip refusal on this stream is a phantom +EVIDENCE: our EC_AV1_TRACE pre_rng vs /home/user/.cache/sqdrift/aom.both | range ladder at frame 4 SB (16,32) | ours pre_rng=33730 ctx=3, aomdec rng=33730 ctx=15(=12+3) -- in sync at block entry, so the defect is inside the block +EVIDENCE: /home/user/.cache/sqdrift/{h.c,aomres1.txt,ourres.txt} | the block's 5 non-zero levels through real libaom av1_inv_txfm2d_add_64x64_c vs our residual | 0/4096 mismatches (swapped-axis control: 2171) -- TX_64X64 dequant+inverse is exact +EVIDENCE: EC_IIS=1 rung on the pinned stream | our intra-in-inter mode read at the failing block | `TRACE iis px=128 py=64 side=64 w=64 h=64 sg=3 mode=0 skip=false`, reconstruction flat 93 = DC_PRED of the true neighbours; aomdec's is not flat (SMOOTH/SMOOTH_V/SMOOTH_H/PAETH all rejected numerically too, so aomdec's coefficients differ as well -- the divergence is a SYMBOL, not a predictor) + +## Residue + +* fix-now (next round, r2): bisect the ~6 remaining symbols of that one block. The + cheapest decisive instrument is a `pre_rng` print on every symbol of + `read_inter_frame_mode_info`'s square intra arm plus an aomdec-side `rng` print at the + same points in `read_intra_block_mode_info` / `read_delta_q_params` (the oracle has no + print there today -- add one to `scripts/instrument-aom-oracle.sh`, do NOT rebuild the + shared aomdec in place). Start with `read_delta_q_params`' `bsize == sb_size` exception. +* deferred: 10-bit arm -- unblocked by the fix; there is nothing to gate yet. +* accepted: the two `EC_*` trace rungs ship as permanent debug instrumentation. diff --git a/lanes/sqdrift-r2.report.md b/lanes/sqdrift-r2.report.md new file mode 100644 index 00000000..936e13f8 --- /dev/null +++ b/lanes/sqdrift-r2.report.md @@ -0,0 +1,93 @@ +# lane-sqdrift r2 -- the square-only silent drift is the no-CFL `uv_mode` alphabet + +## Verdict: GREEN. Root cause confirmed by ablation, gated with a new real-aomenc gate. + +Tip `2b750e6` on `lane-sqdrift` (base main `85887c7`). + +## 1. What the divergence was + +r1 had localised it to one 64x64 `PARTITION_NONE` INTRA block inside an INTER frame +(frame 4, mi(16,32) = the last superblock), entered bit-exactly in sync (`pre_rng=33730` +== aomdec's `rng=33730`), with TX_64X64 dequant+inverse already exonerated against real +libaom. The open question was "which symbol inside that block". + +Answer: `uv_mode`. libaom's `is_cfl_allowed` (`blockd.h`: `block_size_wide[bsize] <= 32 && +block_size_high[bsize] <= 32`, spec 5.11.5) excludes a 64-axis block from CFL, so its +`uv_mode` comes off the **13-symbol `uv_mode_no_cfl`** alphabet. We read the 14-symbol +`uv_mode_cfl` one: the same `DC_PRED` VALUE, a different interval narrowing, and the tile +desynced from that block on (class `wrong-alphabet-same-value`). + +The fix was found independently by lane-sbrect10 (`9f1f108`) and is merged here, not +rewritten: commit `cbcbf13` merges `lane-sbrect10` into this branch. `decode.rs` gets the +`cfl_allowed = write_w.max(write_h) <= 32` test at the intra-in-inter square arm plus the +same `is_cfl_allowed` bound enforced at the two funnels `read_intra_mode` / +`read_intra_mode_rect`, and the `nocfl_uv_mode_hits()` witness counter. No decoder line in +this round is mine; my round's contributions are the confirmation, the ablation, and the +square-only gate. + +## 2. The decisive before/after, same stream, same tree + +Pinned stream `/home/user/.cache/sqdrift/keep-s.obu`, sha256 +`c6af4fb4ebdc3d74dcfa0c945c0ef2d5e1e3a0902891d9e0a97a5608776b5d55` (r1's `gen.sh`, +hashed twice from two independent encodes), compared PRE-LOOP-FILTER, per decode-order +frame, byte for byte against instrumented aomdec's own `EC_AV1_PREFILT_DUMP`: + +| | f0 | f1 | f2 | f3 | f4 | f5 | f6 | f7 | outcome | +|---|---|---|---|---|---|---|---|---|---| +| before (`cfl_allowed = true` ablation on THIS tree) | 0 | 0 | 0 | 0 | **3540** | - | - | - | REFUSED after f4: "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path" | +| after (merged fix) | 0 | 0 | 0 | 0 | **0** | 0 | 0 | 0 | 8 frames decoded, all byte-exact | + +The "before" row is not r1's memory: it is the one-line ablation +`decode.rs:18548 let cfl_allowed = true;` rebuilt and re-run in this round, then reverted +(`git diff --stat` after revert shows stream.rs only). It also re-confirms r1's finding +that the refusal main stops at on this stream is a PHANTOM of the desync -- aomdec's +partition histogram over the stream contains no rect partition at all (class +`refusal-from-own-desync`). + +## 3. The gate (new) + +`crates/ec-av1/src/stream.rs:6900` +`a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact` + +The SQUARE-ONLY twin of lane-sbrect10's gate, pinning r1's recipe: real aomenc, +192x128 mandelbrot (`start_scale` 4.76/3.20), cq 55/45, `--cpu-used=1 --sb-size=64 +--enable-rect-partitions=0 --enable-ab-partitions=0 --enable-1to4-partitions=0 +--min-partition-size=16 --max-partition-size=64 --enable-tx-size-search=0`, 8 decode-order +frames, **both bit depths**. Rect OFF is what makes the 64x64 `PARTITION_NONE` a WHOLE +superblock (`bsize == sb_size`), a shape the sibling gate's rect-on recipe does not pin; +8 frames of drift means a desync that survives one frame still fails here. + +Asserts: every decode-order frame's Y/U/V compared against ffmpeg (a mismatch of ANY shape +is a failure, never a SKIP -- so out-of-scope mismatches are structurally 0); a decode +error must be a named `unsupported` refusal; and `nocfl_uv_mode_hits` delta per attempt +must be > 0 on at least one pixel-exact attempt per depth. + +Result (`--exact --nocapture --test-threads=1`), 10.4 s: + +* 8-bit: 0 named refusals, **4/4 pixel-exact attempts**, 6 no-CFL `uv_mode` reads, 0 carried none +* 10-bit: 0 named refusals, **4/4 pixel-exact attempts**, 6 no-CFL `uv_mode` reads, 0 carried none + +No refusal string is removed in this round: the refusal this stream used to hit was never +about this shape. + +## 4. Suite + +`cargo test -p ec-av1 --lib` under `systemd-run --user --unit=sqdrift-suite-r2-...`, +log `$HOME/.cache/sqdrift-suite-r2.log`: **379 passed, 0 failed, 33 ignored** in 958.68 s (r1 baseline on the unfixed tree never completed). + +## EVIDENCE + +EVIDENCE: /home/user/.cache/sqdrift/np.f0..f7 vs aom.f0..f7 | decode_probe with EC_AV1_PREFILT_DUMP on the pinned stream (sha256 c6af4fb4...) after merging lane-sbrect10, cmp -l per decode-order frame Y+U+V | 0 differing bytes on all 8 frames (r1: f4 3540 wrong luma samples, then refusal) +EVIDENCE: /home/user/.cache/sqdrift/ab.f0..f4 | same binary with decode.rs:18548 ablated to `cfl_allowed = true`, rebuilt, re-run, then reverted | f0-f3 0, f4 3540 differing bytes, decode then REFUSES "an intra-coded 1:4 ... rect strip on the inter block path" -- the phantom refusal is produced by this desync alone +EVIDENCE: cargo test -p ec-av1 --lib -- --exact --nocapture a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact | 4 attempts x 2 bit depths of real aomenc, rect partitions off, every decode-order frame vs ffmpeg | ok in 10.38s; 8-bit 4 exact/6 hits, 10-bit 4 exact/6 hits, 0 refusals, 0 attempts carried none + +## Residue + +* deferred(lane-intra14 re-runs its own gate): `lanes/intra14-r2.report.md` records its + blocker as "decode-order frame 3/4 luma ~3.7-4.5k samples at max |d| 6..17, first diff + around x=128..141, y=58..59, then frames 5-7 drift to ~24k at max |d| ~220" on the same + 192x128 mandelbrot source -- the identical signature to this lane's, at the identical + coordinates. Very likely the same defect, so its two `#[ignore]`d 1:4-strip arms should + be re-measured on a tree carrying this fix. Not measured here: its recipe (1:4 on) is + another lane's surface. +* accepted: r1's `EC_AV1_TRACE pre_rng` and `EC_IIS` rungs stay as debug instrumentation. diff --git a/lanes/uv8-r1.handoff.md b/lanes/uv8-r1.handoff.md new file mode 100644 index 00000000..62b181fc --- /dev/null +++ b/lanes/uv8-r1.handoff.md @@ -0,0 +1,64 @@ +# lane-uv8 r1 — HANDOFF (RED: implemented, NOT gated) + +## What is implemented (`crates/ec-av1/src/decode.rs`, `decode_inter_block8`'s intra arm) +Mirrors libaom `read_intra_block_mode_info` (`av1/decoder/decodemv.c:1178-1220`, read from +`~/.cache/aom-oracle/src`) for an INTRA 8x8 leaf inside an INTER frame: + +- `uv_mode` over the CFL-allowed alphabet (`cdfs.uv_mode_cfl[mode]`; BLOCK_8X8 is inside + `is_cfl_allowed`'s 32x32 bound), then `read_cfl_alphas` when `UV_CFL_PRED`, then + `angle_delta_uv` off `angle_delta[uv_mode - V_PRED]` (`get_uv_mode` is the identity over + `V_PRED..=D67_PRED`) — the exact order libaom reads them in. +- `uv_predict_mode = get_uv_mode(uv_mode)`; chroma prediction, chroma `default_tx_type` + (`read_plane`'s `predict_mode` arg → `default_intra_tx_type`, DCT for CfL) and the CfL AC + (`cfl_ac_q3(y, px, py, 8)` over the leaf's 4x4 chroma) all take it. +- `smooth_neighbor_uv` from `Neighbours::smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c)` + (chroma edge filter reads the CHROMA neighbour's uv_mode — reconintra.c:974), and the leaf's + LUMA `smooth_neighbor` from `modes_above_left_mi` (it passed a hardcoded `false` before). +- `palette_uv_mode` is now read only when `uv_mode == DC_PRED` (`read_palette_mode_info`); + it was read unconditionally, harmless only because every non-DC uv_mode was refused. +- Tail: the leaf now stamps its mode bands (`above_uv_mode[c]`/`left_uv_mode[r]`, + `record_mode_mi`, `record_uv_mode_mi`, 2x2 mi) — it stamped none at all, so a neighbour read + a stale coarse SUB slot. An inter leaf stamps `DC_PRED`, what libaom stores. +- New per-leaf counters `decode::intra_in_inter8_uv_hits() -> (dir, smooth/paeth, cfl)`. + +## Refusal state +`"a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)"` is REMOVED +from decode.rs and from `refusal_inventory.rs::CAPABILITY_CLAIMS`. **This lift is NOT gated** — +see below. If the next round cannot gate it, restoring both lines is the honest move. + +## Gate (written, never observed a firing attempt) +`stream.rs::uv_mode_in_inter8_gate(bit_depth, tile_columns)` + 3 tests (8-bit, 10-bit, 2-tile): +192x128, 8 frames, mandelbrot zoom + hard cut at frame 4 + seeded `noise`, chroma NOT +desaturated, 30 attempts, cq 12..40, `--min-partition-size=8 --max-partition-size=32 +--sb-size=64 --enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1 +--enable-directional-intra=1`, per-attempt counter deltas, every decode-order frame compared, +no SKIP on decode error. The y4m goes through a temp FILE: feeding aomenc on stdin while its +~100 KB OBU fills the stdout pipe DEADLOCKS (measured, 3 min into attempt 0). + +RESULT: 8-bit arm ran, 30/30 attempts REFUSED, 0 compared → the gate fails as designed. + +## The blocker (pre-existing, NOT this round's change) +Every `--min-partition-size=8` inter stream refuses. `--min-partition-size=16` on the same +recipe decodes 8/8 frames. The refusals name tools the encoder was explicitly told to disable: +`--enable-rect-partitions=0 --enable-ab-partitions=0 --enable-1to4-partitions=0` yet we refuse +"an inter 16x16-level AB or 1:4 partition" / "a non-skip rectangular strip"; and +`--enable-angle-delta=0` yet we refuse "a nonzero angle delta on an 8x8 intra leaf". Class +[[refusal-from-own-desync]]: those are our own desync, not encoder output. +Ablation: the same refusals appear with `--enable-cfl-intra=0 --enable-smooth-intra=0 +--enable-paeth-intra=0 --enable-directional-intra=0`, where this round's code is inert → +the desync is INDEPENDENT of this round. +The KEY frame of the same recipe (`--limit=1`, min8) decodes PIXEL-EXACT vs aomdec +(md5 860b50e830271fa57fb60e4a76eb83ec both) — so the 8x8 leaf's key-frame path is fine and the +divergence is in an INTER frame. + +## Exact next step +Bisect the first inter-frame divergence with the oracle mode ladder. Note the trace semantics +(cost this round an hour): oracle `EC_IMODE` = KEY-frame blocks only, oracle `EC_MODE` = +INTER blocks only (an intra block inside an inter frame prints NEITHER), while ours prints +`EC_MODE` for EVERY block of an inter frame. So the oracle's `EC_MODE` (mi_row, mi_col) +sequence must be an ordered SUBSEQUENCE of ours; the first ref entry that ours never produces +is the first structurally divergent block. On `~/.cache/uv8-tmp/o.obu` (recipe above, cq 26, +cpu-used 0) that subsequence match stops after 79 of the ref's frame-1 entries, with ref next +at mi (12,8) — start there with a range ladder (compare RANGE, never tell()). +Scripts: `~/.cache/uv8-tmp/{in.y4m,sweep.sh,sweep2.sh,sweep3.sh}`; probe +`$HOME/.cache/cargo-target-uv8/debug/examples/decode_probe [out.yuv]`. diff --git a/lanes/uv8-r2.handoff.md b/lanes/uv8-r2.handoff.md new file mode 100644 index 00000000..5743e12a --- /dev/null +++ b/lanes/uv8-r2.handoff.md @@ -0,0 +1,65 @@ +# lane-uv8 r2 — HANDOFF (merge done, root cause NARROWED to one block, gate still RED) + +## Merged into lane-uv8 (tip f5c8dbf) +- `a9b4468` main aa83400 (clean). +- `5dc9707` lane-interp3 `10b801a` (clean). +- `c3ead8c`/prev `af47324` lane-intersub8 — CONFLICTS resolved: + * `decode_inter_block8` compound-leaf interp read: kept **interp3's** copy (it adds the + `gm_nontrans_c || skip_mode` suppression and the COMPOUND8_FILTER_HITS counter); dropped + intersub8's duplicate read (two reads = one extra symbol). + * `resolve_interp_filter` tail: kept BOTH (interp3's DUAL_FILTER_DIFF_HITS + intersub8's EC_IF trace). + * `refusal_inventory.rs`: union of both lists, then deleted + "an inter partition below 8x8 (...lane-sub8 scoped to intra)" — intersub8 landed that capability + (the `the_decode_path_refuses_exactly_the_listed_cases` test named it). +- `6561ec4` lane-cdef `8c6065e` (clean). +- `c3ead8c` lane-sqdrift `7d498c0` — stream.rs conflict was two whole appended test fns interleaved; + resolved by `git checkout --ours stream.rs` + `patch -p1` of `git diff 85887c7 7d498c0 -- stream.rs` + (both new tests present: `..._reads_the_no_cfl_uv_alphabet`, `..._square_only_inter_sequence...`). +- `crates/ec-av1/src/cdf.rs` byte-identical to main (`git diff --stat main -- cdf.rs` empty). +- `f5c8dbf` adds EC_TRACE_MODE_STEP ladder prints in the 8x8 intra-in-inter arm + (`EC_ISTEP ... name=use_filter_intra` in the oracle's exact format, plus `EC_ISTEP8 name=modes`). + +## Gate result on the merged tree (RED, same shape as r1) +`uv8-gate-r2.log` (unit uv8-gate-r2-1788332583, before the trace commit): all three arms +30/30 named refusals, counted-exact=0, uncounted-exact=0. Re-armed after the merge as unit +**uv8-gate-r2b** → `$HOME/.cache/uv8-gate-r2.log`, then the full suite in the SAME unit → +`$HOME/.cache/uv8-suite-r2.log`. +Refusal histogram over the 90 attempts: 31x inter 16x16-level 1:4, 21x nonzero angle delta on an +8x8 intra leaf, 13x inter 8x8 HORZ, 10x non-skip rect strip, 5x intra 1:4 rect strip, 3x inter SB AB, +3x 128x128 SB HORZ/VERT/AB, 2x intra 4x4 in sub-8x8 split, 1x 32x64 split TU, 1x intra 8x4/4x8. +All still class [[refusal-from-own-desync]] — proven below. + +## ROOT CAUSE LOCALISED (this is the round's real result) +Stream `~/.cache/uv8-tmp/a0.obu` (regenerate: `~/.cache/uv8-tmp/g2.sh 42 12 a0.obu`, exact gate +recipe, 8-bit, seed 42, cq 12; note it is a **128x128 superblock** stream — the gate recipe has no +`--sb-size=64`). +1. `EC_TRACE=1 aomdec` partition histogram (`ref_part.txt`): the reference codes **only** NONE and + SPLIT (bsize 15/12/9 value=3, bsize 6 value 0|3, bsize 3 value 0). There is no rect/AB/1:4 + partition anywhere in the stream → every refusal above is our own desync. +2. Partition range ladder (ours `EC_TRACE_PART=1` vs ref, ignoring the ctx print convention: + ref prints `4*bsl + ctx`): decode-order frame 1 matches 138/138; frame 2 first range divergence + at element 119 — ref `(0,36,bsize=6,rng=48648)` vs ours `rng=38664`. The previous element, + the 8x8 partition at **mi (2,34)**, still matches (rng 44040). +3. `EC_MODE` subsequence: ref's entries are consumed in order up to `(2,32)`; ours' next block + `(0,36)` starts at rng 57984 vs ref 32884. Ref prints no EC_MODE for `(2,34)` → that block is an + **INTRA 8x8 leaf inside inter frame 2**. +4. `EC_TRACE_MODE_STEP` ladder at that block: ours reads `use_filter_intra val=1 rng=64248` and + `filter_intra_mode val=0 rng=43964` — **bit-identical to the oracle**. Our decoded modes there are + `y=DC_PRED, uv=13 (UV_CFL_PRED)` (`EC_ISTEP8` line). + => the whole mode-info half of this leaf, including the new non-DC/CfL uv path, is IN SYNC. + The desync is in what follows: `read_block_tx_size` or the leaf's COEFFICIENTS. + +## EXACT NEXT STEP +Both coefficient traces are already dumped: `~/.cache/uv8-tmp/ref_co.txt` (761992 lines) and +`ours_co.txt` (260655). Formats: ref `EC_COEFF plane=.. row=.. col=.. tx_size=.. rng=..` + +`EC_COEFF_STEP tag=all_zero|tx_type|base|br ...`; ours prints the STEP lines only (no EC_COEFF +header with plane/row/col). Align the two `EC_COEFF_STEP` streams and find the first `rng` +divergence — it must be inside the block at mi (2,34) of decode-order frame 2, i.e. the FIRST +filter-intra + CfL 8x8 intra leaf of an inter frame. Prime suspects, in order: + (a) the CfL AC / chroma `TxbSet::Chroma4` txb ctx on a leaf whose luma is filter-intra; + (b) `read_block_tx_size` for an intra block in an inter frame at 8x8 (`--enable-tx-size-search=0` + here, so check whether a symbol should be read at all); + (c) the luma `intra_ext_tx` row: `read_plane` gets `filter_intra` and applies `fi_tx_row`, but the + CHROMA calls pass `mode` (raw luma mode) as the tx-row arg with `filter_intra=None` — verify + against libaom `av1_read_tx_type` (chroma tx type is inferred, so this should be inert; prove it). +Do NOT re-do steps 1-4; they are pinned above with their artifacts. diff --git a/lanes/uv8-r3.report.md b/lanes/uv8-r3.report.md new file mode 100644 index 00000000..d8b3fc41 --- /dev/null +++ b/lanes/uv8-r3.report.md @@ -0,0 +1,42 @@ +# lane-uv8 r3 — GREEN (root cause: wrong tx_type ALPHABET on the 8x8 intra-in-inter leaf) + +## Root cause +`decode_inter_block8`'s INTRA arm passed a hardcoded `TxbSet::Luma8` to `read_plane` for the +leaf's 8x8 luma transform. `TxbSet::Luma8` is the `reduced_tx_set == 1` set +(`EXT_TX_SET_DTT4_IDTX`, FIVE types); with `reduced_tx_set == 0` libaom's +`av1_get_ext_tx_set_type` (`av1/common/blockd.h`) returns, for `is_inter == 0` and +`tx_size_sqr == TX_8X8`, `EXT_TX_SET_DTT4_IDTX_1DDCT` — SEVEN types +(`TxbSet::Luma8Set1`). Same symbol, different alphabet: the CDF narrowing differed, so the +msac range diverged at the leaf's first `tx_type` and every following block desynced. The +desync manufactured the 30/30 "named refusals" the r1/r2 gate logs showed +(class [[refusal-from-own-desync]] + [[wrong-alphabet-same-value]]). + +Charter suspect (1) (the `fimode_to_intradir` row) was already correct: `fi_tx_row` is applied +at every luma `txb` call site including this one, and `fimode_to_intradir[0] == DC_PRED` +equals this block's `y_mode` anyway, so that row was inert here. + +## Change +- `crates/ec-av1/src/decode.rs:22057` — `TxbSet::Luma8` -> `txbset_for(8, reduced_tx_set)` + (`reduced_tx_set` was already a parameter of `decode_inter_block8`). +- `crates/ec-av1/src/stream.rs:5897` — gate `counted` predicate tightened from + "sum nonzero" to "all three uv classes fired on the same pixel-compared attempt". + +## Sweep (class: hardcoded reduced-set TxbSet) +`grep -n 'TxbSet::Luma\(4\|8\|16\|32\),' decode.rs` — the only reduced-sensitive hardcodes are +sizes 8 and 4; after this fix there are ZERO outside `txbset_for`/`txbset_for_inter`. Every +`Luma16`/`Luma32` literal is alphabet-invariant to `reduced_tx_set` (`txbset_for` maps 16 and +32 identically for both values). The rect-strip and >=16 square intra-in-inter arms already go +through `txbset_for`/`txbset_for_inter` (decode.rs:6053, 7167, 7777, 7857, 9594, 11075). + +## EVIDENCE +EVIDENCE: ~/.cache/uv8-tmp/ref.tu + ours3.tu | aomdec EC_TRACE_COEFF vs our EC_TRACE_COEFF on ~/.cache/uv8-tmp/a0.obu, per-TU (all_zero,eob) msac range ladder | before: first divergence at TU-line 3392 (ref eob rng=32776, ours 34568; the preceding tx_type read was ref rng=33532 vs ours 35240 at plane=0 tx_size=1, the mi(2,34) filter-intra leaf of decode-order frame 2) — after: 13986/13986 lines identical, whole stream, decode_probe rc=0 with no refusal +EVIDENCE: $HOME/.cache/uv8-gate-r3.log | `cargo test -p ec-av1 --lib -- --test-threads=1 --nocapture non_dc_chroma_8x8_intra_leaf` | 3 passed / 0 failed; every arm exact on attempt 0 with all three classes firing — 8bit/1tile dir 159 smooth-paeth 172 cfl 211; 10bit/1tile 112/126/120; 8bit/2tile 83/66/80; buckets counted-exact=1 uncounted-exact=0 named-refusals=0 on each + +## Residue +- deferred: the 8x8 intra-in-inter leaf whose `tx_depth` splits to four TX_4X4 units is still + refused by name (decode.rs ~21996). Unblocked by an arm with `--enable-tx-size-search=1` + plus a 4x4-TU prediction loop in this leaf path — out of this lane's charter, which fixed the + depth-0 alphabet. Its refusal string stays in refusal_inventory.rs. +- accepted: `frames` from `decode_stream` is decode order; the gate recipe has + `--lag-in-frames=0 --auto-alt-ref=0`, so decode order == display order and all 8 frames are + compared (class [[gate-blind-to-hidden-frames]] does not apply).