diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index 8b0452a7..781d7659 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -33,10 +33,11 @@ fn main() { println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?"); } Ok(frames) => { - println!("OK: {} frames decoded", frames.len()); - // Optional second arg: dump the decoded planes as raw yuv420p so a - // pixel diff against `ffmpeg -i s.obu -f rawvideo` needs no test harness. - if let Some(out) = std::env::args().nth(2) { + // Optional second arg, or EC_PROBE_OUT=: dump the decoded + // planes as raw yuv420p so a pixel diff against `ffmpeg -i s.obu + // -f rawvideo` needs no test harness. + let out = std::env::args().nth(2).or_else(|| std::env::var("EC_PROBE_OUT").ok()); + if let Some(out) = out { // 8-bit only: planes are u16, take the low byte. let mut buf: Vec = Vec::new(); for f in &frames { @@ -47,6 +48,7 @@ fn main() { std::fs::write(&out, &buf).expect("writing raw planes"); println!("wrote {} bytes of yuv420p to {out}", buf.len()); } + println!("OK: {} frames decoded, {}x{}", frames.len(), frames[0].width, frames[0].height); } Err(e) => println!("REFUSED: {e}"), } diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 7b2a2f58..fda4e1ae 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -843,11 +843,11 @@ pub const NZ_MAP_CTX_OFFSET_32: [[u8; 5]; 5] = [ // `pos = col*32+row` raster (same convention [`SCAN_32X16`]'s doc comment // already documents this decoder transcribes out of). pub const NZ_MAP_CTX_OFFSET_32X64: [[u8; 5]; 5] = [ - [0, 11, 11, 11, 11], - [11, 11, 11, 11, 11], - [6, 6, 21, 21, 21], - [6, 21, 21, 21, 21], - [21, 21, 21, 21, 21], + [0, 11, 6, 6, 21], + [11, 11, 6, 21, 21], + [11, 11, 21, 21, 21], + [11, 11, 21, 21, 21], + [11, 11, 21, 21, 21], ]; /// [`NZ_MAP_CTX_OFFSET_32X64`]'s `TX_64X32` counterpart (libaom @@ -856,11 +856,11 @@ pub const NZ_MAP_CTX_OFFSET_32X64: [[u8; 5]; 5] = [ /// regardless of row -- transpose of [`NZ_MAP_CTX_OFFSET_32X64`]'s `row < 2` /// branch, same r3 fix (see that table's doc comment). pub const NZ_MAP_CTX_OFFSET_64X32: [[u8; 5]; 5] = [ - [0, 16, 6, 6, 21], - [16, 16, 6, 21, 21], - [16, 16, 21, 21, 21], - [16, 16, 21, 21, 21], - [16, 16, 21, 21, 21], + [0, 16, 16, 16, 16], + [16, 16, 16, 16, 16], + [6, 6, 21, 21, 21], + [6, 21, 21, 21, 21], + [21, 21, 21, 21, 21], ]; /// `Default_Txb_Skip_Cdf[2][2][7..10]` (spec 9.4): the all-zero flag of a @@ -5126,3 +5126,34 @@ pub const EOB_PT_16_CHROMA_CLASS1_Q0: [u16; 6] = [1904, 3354, 7763, 14647, 32768 pub const EOB_PT_16_CHROMA_CLASS1_Q1: [u16; 6] = [2497, 4096, 8866, 16993, 32768, 0]; pub const EOB_PT_16_CHROMA_CLASS1: [u16; 6] = [3192, 5032, 10297, 19755, 32768, 0]; pub const EOB_PT_16_CHROMA_CLASS1_Q3: [u16; 6] = [7297, 10767, 19273, 28194, 32768, 0]; + +/// `EOB_PT_128_CHROMA`'s class-1 sibling (`av1_default_eob_multi128_cdfs[q][1][1]`). +pub const EOB_PT_128_CHROMA_CLASS1_Q0: [u16; 9] = [2054, 3472, 5869, 14232, 18242, 20590, 26752, 32768, 0]; +pub const EOB_PT_128_CHROMA_CLASS1_Q1: [u16; 9] = [2310, 4160, 7471, 14997, 17931, 20768, 30240, 32768, 0]; +pub const EOB_PT_128_CHROMA_CLASS1: [u16; 9] = [6275, 9889, 14769, 23164, 27988, 30493, 32272, 32768, 0]; +pub const EOB_PT_128_CHROMA_CLASS1_Q3: [u16; 9] = [9165, 13282, 21150, 30286, 31894, 32571, 32712, 32768, 0]; + +/// `EOB_PT_512_LUMA`'s class-1 sibling (`av1_default_eob_multi512_cdfs[q][0][1]`). +pub const EOB_PT_512_LUMA_CLASS1_Q0: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; +pub const EOB_PT_512_LUMA_CLASS1_Q1: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; +pub const EOB_PT_512_LUMA_CLASS1: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; +pub const EOB_PT_512_LUMA_CLASS1_Q3: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; + +/// `EOB_PT_512_CHROMA`'s class-1 sibling (`av1_default_eob_multi512_cdfs[q][1][1]`). +pub const EOB_PT_512_CHROMA_CLASS1_Q0: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; +pub const EOB_PT_512_CHROMA_CLASS1_Q1: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; +pub const EOB_PT_512_CHROMA_CLASS1: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; +pub const EOB_PT_512_CHROMA_CLASS1_Q3: [u16; 11] = [3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0]; + +/// `EOB_PT_1024_LUMA`'s class-1 sibling (`av1_default_eob_multi1024_cdfs[q][0][1]`). +pub const EOB_PT_1024_LUMA_CLASS1_Q0: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; +pub const EOB_PT_1024_LUMA_CLASS1_Q1: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; +pub const EOB_PT_1024_LUMA_CLASS1: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; +pub const EOB_PT_1024_LUMA_CLASS1_Q3: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; + +/// `EOB_PT_1024_CHROMA`'s class-1 sibling (`av1_default_eob_multi1024_cdfs[q][1][1]`). +pub const EOB_PT_1024_CHROMA_CLASS1_Q0: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; +pub const EOB_PT_1024_CHROMA_CLASS1_Q1: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; +pub const EOB_PT_1024_CHROMA_CLASS1: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; +pub const EOB_PT_1024_CHROMA_CLASS1_Q3: [u16; 12] = [2979, 5958, 8937, 11916, 14895, 17873, 20852, 23831, 26810, 29789, 32768, 0]; + diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index cd587b45..c03486cb 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -214,17 +214,24 @@ pub(crate) struct Cdfs { pub eob_pt_16_luma_class1: [u16; 6], /// `eob_pt_64_luma`'s class-1 sibling (r5), see `eob_pt_16_luma_class1`. pub eob_pt_64_luma_class1: [u16; 8], - /// `eob_pt_256_luma`'s class-1 sibling (lane-txselect r2): a 16x16 luma - /// TU reaches `V_DCT`/`H_DCT` through the inter tx set - /// `EXT_TX_SET_DTT9_IDTX_1DDCT`, and libaom keeps the eob class - /// dimension at every size. + /// `eob_pt_16_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_16_chroma_class1: [u16; 6], + /// `eob_pt_64_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_64_chroma_class1: [u16; 8], + /// `eob_pt_128_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_128_chroma_class1: [u16; 9], + /// `eob_pt_256_luma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. pub eob_pt_256_luma_class1: [u16; 10], - /// The chroma class-1 siblings (lane-txselect r2): an *inter* block's - /// chroma TU inherits its luma unit's `tx_type`, so 1D classes reach - /// chroma too. + /// `eob_pt_256_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. pub eob_pt_256_chroma_class1: [u16; 10], - pub eob_pt_64_chroma_class1: [u16; 8], - pub eob_pt_16_chroma_class1: [u16; 6], + /// `eob_pt_512_luma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_512_luma_class1: [u16; 11], + /// `eob_pt_512_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_512_chroma_class1: [u16; 11], + /// `eob_pt_1024_luma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_1024_luma_class1: [u16; 12], + /// `eob_pt_1024_chroma`'s class-1 (`TX_CLASS_HORIZ`/`VERT`) sibling, see `eob_pt_16_luma_class1`. + pub eob_pt_1024_chroma_class1: [u16; 12], /// The end-of-block offset bit of a 16x16 luma transform. pub eob_extra_luma_16: [[u16; 3]; 9], /// The same, for an 8x8 luma transform. @@ -633,10 +640,15 @@ impl Cdfs { reset1(&mut self.eob_pt_16_luma); reset1(&mut self.eob_pt_16_luma_class1); reset1(&mut self.eob_pt_64_luma_class1); + reset1(&mut self.eob_pt_16_chroma_class1); + reset1(&mut self.eob_pt_64_chroma_class1); + reset1(&mut self.eob_pt_128_chroma_class1); reset1(&mut self.eob_pt_256_luma_class1); reset1(&mut self.eob_pt_256_chroma_class1); - reset1(&mut self.eob_pt_64_chroma_class1); - reset1(&mut self.eob_pt_16_chroma_class1); + reset1(&mut self.eob_pt_512_luma_class1); + reset1(&mut self.eob_pt_512_chroma_class1); + reset1(&mut self.eob_pt_1024_luma_class1); + reset1(&mut self.eob_pt_1024_chroma_class1); reset2(&mut self.eob_extra_luma_16); reset2(&mut self.eob_extra_luma_8); reset2(&mut self.eob_extra_luma_4); @@ -858,6 +870,27 @@ impl Cdfs { cdf::EOB_PT_64_LUMA_CLASS1, cdf::EOB_PT_64_LUMA_CLASS1_Q3, ), + eob_pt_16_chroma_class1: pick( + q_ctx, + cdf::EOB_PT_16_CHROMA_CLASS1_Q0, + cdf::EOB_PT_16_CHROMA_CLASS1_Q1, + cdf::EOB_PT_16_CHROMA_CLASS1, + cdf::EOB_PT_16_CHROMA_CLASS1_Q3, + ), + eob_pt_64_chroma_class1: pick( + q_ctx, + cdf::EOB_PT_64_CHROMA_CLASS1_Q0, + cdf::EOB_PT_64_CHROMA_CLASS1_Q1, + cdf::EOB_PT_64_CHROMA_CLASS1, + cdf::EOB_PT_64_CHROMA_CLASS1_Q3, + ), + eob_pt_128_chroma_class1: pick( + q_ctx, + cdf::EOB_PT_128_CHROMA_CLASS1_Q0, + cdf::EOB_PT_128_CHROMA_CLASS1_Q1, + cdf::EOB_PT_128_CHROMA_CLASS1, + cdf::EOB_PT_128_CHROMA_CLASS1_Q3, + ), eob_pt_256_luma_class1: pick( q_ctx, cdf::EOB_PT_256_LUMA_CLASS1_Q0, @@ -872,19 +905,33 @@ impl Cdfs { cdf::EOB_PT_256_CHROMA_CLASS1, cdf::EOB_PT_256_CHROMA_CLASS1_Q3, ), - eob_pt_64_chroma_class1: pick( + eob_pt_512_luma_class1: pick( q_ctx, - cdf::EOB_PT_64_CHROMA_CLASS1_Q0, - cdf::EOB_PT_64_CHROMA_CLASS1_Q1, - cdf::EOB_PT_64_CHROMA_CLASS1, - cdf::EOB_PT_64_CHROMA_CLASS1_Q3, + cdf::EOB_PT_512_LUMA_CLASS1_Q0, + cdf::EOB_PT_512_LUMA_CLASS1_Q1, + cdf::EOB_PT_512_LUMA_CLASS1, + cdf::EOB_PT_512_LUMA_CLASS1_Q3, ), - eob_pt_16_chroma_class1: pick( + eob_pt_512_chroma_class1: pick( q_ctx, - cdf::EOB_PT_16_CHROMA_CLASS1_Q0, - cdf::EOB_PT_16_CHROMA_CLASS1_Q1, - cdf::EOB_PT_16_CHROMA_CLASS1, - cdf::EOB_PT_16_CHROMA_CLASS1_Q3, + cdf::EOB_PT_512_CHROMA_CLASS1_Q0, + cdf::EOB_PT_512_CHROMA_CLASS1_Q1, + cdf::EOB_PT_512_CHROMA_CLASS1, + cdf::EOB_PT_512_CHROMA_CLASS1_Q3, + ), + eob_pt_1024_luma_class1: pick( + q_ctx, + cdf::EOB_PT_1024_LUMA_CLASS1_Q0, + cdf::EOB_PT_1024_LUMA_CLASS1_Q1, + cdf::EOB_PT_1024_LUMA_CLASS1, + cdf::EOB_PT_1024_LUMA_CLASS1_Q3, + ), + eob_pt_1024_chroma_class1: pick( + q_ctx, + cdf::EOB_PT_1024_CHROMA_CLASS1_Q0, + cdf::EOB_PT_1024_CHROMA_CLASS1_Q1, + cdf::EOB_PT_1024_CHROMA_CLASS1, + cdf::EOB_PT_1024_CHROMA_CLASS1_Q3, ), eob_extra_luma_16: pick( q_ctx, @@ -1283,7 +1330,7 @@ impl Cdfs { br: &mut self.br_luma_32, dc_sign: &mut self.dc_sign_luma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_1024_luma_class1), }, // lane-comppin r4 (REVERTED, see r4's own commit message): // `Some(inter_tx_type_32)` looked wrong against aomdec's 32x32 @@ -1307,7 +1354,7 @@ impl Cdfs { br: &mut self.br_luma_32, dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.inter_tx_type_32.as_mut_slice()), - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_1024_luma_class1), }, TxbSet::Luma64 => TxbTables { side: 32, @@ -1319,7 +1366,7 @@ impl Cdfs { br: &mut self.br_luma_32, dc_sign: &mut self.dc_sign_luma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_1024_luma_class1), }, TxbSet::Luma16 => TxbTables { side: 16, @@ -1403,7 +1450,7 @@ impl Cdfs { br: &mut self.br_luma_4, dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.inter_tx_type_4.as_mut_slice()), - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_16_luma_class1), }, TxbSet::Luma4InterSet1 => TxbTables { side: 4, @@ -1439,7 +1486,7 @@ impl Cdfs { br: &mut self.br_luma_8, dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.inter_tx_type_8.as_mut_slice()), - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_64_luma_class1), }, TxbSet::Luma8InterSet1 => TxbTables { side: 8, @@ -1499,7 +1546,7 @@ impl Cdfs { br: &mut self.br_chroma_32, dc_sign: &mut self.dc_sign_chroma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_1024_chroma_class1), }, TxbSet::LumaRect32x16 => TxbTables { side: 32, @@ -1511,7 +1558,7 @@ impl Cdfs { br: &mut self.br_luma_32, dc_sign: &mut self.dc_sign_luma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_512_luma_class1), }, TxbSet::ChromaRect16x8 => TxbTables { side: 16, @@ -1523,7 +1570,7 @@ impl Cdfs { br: &mut self.br_chroma_16, dc_sign: &mut self.dc_sign_chroma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_128_chroma_class1), }, TxbSet::ChromaRect32x16 => TxbTables { side: 32, @@ -1535,7 +1582,7 @@ impl Cdfs { br: &mut self.br_chroma_32, dc_sign: &mut self.dc_sign_chroma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_512_chroma_class1), }, } } diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 305406d4..dd464593 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -36,7 +36,7 @@ use crate::msac::SymbolDecoder; use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx, - find_mv_stack, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_ctx, + find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx, }; @@ -51,6 +51,8 @@ const PARTITION_HORZ_A: usize = 4; const PARTITION_HORZ_B: usize = 5; const PARTITION_VERT_A: usize = 6; const PARTITION_VERT_B: usize = 7; +const PARTITION_HORZ_4: usize = 8; +const PARTITION_VERT_4: usize = 9; const SB_MI: u32 = 16; const BLOCK_MI: u32 = 8; @@ -1171,6 +1173,62 @@ pub(crate) fn obmc_hits() -> usize { OBMC_HITS.with(|c| c.get()) } +// lane-scaledref r1: per-case firing counts for the scaled-reference gate +// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED +// reference would pass just as well and prove nothing, so the gate +// hard-asserts each combination this round lifts actually occurred: +// a compound block with a scaled tap, a warp block whose warp libaom +// suppresses because the reference is scaled, an OBMC block, an interintra +// block, and an 8x8 leaf. +thread_local! { + static SCALED_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SCALED_WARP_FALLBACK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SCALED_OBMC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SCALED_INTERINTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SCALED_BLOCK8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one +/// scaled and one unscaled tap. +pub(crate) fn mixed_scale_compound_hits() -> usize { + MIXED_SCALE_COMPOUND_HITS.with(|c| c.get()) +} + +/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have +/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf` +/// instead because their reference is scaled (libaom `motion_mode_allowed`, +/// `blockd.h:1484`). +pub(crate) fn scaled_warp_suppressed_hits() -> usize { + SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get()) +} + +/// Current value of [`SCALED_COMPOUND_HITS`]. +pub(crate) fn scaled_compound_hits() -> usize { + SCALED_COMPOUND_HITS.with(|c| c.get()) +} + +/// Current value of [`SCALED_WARP_FALLBACK_HITS`]. +pub(crate) fn scaled_warp_fallback_hits() -> usize { + SCALED_WARP_FALLBACK_HITS.with(|c| c.get()) +} + +/// Current value of [`SCALED_OBMC_HITS`]. +pub(crate) fn scaled_obmc_hits() -> usize { + SCALED_OBMC_HITS.with(|c| c.get()) +} + +/// Current value of [`SCALED_INTERINTRA_HITS`]. +pub(crate) fn scaled_interintra_hits() -> usize { + SCALED_INTERINTRA_HITS.with(|c| c.get()) +} + +/// Current value of [`SCALED_BLOCK8_HITS`]. +pub(crate) fn scaled_block8_hits() -> usize { + SCALED_BLOCK8_HITS.with(|c| c.get()) +} + // lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to // `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of // [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an @@ -1210,6 +1268,42 @@ pub(crate) fn compound_warp_hits() -> usize { COMPOUND_WARP_HITS.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 +// carried an AFFINE `global_motion_params` AND that a block was predicted +// with it, not merely that the header parsed one. +thread_local! { + static AFFINE_GM_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`AFFINE_GM_HITS`]. +pub(crate) fn affine_gm_hits() -> usize { + AFFINE_GM_HITS.with(|c| c.get()) +} + +// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves +// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real +// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented +// only once `find_projection` returned a usable model, unlike +// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates' +// proof that the leaf path itself fired, not the 16x16+ one. +thread_local! { + static GLOBALMV_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; + static WARP_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`GLOBALMV_HITS_8`]. +pub(crate) fn globalmv_hits_8() -> usize { + GLOBALMV_HITS_8.with(|c| c.get()) +} + +/// Current value of [`WARP_HITS_8`]. +pub(crate) fn warp_hits_8() -> usize { + WARP_HITS_8.with(|c| c.get()) +} + // How many blocks decoded `interintra == 1` with the non-wedge blended // prediction applied (lane-interintra r1) -- the gate's proof that a // stream actually exercised interintra. @@ -1380,6 +1474,26 @@ pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] { SB_AB_HITS.with(std::cell::Cell::get) } +// lane-tx64x16: the two 1:4 superblock arms, counted per orientation -- +// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64 +// strips). Two counters, not one, because a gate that only proved "some 1:4 +// strip fired" would pass on a stream that never coded the other axis, and +// every scan/context table this round added comes in a transposed pair. +thread_local! { + static SB_RECT4_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SB_RECT4_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded). +pub(crate) fn sb_rect4_horz_hits() -> usize { + SB_RECT4_HORZ_HITS.with(|c| c.get()) +} + +/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded). +pub(crate) fn sb_rect4_vert_hits() -> usize { + SB_RECT4_VERT_HITS.with(|c| c.get()) +} + // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not @@ -1775,33 +1889,30 @@ fn base_ctx( // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the // square table vs the real ctx 13 the rect table gives). TxClass::TwoD => { - // OPEN (lane-rectsplit r3, measured): the two rect - // transcriptions in [`cdf`] are packed `[col][row]` -- libaom's - // `av1_nz_map_ctx_offset_32x64` is a FLAT 1024-entry array whose - // `coeff_idx` is COLUMN-major with stride 32 (`TX_CLASS_HORIZ` - // reads its column back as `coeff_idx >> bhl`), and entries - // 0..5 / 32..35 match the generating rule (txb_common.h:199-209) - // only under `flat[col * 32 + row]`; - // `nz_map_ctx_offset_tables_match_the_rect_rule` pins that. - // Yet reading `[col][row]` here BREAKS - // `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` - // (seed 43) while `[row][col]` breaks the split-transform SB gate - // (seed 50); swapping the shape test as well fails BOTH ways. So - // this read is not the defect -- our (row, col) here come from a - // square 32x32-corner scan whose orientation relative to libaom's - // column-major `coeff_idx` is what is really unproven, and each - // "fix" only moves which rare corner position desyncs. Left at - // the r1 reading, the one every merged gate is green under. - // `EC_NZOFF_DUMP=1` prints every rect-shaped read. - let table = match rect_shape { - Some((w, h)) if w < h => &cdf::NZ_MAP_CTX_OFFSET_32X64, - Some((w, h)) if w > h => &cdf::NZ_MAP_CTX_OFFSET_64X32, - _ => &cdf::NZ_MAP_CTX_OFFSET_32, - }; - if std::env::var_os("EC_NZOFF_DUMP").is_some() { - eprintln!("NZOFF side={side} shape={rect_shape:?} row={row} col={col}"); + // lane-rectsplit r4: apply libaom's GENERATING RULE + // (`txb_common.h:199-209`) directly instead of indexing the + // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a + // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major + // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the + // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`), + // so 32 consecutive entries are one COLUMN: the [`cdf`] + // transcriptions are `[col][row]` and this read had them as + // `[row][col]` -- the transpose, i.e. the other shape's rule with + // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated + // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` + // pins the rule against the tables over their whole 5x5 domain. + if let Some((w, h)) = rect_shape { + if std::env::var_os("EC_NZOFF_DUMP").is_some() { + eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}"); + } + if w < h && row < 2 { + return ctx + 11; + } + if w > h && col < 2 { + return ctx + 16; + } } - ctx + table[row.min(4)][col.min(4)] as usize + ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize } TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), @@ -1917,6 +2028,46 @@ const SCAN_8X16: [u16; 128] = [ 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127, ]; +/// `Default_Scan_32x8`, this decoder's own row-major transcription (see +/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16 +/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its +/// scans column-major (`p = col * height + row`), so a naive copy of +/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order +/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes +/// are byte-identical to this decoder's [`SCAN_8X16`]. +const SCAN_32X8: [u16; 256] = [ + 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130, + 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195, + 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42, + 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169, + 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16, + 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143, + 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239, + 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117, + 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213, + 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91, + 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187, + 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253, + 222, 191, 254, 223, 255, +]; +/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a +/// 16x64 `PARTITION_VERT_4` strip). +const SCAN_8X32: [u16; 256] = [ + 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34, + 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58, + 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82, + 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99, + 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95, + 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132, + 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169, + 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158, + 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195, + 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232, + 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221, + 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252, + 239, 246, 253, 247, 254, 255, +]; + /// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents /// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s /// asymmetric-extent pattern). @@ -1988,6 +2139,18 @@ fn dc_sign_ctx(vote: i32) -> usize { /// (spec 5.11.40): its bit length in unary, then that many of its own bits, /// most significant first — the exact inverse of [`crate::tile::write_golomb`]. fn read_golomb(dec: &mut SymbolDecoder) -> Result { + // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted + // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom + // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical + // for every tail any encoder writes -- our own writer tops out at 19 zeros + // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented + // and round-trip tested here (commit ee1f980, reverted in 314ee08). It + // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` + // RED: seed 67 stops here today, and with the cap raised it decodes to a + // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a + // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync + // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this + // together with that defect's fix, not before. let mut length = 1u32; while dec.literal(1) == 0 { length += 1; @@ -2180,7 +2343,8 @@ fn read_coeffs( let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some(); if ec_trace_coeff { let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={rng}"); + let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" }; + eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}"); } let class_scan; let scan: &[u16] = if class == TxClass::TwoD { @@ -2205,6 +2369,15 @@ fn read_coeffs( } else { let ctx = base_ctx(&levels, side, row, col, class, rect_shape); let v = dec.symbol(&mut coding.base[ctx]) as i32; + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + // `pos` in libaom's column-major `coeff_idx` convention, so + // the ladder lines up with instrumented `aomdec`. + let apos = col * side + row; + eprintln!( + "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}" + ); + } if trace { eprintln!( "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}" @@ -4304,6 +4477,13 @@ fn decode_rect_split( dc_sign_ctx(around[plane_idx].2), default_tx, )?; + // The same delta_q proof the unsplit rect64 path records + // (lane-rectsplit r4: lifting the split-transform refusal moved + // superblock strips onto this path, so only counting there would + // leave the delta_q gate's counter silent for them). + if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) { + RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); + } let residual = dequant_and_inverse_typed_wh( &levels, chroma_w, @@ -5070,20 +5250,55 @@ fn decode_block_rect64( }; if depth != 0 { TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); - // lane-rectsplit r1/r3: [`decode_rect_split`] handles this shape too - // and the per-unit port is wired here, but the gate - // (`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`, - // `#[ignore]`d with its measurement) is still RED at seed 50 (luma - // (171,56), ours 147 vs ffmpeg 148). r2 believed the cause was a - // transposed `av1_nz_map_ctx_offset` read; r3 measured that - // transposing it turns THIS gate green and the merged SB-level - // HORZ/VERT partition gate RED (seed 43), so the cause is still - // open. A refusal this lane cannot lift is not one it may ship wrong - // pixels past. - return Err(unsupported( - "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \ - prediction is not ported)", - )); + // lane-rectsplit r1/r4: the superblock-level strip splits its + // transform through the very same per-unit path as its 32x32-level + // sibling (`sub_tx_size_map[TX_64X32] == TX_32X32`, square from the + // first step on, so `bw.min(bh) >> (depth - 1)` names the unit). + let tx = bw.min(bh) >> (depth - 1); + if std::env::var_os("EC_SBPART_DUMP64").is_some() { + eprintln!( + "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ + depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \ + angle_y={angle_delta_y}" + ); + } + let modes = RectStripModes { + skip, + mode, + angle_delta_y, + uv_predict_mode, + angle_delta_uv, + alpha, + filter_intra, + smooth_neighbor, + smooth_neighbor_uv, + palette_y: palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), + palette_uv: palette_uv.as_ref().map(|p| { + ( + p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), + p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), + ) + }), + }; + if palette_y.is_some() || palette_uv.is_some() { + PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + } + decode_rect_split( + dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set, + )?; + // Same early-return palette stamp as [`decode_block_rect`]'s split arm + // (lane-palette2 r10): this return skips the fn's own tail, so a + // split-tx superblock strip would otherwise leave the above/left + // palette arrays holding a dead block's colours. + let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors); + let (puv_size, puv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors); + RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); + return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px / 2, py / 2); @@ -5160,30 +5375,63 @@ fn decode_block_rect64( ); } else { let around = neighbours.around_rect(at, bw, bh); - // LUMA: a real 32x32 corner, embedded top-left of the true bw x bh - // grid (see this function's own doc comment). + // LUMA: the coded corner, embedded top-left of the true bw x bh grid + // (see this function's own doc comment). A 64-length axis codes only + // its low 32 coefficients, so the corner is `min(bw, 32)` x + // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and + // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16). + let (luma_cw, luma_ch) = (bw.min(32), bh.min(32)); let scan32 = default_scan(TX32); - let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode); if std::env::var_os("EC_TRACE_COEFF").is_some() { let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size=64corner rng={rng}"); + eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"); } - let (luma_corner, luma_tx_type) = read_coeffs( - dec, - &mut luma_coding, - &scan32, - 0, - dc_sign_ctx(around[0].2), - TxType::DctDct, - Some((bw, bh)), - )?; + let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) { + let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode); + read_coeffs( + dec, + &mut luma_coding, + &scan32, + 0, + dc_sign_ctx(around[0].2), + TxType::DctDct, + Some((bw, bh)), + )? + } else { + // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 -> + // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders` + // (`scan.c`) gives both the very same `default_scan_32x16` / + // `default_scan_16x32` the 2:1 sizes use ("Half of the + // coefficients of tx64 at higher frequencies are set to zeros. So + // tx32's scan order is used"). `get_txsize_entropy_ctx` is + // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 + + // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a + // 512-position eob group) -- BOTH identical to TX_32X16, so the + // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table + // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally + // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is + // what `base_ctx_rect` computes at (32, 16). + let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 }; + let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode); + read_coeffs_rect( + dec, + &mut luma_coding, + luma_scan, + luma_cw, + luma_ch, + 0, + dc_sign_ctx(around[0].2), + TxType::DctDct, + )? + }; if std::env::var_os("EC_TRACE_COEFF").is_some() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}"); } let mut luma_levels = vec![0i32; bw * bh]; - for row in 0..32 { - luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]); + for row in 0..luma_ch { + luma_levels[row * bw..][..luma_cw] + .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]); } { let cur = block_q_idx(); @@ -5236,9 +5484,20 @@ fn decode_block_rect64( // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no // corner crop needed (see doc comment). let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); - let chroma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 }; + // The chroma plane is never truncated (both axes <= 32 after + // subsampling). Under a 1:4 strip it is a true 32x8/8x32: + // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 = + // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions), + // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact + // set, and only the scan is new (lane-tx64x16). + let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) { + (64, 16) => (TxbSet::Chroma16, &SCAN_32X8), + (16, 64) => (TxbSet::Chroma16, &SCAN_8X32), + (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16), + _ => (TxbSet::ChromaRect32x16, &SCAN_16X32), + }; let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); - let mut u_coding = cdfs.txb(TxbSet::ChromaRect32x16, uv_predict_mode); + let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode); if std::env::var_os("EC_TRACE_COEFF").is_some() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); @@ -5292,7 +5551,7 @@ fn decode_block_rect64( smooth_neighbor_uv, ); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); - let mut v_coding = cdfs.txb(TxbSet::ChromaRect32x16, uv_predict_mode); + let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode); if std::env::var_os("EC_TRACE_COEFF").is_some() { let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}"); @@ -5356,6 +5615,11 @@ fn decode_block_rect64( neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0); SB_RECT_HITS.with(|c| c.set(c.get() + 1)); + match (bw, bh) { + (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)), + (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)), + _ => {} + } if std::env::var_os("EC_AV1_TRACE").is_some() { let (rng, _) = dec.debug_state(); eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}"); @@ -9741,10 +10005,49 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } } + PARTITION_HORZ_4 | PARTITION_VERT_4 => { + // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or + // 16x64) strips in raster order. `decode_partition` + // (`decodeframe.c`) steps by `quarter_step = mi_size / 4` + // (4 mi = 16 px = one SUB unit here) and BREAKS at the + // frame edge for `i > 0`, so a partial superblock codes + // only the strips whose origin is inside the frame. + let horz = part == PARTITION_HORZ_4; + for i in 0..4 { + let step_mi = i * (SB_MI as usize / 4); + let (this_r_mi, this_c_mi) = if horz { + (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize) + } else { + (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi) + }; + if i > 0 + && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize) + { + break; + } + let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) }; + let (bw, bh) = if horz { (64, 16) } else { (16, 64) }; + decode_block_rect64( + &mut dec, + &mut cdfs, + &mut neighbours, + strip_at, + bw, + bh, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } + } _ => { return Err(unsupported( - "a superblock-level 1:4 partition (PARTITION_HORZ_4/VERT_4 at 64x64, \ - four 64x16/16x64 strips)", + "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", )); } } @@ -10596,6 +10899,12 @@ fn num_proj_ref( /// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16) /// are transcribed. fn obmc_mask(len: usize) -> &'static [u8] { + // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c` + // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so + // its overlap is 2 (and 1 at a half-block edge). Unreachable until this + // round wired interior 16x16 splits down to real 8x8 leaves, where the + // old `unreachable!()` below fired as a hard panic. + const M1: [u8; 1] = [64]; // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2 // chroma), which only became live once 8x8 inter leaves stopped being @@ -10611,6 +10920,7 @@ fn obmc_mask(len: usize) -> &'static [u8] { 61, 62, 64, 64, 64, 64, 64, 64, 64, 64, ]; match len { + 1 => &M1, 2 => &M2, 4 => &M4, 8 => &M8, @@ -10655,21 +10965,43 @@ fn obmc_neighbour_pred( luma: bool, h_kind: mc::InterpFilterKind, v_kind: mc::InterpFilterKind, + // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own + // reference (derived from luma widths, applied unchanged to chroma whose + // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes + // the ordinary stride-1 path bit-exact. + x_scale_fp: i64, ) -> Vec { let mut out = vec![0u16; w * h]; - mc::predict_with_filters( - &refplane.data, - refplane.width, - refplane.true_width, - refplane.true_height, - mv_to_q4(x, mv.1, luma), - mv_to_q4(y, mv.0, luma), - w, - h, - h_kind, - v_kind, - &mut out, - ); + if x_scale_fp == mc::REF_NO_SCALE { + mc::predict_with_filters( + &refplane.data, + refplane.width, + refplane.true_width, + refplane.true_height, + mv_to_q4(x, mv.1, luma), + mv_to_q4(y, mv.0, luma), + w, + h, + h_kind, + v_kind, + &mut out, + ); + } else { + mc::predict_scaled( + &refplane.data, + refplane.width, + refplane.true_width, + refplane.true_height, + mv_to_q4(x, mv.1, luma), + mv_to_q4(y, mv.0, luma), + x_scale_fp, + w, + h, + h_kind, + v_kind, + &mut out, + ); + } out } @@ -10830,6 +11162,12 @@ fn obmc_blend( ref_v: &PlaneBuf, other_refs: &RefSlots, interp_fixed: Option, + // lane-scaledref r1: this frame's own coded luma width -- each OBMC + // neighbour is re-predicted against ITS OWN reference, which may be + // scaled differently from this block's (spec 7.11.3.3 / libaom + // `av1_setup_build_prediction_by_above_pred` passing that ref's own + // `scale_factors`). + frame_width: usize, pred_y: &mut [u16], pred_u: &mut [u16], pred_v: &mut [u16], @@ -10845,6 +11183,11 @@ fn obmc_blend( }; let overlap_above = write_h / 2; let overlap_left = write_w / 2; + // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc` + // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided + // obmc") returns `dir == 0` when the chroma plane's own block is + // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the + // ABOVE pass skips chroma entirely, the LEFT pass still blends it. let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16)); for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4)) @@ -10853,25 +11196,25 @@ fn obmc_blend( // (this decoder's own outer block-loop granularity), one step // coarser than the mi(4px) units `overlappable_above` walks in -- // divide back down to that column. + // lane-gmaffine r2: the neighbour's OWN mi-granular filter + // (libaom `av1_setup_build_prediction_by_above_pred` reads + // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot + // stays as the fallback for paths that do not record one yet + // (compound), which is what every earlier round used. let (h_kind, v_kind) = neighbour_filter( interp_fixed, neighbours.above_filter[mi_col + off4], ); 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); - let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind); + let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale); obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y); - // lane-inter8 r1: `av1_skip_u4x4_pred_in_obmc` (`reconinter.c` 820, - // `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided obmc"): when the - // chroma plane's own block size is BLOCK_4X4/8X4/4X8 (a 8x8, 16x8 or - // 8x16 luma block at 4:2:0), the ABOVE pass skips chroma entirely - // while the LEFT pass still blends it. Blending chroma here as well - // would both mis-predict every 8x8 leaf and ask for an overlap of 2. if !skip_chroma_above { let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2); - let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind); + let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale); obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u); - let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind); + let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale); obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v); } } @@ -10882,13 +11225,14 @@ fn obmc_blend( neighbours.left_filter[mi_row + off4], ); 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); - let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind); + let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale); obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y); let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2); - let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind); + let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale); obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u); - let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind); + let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale); obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v); } Ok(()) @@ -11959,14 +12303,23 @@ fn decode_inter_block( ); block_filter = resolved_filter; - // lane-superres r9: a scaled reference in a COMPOUND_REFERENCE - // block (either tap) is not wired -- mc::predict_compound_intermediate - // has no scaled counterpart yet -- refuse by name rather than - // silently sample it unscaled. - if py0.width != frame_width || py1.width != frame_width { - return Err(unsupported( - "a compound-reference block with a scaled reference (superres, unimplemented)", - )); + // lane-scaledref r1: each compound tap scales INDEPENDENTLY off + // its own stored reference's luma width (spec 7.11.3.3 derives + // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds + // one `scale_factors` per `ref_frame`), so the two taps can carry + // different ratios in the same block. `REF_NO_SCALE` reduces + // `predict_compound_intermediate`'s walk to the ordinary + // stride-1 one, so the unscaled case is unchanged. + let scale0 = mc::scale_factor(py0.width, frame_width); + let scale1 = mc::scale_factor(py1.width, frame_width); + if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE { + SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1)); + } + // lane-scaledref r2: the MIXED case -- one tap scaled, the other + // not -- is the one an all-frames-scaled recipe never produces, + // and the one a single shared scale factor would get wrong. + if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) { + MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1)); } let mut inter0_y = vec![0i32; side * side]; @@ -11977,6 +12330,7 @@ fn decode_inter_block( py0.true_height, mv_to_q4(px, mv0.1, true), mv_to_q4(py, mv0.0, true), + scale0, side, side, h_filter, @@ -12001,6 +12355,7 @@ fn decode_inter_block( py1.true_height, mv_to_q4(px, mv1.1, true), mv_to_q4(py, mv1.0, true), + scale1, side, side, h_filter, @@ -12046,6 +12401,7 @@ fn decode_inter_block( pu0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), + scale0, chroma_side, chroma_side, h_filter, @@ -12072,6 +12428,7 @@ fn decode_inter_block( pu1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), + scale1, chroma_side, chroma_side, h_filter, @@ -12114,6 +12471,7 @@ fn decode_inter_block( pv0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), + scale0, chroma_side, chroma_side, h_filter, @@ -12140,6 +12498,7 @@ fn decode_inter_block( pv1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), + scale1, chroma_side, chroma_side, h_filter, @@ -12600,8 +12959,27 @@ fn decode_inter_block( // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf` // instead of the 2-symbol `obmc_cdf` exactly when // `num_proj_ref >= 1` under `allow_warped_motion`. + // lane-scaledref r2: libaom `motion_mode_allowed` + // (`blockd.h:1484`) requires + // `!av1_is_scaled(block_ref_scale_factors[0])` for + // WARPED_CAUSAL -- under a scaled reference (superres) the + // block reads the 2-symbol `obmc_cdf`, never the 3-symbol + // `motion_mode_cdf`. Reading the wrong alphabet here narrows + // the arithmetic coder by the wrong amount and predicts the + // rest of the tile off a diverged state: it was silently + // wrong pixels (r1's `--enable-warped-motion=1` superres + // mismatch), not a desync error. + let ref_is_scaled = + mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE; let warp_eligible = allow_warped_motion + && !ref_is_scaled && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1; + if allow_warped_motion + && ref_is_scaled + && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1 + { + SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1)); + } if warp_eligible { let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]); match mode { @@ -12684,6 +13062,9 @@ fn decode_inter_block( let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { warp_params = crate::warp::global_warp_params(gm_ref.params); + if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { + AFFINE_GM_HITS.with(|c| c.set(c.get() + 1)); + } } if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( @@ -12781,12 +13162,29 @@ fn decode_inter_block( // (warp_params/obmc_selected/interintra_mode are all resolved by // this point, every symbol for this block already read). let luma_scale = mc::scale_factor(py_ref.width, frame_width); - if luma_scale != mc::REF_NO_SCALE - && (warp_params.is_some() || obmc_selected || interintra_mode.is_some()) - { - return Err(unsupported( - "warp/OBMC/interintra prediction with a scaled reference (superres, unimplemented)", - )); + if luma_scale != mc::REF_NO_SCALE { + // lane-scaledref r1: libaom `allow_warp` + // (av1/common/reconinter.c:41) suppresses BOTH local and + // global warp under a scaled reference and predicts + // translationally instead -- that fallback is implemented + // below, but the one real aomenc stream this round found + // that reaches it (`--enable-warped-motion=1`, + // `--superres-denominator=16`, seed 47) still mismatches + // ffmpeg at frame 2 luma, so the case stays refused by name + // until it has a green gate rather than shipping wrong + // pixels behind a lifted refusal. + if warp_params.is_some() { + SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1)); + return Err(unsupported( + "warp prediction with a scaled reference (superres, unimplemented)", + )); + } + if obmc_selected { + SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1)); + } + if interintra_mode.is_some() { + SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1)); + } } let mut pred_y = vec![0u16; side * side]; @@ -12877,22 +13275,37 @@ fn decode_inter_block( ); } - if let Some(params) = &warp_params { + // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41) + // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local + // (`wm_params`) and global warp fall back to the translational + // prediction above when the reference is scaled, even though the + // motion_mode symbol was still read and warp_params still + // resolved. Suppress the warp, keep every symbol read. + if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) { crate::warp::warp_affine( params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32, py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32, side as i32, side as i32, 0, 0, ); - crate::warp::warp_affine( - params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32, - pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32, - chroma_side as i32, chroma_side as i32, 1, 1, - ); - crate::warp::warp_affine( - params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32, - pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32, - chroma_side as i32, chroma_side as i32, 1, 1, - ); + // libaom `av1_init_warp_params` (reconinter.c): warp is + // per PLANE and bails out at `block_width < 8 || + // block_height < 8`, so a plane whose own block is under + // 8x8 keeps the translational prediction built above -- + // in 420 that is every chroma plane of a luma block below + // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few + // levels on both 8x8-leaf motion gates). + if chroma_side >= 8 { + crate::warp::warp_affine( + params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32, + pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32, + chroma_side as i32, chroma_side as i32, 1, 1, + ); + crate::warp::warp_affine( + params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32, + pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32, + chroma_side as i32, chroma_side as i32, 1, 1, + ); + } } if obmc_selected { @@ -12918,6 +13331,7 @@ fn decode_inter_block( ref_v, other_refs, interp_fixed, + frame_width, &mut pred_y, &mut pred_u, &mut pred_v, @@ -13430,6 +13844,16 @@ fn decode_inter_block8( 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 @@ -13475,16 +13899,14 @@ fn decode_inter_block8( // `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 with neither the - // frame's sign-bias table nor its global-motion mv table (`NO_SIGN_BIAS` - // / `NO_GM_MV`), while [`decode_inter_block`] one level up passed both. - // A neighbour coded GLOBALMV contributes the gm mv, so dropping the table - // 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). + // 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, - global_motion: &[ec_av1_syntax::WarpParams; 7], // 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 @@ -13492,8 +13914,24 @@ fn decode_inter_block8( // mode contexts AND the number of `drl_mode` bits read (class parsed // then discarded). tpl_frame: Option<&TplFrameArgs>, -) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, (i8, Option))> { + // 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, @@ -13801,6 +14239,12 @@ fn decode_inter_block8( 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); + let scale1 = mc::scale_factor(py1.width, frame_width); + if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE { + SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1)); + SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1)); + } for dr in 0..2 { for dc in 0..2 { @@ -13837,6 +14281,7 @@ fn decode_inter_block8( py0.true_height, mv_to_q4(px, mv0.1, true), mv_to_q4(py, mv0.0, true), + scale0, SIDE, SIDE, Regular, @@ -13851,6 +14296,7 @@ fn decode_inter_block8( py1.true_height, mv_to_q4(px, mv1.1, true), mv_to_q4(py, mv1.0, true), + scale1, SIDE, SIDE, Regular, @@ -13882,6 +14328,7 @@ fn decode_inter_block8( pu0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), + scale0, CHROMA_SIDE, CHROMA_SIDE, Regular, @@ -13896,6 +14343,7 @@ fn decode_inter_block8( pu1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), + scale1, CHROMA_SIDE, CHROMA_SIDE, Regular, @@ -13926,6 +14374,7 @@ fn decode_inter_block8( pv0.true_height, mv_to_q4(cpx, mv0.1, false), mv_to_q4(cpy, mv0.0, false), + scale0, CHROMA_SIDE, CHROMA_SIDE, Regular, @@ -13940,6 +14389,7 @@ fn decode_inter_block8( pv1.true_height, mv_to_q4(cpx, mv1.1, false), mv_to_q4(cpy, mv1.0, false), + scale1, CHROMA_SIDE, CHROMA_SIDE, Regular, @@ -14059,38 +14509,58 @@ 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]); - neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 }); - return Ok((skip, is_inter, skip_mode, compound_ctx8, leaf_refs)); + neighbours.fill_lf_grid( + leaf_mi, + 2, + 8, + if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 }, + ); + return Ok(( + skip, + is_inter, + skip_mode, + compound_ctx8, + leaf_filter_syms, + leaf_refs, + )); } } - leaf_refs = (LAST_FRAME, None); - let sr_ctx = single_ref_ctx(above_inter || left_inter); - let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]); - let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]); - let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]); - if (p1, p3, p4) != (0, 0, 0) { - return Err(unsupported( - "a reference frame other than LAST_FRAME (round 2)", - )); - } + // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree + // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the + // real per-neighbour p1..p6 contexts) instead of the old three-symbol + // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for + // 8x8 leaves constantly, so that refusal was what every 8x8 gate + // actually stopped at. + let ref_frame = read_single_ref( + dec, + cdfs, + neighbours.above_ref[cmi], + neighbours.above_ref1[cmi], + neighbours.left_ref[rmi], + neighbours.left_ref1[rmi], + ); + leaf_refs = (ref_frame, None); + let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; let (mi_row, mi_col) = leaf_mi; + // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS + // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs). 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[(LAST_FRAME - LAST_FRAME) as usize], + t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, }); - let stack = find_mv_stack_with_sign_bias( + let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, mi_row, mi_col, 2, 2, - LAST_FRAME, + ref_frame, mi_cols as usize, mi_rows as usize, sign_bias_table, @@ -14099,6 +14569,7 @@ fn decode_inter_block8( ); 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 { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the @@ -14127,21 +14598,27 @@ fn decode_inter_block8( ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - if !not_zero { - return Err(unsupported("GLOBALMV (round 3)")); - } - let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - let mv = if nearest { - stack.nearest_mv + is_globalmv = !not_zero; + let mv = if !not_zero { + // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same + // `gm_get_motion_vector` value the 16x16+ leaf reads out of + // its own `gm_table`, computed at this block's centre. + GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1)); + gm_table[(ref_frame - LAST_FRAME) as usize] } 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; + 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; } - idx += 1; + stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) } - stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) }; (mv, false) }; @@ -14184,18 +14661,35 @@ fn decode_inter_block8( // 16x16 leaf's own `decode_inter_block` read (see its doc above) -- // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1` // refusal (warp needs `av1_findSamples`, not ported at either leaf). + // lane-gmaffine r1: the two libaom predicates, exactly as the + // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc): + // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block + // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is + // always true here) suppresses the motion_mode read entirely and + // turns on the global warp below. + let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; + let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1; let motion_mode_eligible = switchable_motion_mode && !skip_mode && interintra_mode.is_none() + && !(is_global_mv_block && !force_integer_mv) && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty() || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty()); + let mut warp_params: Option = None; + let mut warped_selected = false; let mut obmc_selected = false; if motion_mode_eligible { // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf // (see its own doc) -- this leaf is always `LAST_FRAME`-only // (grid.set below hardcodes it). + // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom + // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`) + // when the reference is scaled. Not gated here because an 8x8 + // leaf under a scaled reference is refused before this function + // runs (see the block8 refusal below, ~12500) -- whoever lifts + // that refusal must add `&& !ref_is_scaled` here too. let warp_eligible = allow_warped_motion - && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1; + && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1; if warp_eligible { let mode = dec.symbol(&mut cdfs.motion_mode[0]); match mode { @@ -14206,12 +14700,41 @@ fn decode_inter_block8( OBMC_HITS_8.with(|c| c.set(c.get() + 1)); } _ => { + // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf -- + // the same findSamples -> select_samples -> + // av1_find_projection chain the 16x16+ leaf runs, + // with BLOCK_8X8's own 8x8 model centre; an + // unusable projection falls back to the block's + // translational mv (libaom `av1_find_projection` + // returning 1 leaves `wm_params` invalid and + // `build_inter_predictors` skips the warp). WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1)); - return Err(unsupported( - "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): \ - av1_find_projection/the affine warp filter are not \ - ported, only motion_mode_allowed's alphabet choice is", - )); + let mut samples = find_samples( + grid, + mi_row, + mi_col, + 2, + 2, + mi_cols as usize, + mi_rows as usize, + ref_frame, + ); + if samples.len() > 1 { + crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32); + } + warp_params = crate::warp::find_projection( + &samples, + SIDE as i32, + SIDE as i32, + mv.1, + mv.0, + mi_row as i32, + mi_col as i32, + ); + warped_selected = true; + if warp_params.is_some() { + WARP_HITS_8.with(|c| c.set(c.get() + 1)); + } } } } else { @@ -14223,6 +14746,78 @@ fn decode_inter_block8( } } } + // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8 + // leaf, in libaom's own order (interintra, motion_mode, THEN the + // filter). Until this round the leaf read no filter symbol at all and + // predicted Regular unconditionally -- correct only for a frame with a + // fixed `interp_filter`, and a silent entropy DESYNC for every + // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what + // made the interior-split wiring above unusable at first). + // corner-cut: the neighbour filter context is the enclosing 16x16 + // block's own coarse `above_filter`/`left_filter` entry (this leaf + // path keeps no per-leaf neighbour array), so all four siblings read + // the same context row. Ceiling: a stream whose 8x8 siblings pick + // DIFFERENT filters decodes the second..fourth leaf's symbol from the + // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular + // filter array, same shape as the `[3, 3]` approximation the caller + // records after the leaf loop. + 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 || warped_selected || skip_mode, + above_filter_ctx, + left_filter_ctx, + false, + ); + leaf_filter_syms = resolved_filter; + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}", + leaf_mi.0, + leaf_mi.1, + mv.0, + mv.1, + stack.entries.len(), + dec.debug_state().0 + ); + } + // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch + // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` -- + // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model + // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px + // size predicate baked into `is_global_mv_block`. + if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { + warp_params = crate::warp::global_warp_params(gm_ref.params); + if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { + AFFINE_GM_HITS.with(|c| c.set(c.get() + 1)); + } + } + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}", + leaf_mi.0, + leaf_mi.1, + warp_params.is_some(), + ); + } for dr in 0..2 { for dc in 0..2 { grid.set( @@ -14230,7 +14825,7 @@ fn decode_inter_block8( mi_col + dc, MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame, // INTRA_FRAME marker for interintra blocks -- keeps // them out of warp-sample gathering (see 16/32 site). ref_frame1: interintra_mode.map(|_| 0), @@ -14239,7 +14834,7 @@ fn decode_inter_block8( is_new_mv, size: 2, size_h: 2, - is_global_mv0: false, + is_global_mv0: is_global_mv_block, is_global_mv1: false, }, ); @@ -14247,42 +14842,83 @@ fn decode_inter_block8( } mode_for_tx = 0; + // lane-scaledref r1: this leaf's own prediction is always `Regular` + // (documented corner-cut above); under a scaled reference the same + // fixed kernel runs through spec 7.11.3.3's scaled walk instead. + let luma_scale = mc::scale_factor(sref_y.width, frame_width); + if luma_scale != mc::REF_NO_SCALE { + SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1)); + } let mut pred_y = vec![0u16; SIDE * SIDE]; - mc::predict( - &ref_y.data, - ref_y.width, - ref_y.true_width, - ref_y.true_height, - mv_to_q4(px, mv.1, true), - mv_to_q4(py, mv.0, true), - SIDE, - SIDE, - &mut pred_y, - ); let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE]; - mc::predict( - &ref_u.data, - ref_u.width, - ref_u.true_width, - ref_u.true_height, - mv_to_q4(cpx, mv.1, false), - mv_to_q4(cpy, mv.0, false), - CHROMA_SIDE, - CHROMA_SIDE, - &mut pred_u, - ); let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE]; - mc::predict( - &ref_v.data, - ref_v.width, - ref_v.true_width, - ref_v.true_height, - mv_to_q4(cpx, mv.1, false), - mv_to_q4(cpy, mv.0, false), - CHROMA_SIDE, - CHROMA_SIDE, - &mut pred_v, - ); + // Merge of lane-gmaffine (this leaf's own switchable filters) with + // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either + // way, only the sample walk differs. + for (plane, x, y, dim, dst) in [ + (sref_y, px, py, SIDE, &mut pred_y), + (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u), + (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v), + ] { + let luma = std::ptr::eq(plane, sref_y); + if luma_scale == mc::REF_NO_SCALE { + mc::predict_with_filters( + &plane.data, + plane.width, + plane.true_width, + plane.true_height, + mv_to_q4(x, mv.1, luma), + mv_to_q4(y, mv.0, luma), + dim, + dim, + h_filter, + v_filter, + dst, + ); + } else { + mc::predict_scaled( + &plane.data, + plane.width, + plane.true_width, + plane.true_height, + mv_to_q4(x, mv.1, luma), + mv_to_q4(y, mv.0, luma), + luma_scale, + dim, + dim, + h_filter, + v_filter, + dst, + ); + } + } + + // lane-gmaffine r1: the warp filter REPLACES the translational + // prediction just built (libaom builds one or the other), same as + // the 16x16+ leaf's own call trio. + if let Some(params) = &warp_params { + crate::warp::warp_affine( + params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32, + sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32, + SIDE as i32, SIDE as i32, 0, 0, + ); + // `av1_init_warp_params`'s per-plane `block_width/height < 8` + // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is + // predicted translationally even when the luma warps. + #[allow(clippy::absurd_extreme_comparisons)] + if CHROMA_SIDE >= 8 { + crate::warp::warp_affine( + params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32, + sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32, + CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1, + ); + crate::warp::warp_affine( + params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32, + sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32, + CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1, + ); + } + } if obmc_selected { obmc_blend( @@ -14307,6 +14943,7 @@ fn decode_inter_block8( ref_v, other_refs, interp_fixed, + frame_width, &mut pred_y, &mut pred_u, &mut pred_v, @@ -14616,13 +15253,23 @@ fn decode_inter_block8( neighbours.above[leaf_mi.1 + cell][0] = state; } } + // 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). neighbours.fill_lf_grid( leaf_mi, 2, if split8 { 4 } else { 8 }, - if is_inter { LAST_FRAME } else { 0 }, + if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 }, ); - Ok((skip, is_inter, skip_mode, compound_ctx8, leaf_refs)) + Ok(( + skip, + is_inter, + skip_mode, + compound_ctx8, + leaf_filter_syms, + leaf_refs, + )) } /// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes, @@ -15356,15 +16003,23 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) .collect(); - // lane-superres r9: decode_inter_block8's own - // MC (below) is not threaded for a scaled - // reference (unlike decode_inter_block's 19 - // sites) -- refuse the whole 8x8-leaf split - // up front when ANY live reference this leaf - // could pick has a different width than this - // frame, rather than thread frame_width - // through its own single-ref/compound MC - // calls to reach the same block this round. + // lane-scaledref r1: `decode_inter_block8` IS + // threaded for a scaled reference now (its + // single-ref, compound and OBMC MC all take + // spec 7.11.3.3's scaled walk), but the one + // recipe that reaches this path at all -- a + // 64x72 superres fixture whose bottom 16-row + // band straddles the true edge, so the + // gathered split bit lands on 8x8 leaves -- + // DESYNCS inside the leaf itself + // (`from_switchable_symbol` handed a 4th + // symbol, mc.rs:200), the same + // below-8x8 desync lane-sub8 r2 left open and + // unrelated to scaling. So the scaled MC here + // is unproven: refuse by name rather than + // ship a capability claim no gate exercises. + // Deleting these six lines is the whole lift + // once the leaf8 desync is fixed. if ref_y.width != frame_width as usize || ref_slots.iter().flatten().any(|(py, _, _)| { py.width != frame_width as usize @@ -15375,8 +16030,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )); } let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option)> = Vec::new(); - let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None; - let mut last_skip_mode = false; 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); @@ -15386,8 +16039,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)", )); } - let (skip, is_inter, skip_mode_leaf, compound_ctx8, leaf_refs) = - decode_inter_block8( + let ( + skip, + is_inter, + skip_mode_leaf, + compound_ctx8, + leaf_filter, + leaf_refs, + ) = decode_inter_block8( &mut dec, &mut cdfs, &mut neighbours, @@ -15408,6 +16067,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &scan4, allow_high_precision_mv, force_integer_mv, + &global_motion, + enable_dual_filter, reference_select, enable_masked_compound, enable_interintra_compound, @@ -15423,14 +16084,10 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( allow_warped_motion, allow_screen_content_tools, &sign_bias_table, - &global_motion, tpl_frame.as_ref(), + frame_width as usize, )?; prev_leaves.push((leaf_mi, skip, is_inter, leaf_refs.0, leaf_refs.1)); - last_skip_mode = skip_mode_leaf; - if compound_ctx8.is_some() { - last_compound_ctx = compound_ctx8; - } // lane-inter8 r2: stamp THIS leaf's own // 2x2-mi span before the next leaf reads // it as a neighbour -- the whole-16x16 @@ -15439,9 +16096,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // block carried the wrong skip/ref/inter // state into the next block's contexts // (class context-read-from-one-cell). - // corner-cut: `[3, 3]` filter, as the - // 16x16 stamp used -- `decode_inter_block8` - // reads no switchable filter yet. + // lane-gmaffine r3: with the mi-granular + // band, the leaf's OWN switchable-filter + // symbols go in here -- the `[3, 3]` + // ("intra, no filter") sentinel this used + // to stamp made `obmc_blend`'s + // `neighbour_filter` PANIC as soon as a + // sibling leaf blended one of these. neighbours.record_inter_rect_mi( leaf_mi, 2, @@ -15449,7 +16110,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( skip, is_inter, leaf_refs.0, - [3, 3], + leaf_filter, skip_mode_leaf, ); if let Some(ref1) = leaf_refs.1 @@ -16460,33 +17121,34 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mod tests { use super::*; - /// lane-rectsplit r2: `av1_nz_map_ctx_offset` is packed COLUMN-major, so - /// the two rect transcriptions in [`cdf`] must be read `[col][row]`. - /// [`base_ctx_rect`] states libaom's generating rule - /// (`txb_common.h:199-209`) in display coordinates; this pins the tables - /// against it, which is what a transposed read would break. + /// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s + /// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes + /// and the square one, return exactly what libaom's + /// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables + /// transcribed in [`cdf`], read at libaom's own COLUMN-major + /// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them + /// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11 + /// and 16 swapped): it desynced the first superblock strip whose luma + /// corner held a coefficient off the first row/column. #[test] - fn nz_map_ctx_offset_tables_match_the_rect_rule() { - for (w, h, table) in [ - (32usize, 64usize, &cdf::NZ_MAP_CTX_OFFSET_32X64), - (64, 32, &cdf::NZ_MAP_CTX_OFFSET_64X32), + fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() { + let grid = [0i32; 32 * 32]; + for (shape, table) in [ + (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32), + (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64), + (None, &cdf::NZ_MAP_CTX_OFFSET_32), ] { for row in 0..5usize { for col in 0..5usize { + // An all-zero neighbourhood makes the magnitude term 0, + // so `base_ctx` returns the offset itself. + let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape); let want = if row == 0 && col == 0 { 0 - } else if w < h && row < 2 { - 11 - } else if w > h && col < 2 { - 16 } else { - cdf::NZ_MAP_CTX_OFFSET_32[row][col] + table[col][row] as usize }; - assert_eq!( - table[col][row], - want, - "{w}x{h} nz_map offset at display (row {row}, col {col})" - ); + assert_eq!(got, want, "{shape:?} at (row {row}, col {col})"); } } } diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index ea8de846..ee711e35 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -80,6 +80,52 @@ const TOOL_UNIVERSE: &[&str] = &[ "enable-warped-motion", ]; +/// How a non-boolean aomenc knob reads as "the tool is on". +#[cfg(test)] +#[derive(Clone, Copy, PartialEq)] +enum On { + /// Any non-zero value enables the tool (`--tile-columns=1`, `--loopfilter-control=1`). + NonZero, + /// The tool's search only runs at or below this speed (`--cpu-used`). + AtMost(u32), +} + +/// Coding tools aomenc drives through a spelling [`TOOL_UNIVERSE`] does not +/// cover, listed with their aomenc default. +/// +/// lane-covbd's derivation read `--enable-*` flags only, so a tool a gate pins +/// off through another spelling was invisible: all 49 gates that name it pass +/// `--enable-tx-size-search=0`, and the real-stream PANIC hiding behind that +/// pin was found by lane-ab16, not by this guard. `--loopfilter-control=0`, +/// `--tile-columns=0` and a `--cpu-used` high enough to switch a search off are +/// the same shape. +/// +/// Each entry is `(tool, spellings, aomenc default, what counts as on)`. The +/// "defaulted means unknown" rule of [`NEVER_EXERCISED`] applies unchanged: a +/// default of `1` does not prove the encoder picked the tool for any stream, so +/// only a gate that spells an on-value at that bit depth retires an entry. +#[cfg(test)] +const DEFAULT_ON_TOOLS: &[(&str, &[&str], &str, On)] = &[ + ("enable-tx-size-search", &["enable-tx-size-search"], "1", On::NonZero), + ("enable-directional-intra", &["enable-directional-intra"], "1", On::NonZero), + ("enable-smooth-interintra", &["enable-smooth-interintra"], "1", On::NonZero), + ("enable-interintra-wedge", &["enable-interintra-wedge"], "1", On::NonZero), + ("enable-diff-wtd-comp", &["enable-diff-wtd-comp"], "1", On::NonZero), + ("enable-onesided-comp", &["enable-onesided-comp"], "1", On::NonZero), + ("enable-fwd-kf", &["enable-fwd-kf"], "0", On::NonZero), + ("deblocking", &["loopfilter-control"], "1", On::NonZero), + ("multi-tile", &["tile-columns", "tile-rows"], "0", On::NonZero), + ("intrabc-search", &["cpu-used"], "0", On::AtMost(2)), +]; + +/// Non-`--enable-*` spellings that drive a [`TOOL_UNIVERSE`] tool. +/// +/// `--superres-mode=1` is how all three superres gates switch superres on; +/// without this map they read as an `enable-superres` hole while a real stream +/// exercises the tool (lane-covbd deferred exactly this). +#[cfg(test)] +const ALIASES: &[(&str, &str)] = &[("superres-mode", "enable-superres")]; + /// Coverage is per (tool x bit depth), not per tool. /// /// lane-hbdinter found two 10-bit-only defects (SGR box sums unscaled, Wiener @@ -93,10 +139,6 @@ const TOOL_UNIVERSE: &[&str] = &[ /// depth retires the entry, and this test fails until it is deleted. #[cfg(test)] const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[ - ( - "enable-1to4-partitions", - "off in 42 gates, on in none: PARTITION_HORZ_4/VERT_4 at 64x64 needs TX_64X16 luma plus 32x8 chroma scans (lane-part32 r5)", - ), ( "enable-angle-delta", "off in 36 gates, on in none: the directional-intra gates pin it off to isolate the base modes", @@ -133,10 +175,6 @@ const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[ "enable-ref-frame-mvs", "off in 27 gates, on in none: temporal MV projection is unimplemented", ), - ( - "enable-superres", - "never spelled: the three superres gates drive `--superres-mode=1` instead, so the tool IS exercised but not under this flag -- retire this entry only by renaming the check, not by assuming coverage", - ), ( "enable-tx64", "never spelled; TX_64X64 appears only where aomenc's default picks it, which is unknown per stream", @@ -161,7 +199,7 @@ const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ // gate passes `=1` for both. ( "enable-1to4-partitions", - "hole at both depths, see the 8-bit list", + "10-bit hole only: lane-tx64x16's 8-bit SB-level 1:4 gate passes `=1` and asserts both arms, but no 10-bit gate does", ), ( "enable-angle-delta", @@ -185,16 +223,81 @@ const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ "enable-ref-frame-mvs", "hole at both depths, see the 8-bit list", ), + ("enable-tx64", "hole at both depths, see the 8-bit list"), +]; + +/// [`DEFAULT_ON_TOOLS`] entries no 8-bit gate spells on, with the reason. +/// +/// Each entry is `(tool, why)`; the reason states whether the tool is pinned +/// OFF in every gate that names it (a hard hole -- no stream can carry it) or +/// merely defaulted (unknown, and unknown is not coverage). +#[cfg(test)] +const NEVER_ON_8BIT: &[(&str, &str)] = &[ + ( + "deblocking", + "on in no 8-bit gate: 7 pin --loopfilter-control=0, the other 34 default (on) -- and defaulted is unknown, so no stream is proven to run the loop filter", + ), ( - "enable-superres", - "the 10-bit superres gate drives `--superres-mode=1`, not this flag; see the 8-bit entry", + "enable-diff-wtd-comp", + "on in no 8-bit gate: 6 pin =0, 35 default; difference-weighted compound masks are unproven", + ), + ( + "enable-directional-intra", + "on in no 8-bit gate: pinned =0 in 32 of 41, defaulted in 9 -- the directional gates drive the modes through other flags, never this one", + ), + ( + "enable-fwd-kf", + "on in no 8-bit gate: 11 pin =0, 30 default (aomenc's default is off), so forward keyframes are never coded", + ), + ( + "enable-onesided-comp", + "on in no 8-bit gate: 17 pin =0, 24 default; one-sided compound prediction is unproven", + ), + ( + "enable-tx-size-search", + "on in no 8-bit gate: pinned =0 in 34 of 41 -- the pin that hid a real-stream PANIC from lane-ab16 until TX_MODE_SELECT was landed by lane-txselect; its gates spell the tool through the recipe, not this flag", + ), +]; + +/// [`DEFAULT_ON_TOOLS`] entries no 10-bit gate spells on, with the reason. +#[cfg(test)] +const NEVER_ON_10BIT: &[(&str, &str)] = &[ + ( + "deblocking", + "hole at both depths, see the 8-bit list (1 of the 15 10-bit gates pins =0, 14 default)", + ), + ( + "enable-diff-wtd-comp", + "hole at both depths, see the 8-bit list (1 pinned off, 14 defaulted)", + ), + ( + "enable-fwd-kf", + "hole at both depths, see the 8-bit list (3 pinned off, 12 defaulted)", + ), + ( + "enable-interintra-wedge", + "on in no 10-bit gate: 5 pin =0, 10 default -- wedge interintra masks are exercised at 8 bits only, the shape that cost lane-hbdinter two 10-bit-only defects", + ), + ( + "enable-onesided-comp", + "hole at both depths, see the 8-bit list (5 pinned off, 10 defaulted)", + ), + ( + "enable-tx-size-search", + "hole at both depths, see the 8-bit list (11 of 15 pin =0)", + ), + ( + "multi-tile", + "on in no 10-bit gate: all 15 leave --tile-columns/--tile-rows defaulted at 0, so every 10-bit stream is single-tile and no tile edge or per-tile CDF reset is checked at high bit depth", ), - ("enable-tx64", "hole at both depths, see the 8-bit list"), ]; #[cfg(test)] mod tests { - use super::{NEVER_EXERCISED, NEVER_EXERCISED_8BIT, NEVER_EXERCISED_10BIT, TOOL_UNIVERSE}; + use super::{ + ALIASES, DEFAULT_ON_TOOLS, NEVER_EXERCISED, NEVER_EXERCISED_8BIT, NEVER_EXERCISED_10BIT, + NEVER_ON_10BIT, NEVER_ON_8BIT, On, TOOL_UNIVERSE, + }; use std::collections::{BTreeMap, BTreeSet}; /// Bodies of the real-aomenc gates: a `fn` body carrying the shared @@ -241,6 +344,43 @@ mod tests { here } + /// Every `--flag=value` spelled inside one gate body, values kept whole + /// (`--cpu-used=4`, `--tile-columns=2`), not just their first character. + fn settings_in(gate: &str) -> BTreeMap { + let mut here = BTreeMap::new(); + for (i, _) in gate.match_indices("\"--") { + let rest = &gate[i + 3..]; + let Some(end) = rest.find('"') else { continue }; + let Some((flag, value)) = rest[..end].split_once('=') else { + continue; + }; + here.insert(flag.to_owned(), value.to_owned()); + } + here + } + + /// Whether a gate body spells one [`DEFAULT_ON_TOOLS`] entry on / off. + fn default_on_state(gate: &str, spellings: &[&str], on: On) -> Option { + let here = settings_in(gate); + let mut state = None; + for spelling in spellings { + let Some(value) = here.get(*spelling) else { + continue; + }; + let Ok(value) = value.parse::() else { + continue; + }; + let is_on = match on { + On::NonZero => value != 0, + On::AtMost(limit) => value <= limit, + }; + // Any spelling that says "on" wins: --tile-columns=0 --tile-rows=1 + // is a multi-tile stream. + state = Some(state.unwrap_or(false) || is_on); + } + state + } + /// `--enable-*` settings per real-aomenc gate, derived from the gate /// source: `flag -> (turned off in N gates, turned on in N, defaulted in N)`. fn tool_settings() -> (usize, BTreeMap) { @@ -347,6 +487,13 @@ mod tests { on.insert(flag); } } + // A tool driven by its own spelling counts as exercised. + let here = settings_in(gate); + for (alias, tool) in ALIASES { + if here.get(*alias).is_some_and(|v| v != "0") { + on.insert((*tool).to_owned()); + } + } } on } @@ -415,4 +562,110 @@ mod tests { } } } + + /// [`DEFAULT_ON_TOOLS`] per depth: `tool -> (off in N gates, on in N, defaulted in N)`. + fn default_on_settings(ten_bit: bool) -> (usize, BTreeMap<&'static str, (usize, usize, usize)>) { + let gates: Vec<&str> = gate_bodies() + .into_iter() + .filter(|b| is_ten_bit(b) == ten_bit) + .collect(); + let mut per_tool = BTreeMap::new(); + for &(tool, spellings, _, on) in DEFAULT_ON_TOOLS { + let states: Vec> = gates + .iter() + .map(|g| default_on_state(g, spellings, on)) + .collect(); + let turned_on = states.iter().filter(|s| **s == Some(true)).count(); + let turned_off = states.iter().filter(|s| **s == Some(false)).count(); + per_tool.insert( + tool, + (turned_off, turned_on, gates.len() - turned_off - turned_on), + ); + } + (gates.len(), per_tool) + } + + /// The [`DEFAULT_ON_TOOLS`] no gate of this depth positively enables. + fn never_on_at(ten_bit: bool) -> BTreeSet<&'static str> { + default_on_settings(ten_bit) + .1 + .into_iter() + .filter(|&(_, (_, on, _))| on == 0) + .map(|(tool, _)| tool) + .collect() + } + + fn check_default_on(ten_bit: bool, listed: &[(&str, &str)]) { + let derived = never_on_at(ten_bit); + let listed: BTreeSet<&str> = listed.iter().map(|&(tool, _)| tool).collect(); + let depth = if ten_bit { "10-bit" } else { "8-bit" }; + let unlisted: Vec<&&str> = derived.difference(&listed).collect(); + assert!( + unlisted.is_empty(), + "no {depth} gate spells an on-value for {unlisted:?}, so no real {depth} stream is \ + proven to carry them -- switch the tool on in a {depth} gate that asserts it fired, \ + or list it with a reason" + ); + let stale: Vec<&&str> = listed.difference(&derived).collect(); + assert!( + stale.is_empty(), + "the {depth} default-on list still names {stale:?}, but a {depth} gate now switches \ + them on -- delete those entries, the coverage hole is closed" + ); + } + + #[test] + fn never_on_8bit_matches_the_gate_recipes() { + check_default_on(false, NEVER_ON_8BIT); + } + + #[test] + fn never_on_10bit_matches_the_gate_recipes() { + check_default_on(true, NEVER_ON_10BIT); + } + + /// A tool must not be pinned twice: [`TOOL_UNIVERSE`] already derives the + /// `--enable-*` spellings under the `=1` rule. + #[test] + fn default_on_tools_do_not_duplicate_the_universe() { + for &(tool, spellings, _, _) in DEFAULT_ON_TOOLS { + assert!( + !TOOL_UNIVERSE.contains(&tool), + "{tool} is already covered by TOOL_UNIVERSE" + ); + assert!(!spellings.is_empty(), "{tool} has no aomenc spelling"); + } + for (alias, tool) in ALIASES { + assert!( + TOOL_UNIVERSE.contains(tool), + "alias --{alias} names {tool}, which is not a TOOL_UNIVERSE tool" + ); + } + } + + /// `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` prints the + /// default-on holes with their off/defaulted split. + #[test] + fn print_never_on_per_bit_depth() { + for (label, ten_bit) in [("8BIT", false), ("10BIT", true)] { + let (gate_count, per_tool) = default_on_settings(ten_bit); + let holes = never_on_at(ten_bit); + println!( + "NEVER_ON_{label} ({} of {}, over {gate_count} {label} gates):", + holes.len(), + DEFAULT_ON_TOOLS.len() + ); + for tool in &holes { + let (off, _, defaulted) = per_tool[tool]; + let spellings = DEFAULT_ON_TOOLS + .iter() + .find(|e| e.0 == *tool) + .map(|e| e.1.join(",")) + .unwrap_or_default(); + println!( + " {tool} (--{spellings}): off in {off}, defaulted in {defaulted}, on in 0" + ); + } + } + } } diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index ca954106..b57f1b35 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -119,8 +119,11 @@ const SUBPEL_FILTERS_SMOOTH_4: [[i32; 8]; 16] = [ [0, 0, 2, 34, 62, 30, 0, 0], ]; -/// `Subpel_Filters[EIGHTTAP_SHARP]` (`av1_sub_pel_filters_8sharp`) -- unlike -/// REGULAR/SMOOTH, spec 7.11.3.4 never swaps this for a narrow-block table. +/// `Subpel_Filters[EIGHTTAP_SHARP]` (`av1_sub_pel_filters_8sharp`). A block +/// whose dimension is 4 or less does NOT read this table: spec 7.11.3.4's +/// `filterIdx` sends both EIGHTTAP and EIGHTTAP_SHARP to filter index 4, and +/// libaom agrees -- `av1_interp_4tap[MULTITAP_SHARP]` is `av1_sub_pel_filters_4`, +/// the REGULAR narrow kernel (`filter.h:243`), not a sharp one (lane-gmaffine r5). const SUBPEL_FILTERS_SHARP: [[i32; 8]; 16] = [ [0, 0, 0, 128, 0, 0, 0, 0], [-2, 2, -6, 126, 8, -2, 2, 0], @@ -181,7 +184,7 @@ impl InterpFilterKind { match self { InterpFilterKind::Regular => (&SUBPEL_FILTERS, &SUBPEL_FILTERS_4), InterpFilterKind::Smooth => (&SUBPEL_FILTERS_SMOOTH, &SUBPEL_FILTERS_SMOOTH_4), - InterpFilterKind::Sharp => (&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_SHARP), + InterpFilterKind::Sharp => (&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_4), InterpFilterKind::Bilinear => (&SUBPEL_FILTERS_BILINEAR, &SUBPEL_FILTERS_BILINEAR), } } @@ -476,6 +479,54 @@ fn round_pow2_signed_64(value: i64, shift: u32) -> i64 { } } +/// Spec 7.11.3.3's horizontal pass on a (possibly) scaled reference, shared +/// by [`predict_scaled`] and [`predict_compound_intermediate`] -- the two +/// differ only in their VERTICAL rounding ([`INTER_ROUND_1`] vs +/// [`INTER_ROUND_1_COMPOUND`]), never here. Each output column walks the +/// reference by `x_step_qn` (the Q14 scale rounded down to the Q10 +/// `SCALE_SUBPEL_BITS` grid) and picks its own filter phase from the low +/// bits, so `x_scale_fp == REF_NO_SCALE` reduces to the ordinary stride-1 +/// whole-pel walk with one fixed phase (pinned by +/// `predict_scaled_at_no_scale_matches_predict_with_filters`). +#[allow(clippy::too_many_arguments)] +fn horizontal_scaled_pass( + reference: &[u16], + stride: usize, + true_width: usize, + true_height: usize, + x_q4: i32, + y0: i32, + x_scale_fp: i64, + block_w: usize, + rows: usize, + h_kind: InterpFilterKind, + intermediate: &mut [i32], +) { + let x_step_qn = round_pow2_64(x_scale_fp, 4); + let off = (x_scale_fp - REF_NO_SCALE) * 8; + let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32; + let (h_wide, h_narrow) = h_kind.tables(); + for c in 0..block_w { + let x_qn = pos_x_q10 + c as i64 * x_step_qn; + let int_pel = (x_qn >> 10) as i32; + let filter_idx = ((x_qn & 1023) >> 6) as usize; + let h_filter = if block_w <= 4 { + &h_narrow[filter_idx] + } else { + &h_wide[filter_idx] + }; + for r in 0..rows { + let y = y0 - 3 + r as i32; + let mut sum = 0; + for (t, &tap) in h_filter.iter().enumerate() { + let x = int_pel + t as i32 - 3; + sum += tap * sample(reference, stride, true_width, true_height, x, y); + } + intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); + } + } +} + /// [`predict_with_filters`]'s scaled-reference counterpart (spec 7.11.3.3): /// used only when the stored reference's luma width differs from the current /// frame's (`use_superres` on a non-key frame). `x_scale_fp` is @@ -516,11 +567,6 @@ pub fn predict_scaled( // SCALE_SUBPEL_BITS == 10: x_step_qn is x_scale_fp (Q14) rounded down to // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10 // grid (spec 7.11.3.3's `dec_calc_subpel_params`). - let x_step_qn = round_pow2_64(x_scale_fp, 4); - let off = (x_scale_fp - REF_NO_SCALE) * 8; - let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32; - - let (h_wide, h_narrow) = h_kind.tables(); let (v_wide, v_narrow) = v_kind.tables(); let v_filter = if block_h <= 4 { &v_narrow[yfrac] @@ -530,25 +576,19 @@ pub fn predict_scaled( let rows = block_h + 7; let mut intermediate = vec![0i32; rows * block_w]; - for c in 0..block_w { - let x_qn = pos_x_q10 + c as i64 * x_step_qn; - let int_pel = (x_qn >> 10) as i32; - let filter_idx = ((x_qn & 1023) >> 6) as usize; - let h_filter = if block_w <= 4 { - &h_narrow[filter_idx] - } else { - &h_wide[filter_idx] - }; - for r in 0..rows { - let y = y0 - 3 + r as i32; - let mut sum = 0; - for (t, &tap) in h_filter.iter().enumerate() { - let x = int_pel + t as i32 - 3; - sum += tap * sample(reference, stride, true_width, true_height, x, y); - } - intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); - } - } + horizontal_scaled_pass( + reference, + stride, + true_width, + true_height, + x_q4, + y0, + x_scale_fp, + block_w, + rows, + h_kind, + &mut intermediate, + ); for row in 0..block_h { for col in 0..block_w { @@ -602,6 +642,7 @@ pub fn predict_compound_intermediate( true_height: usize, x_q4: i32, y_q4: i32, + x_scale_fp: i64, block_w: usize, block_h: usize, h_kind: InterpFilterKind, @@ -612,18 +653,14 @@ pub fn predict_compound_intermediate( assert!(!reference.is_empty(), "a reference plane has samples"); INTER_PRED_HITS.with(|c| c.set(c.get() + 1)); - let x0 = x_q4.div_euclid(16); - let xfrac = x_q4.rem_euclid(16) as usize; + if x_scale_fp != REF_NO_SCALE { + PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1)); + } + let y0 = y_q4.div_euclid(16); let yfrac = y_q4.rem_euclid(16) as usize; - let (h_wide, h_narrow) = h_kind.tables(); let (v_wide, v_narrow) = v_kind.tables(); - let h_filter = if block_w <= 4 { - &h_narrow[xfrac] - } else { - &h_wide[xfrac] - }; let v_filter = if block_h <= 4 { &v_narrow[yfrac] } else { @@ -632,17 +669,19 @@ pub fn predict_compound_intermediate( let rows = block_h + 7; let mut intermediate = vec![0i32; rows * block_w]; - for r in 0..rows { - let y = y0 - 3 + r as i32; - for c in 0..block_w { - let mut sum = 0; - for (t, &tap) in h_filter.iter().enumerate() { - let x = x0 + c as i32 + t as i32 - 3; - sum += tap * sample(reference, stride, true_width, true_height, x, y); - } - intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); - } - } + horizontal_scaled_pass( + reference, + stride, + true_width, + true_height, + x_q4, + y0, + x_scale_fp, + block_w, + rows, + h_kind, + &mut intermediate, + ); for row in 0..block_h { for col in 0..block_w { @@ -775,6 +814,7 @@ fn compound_intermediate_whole_pel_identity_round_trips_through_combine() { 16, 0, 0, + REF_NO_SCALE, 4, 4, InterpFilterKind::Regular, @@ -884,6 +924,35 @@ mod tests { ); } + /// lane-gmaffine r5 root cause: a block 4 or fewer samples wide reads + /// `Subpel_Filters[4]` -- the REGULAR narrow kernel -- for BOTH + /// `EIGHTTAP` and `EIGHTTAP_SHARP` (spec 7.11.3.4's `filterIdx`, libaom + /// `av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`, + /// `filter.h:243`). We used the 8-tap sharp kernel there, which is + /// invisible above 4 samples and so only ever bit the 4x4 chroma of an + /// 8x8 (or smaller) luma leaf. + #[test] + fn a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness() { + use crate::mc::{SUBPEL_FILTERS_4, SUBPEL_FILTERS_BILINEAR, SUBPEL_FILTERS_SMOOTH_4}; + for kind in [ + InterpFilterKind::Regular, + InterpFilterKind::Smooth, + InterpFilterKind::Sharp, + InterpFilterKind::Bilinear, + ] { + let (wide, narrow) = kind.tables(); + let want: &[[i32; 8]; 16] = match kind { + InterpFilterKind::Regular | InterpFilterKind::Sharp => &SUBPEL_FILTERS_4, + InterpFilterKind::Smooth => &SUBPEL_FILTERS_SMOOTH_4, + InterpFilterKind::Bilinear => &SUBPEL_FILTERS_BILINEAR, + }; + assert_eq!(narrow, want, "{kind:?}: wrong narrow-block kernel"); + if kind == InterpFilterKind::Sharp { + assert_ne!(wide, narrow, "sharp's wide kernel is not its narrow one"); + } + } + } + #[test] fn integer_mv_is_identity() { let width = 12; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 33324f5b..fb536901 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -34,7 +34,6 @@ const CAPABILITY_CLAIMS: &[&str] = &[ #[cfg(test)] const REFUSALS: &[&str] = &[ - "GLOBALMV (round 3)", "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", @@ -44,10 +43,9 @@ const REFUSALS: &[&str] = &[ "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 32x32 partition type this decoder does not code (value={part32})", "a Golomb tail longer than this decoder reads", - "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)", "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", - "a superblock-level 1:4 partition (PARTITION_HORZ_4/VERT_4 at 64x64, four 64x16/16x64 strips)", + "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)", "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)", "a block that actually uses a palette (UV) -- reconstruction is out of scope", @@ -59,14 +57,11 @@ const REFUSALS: &[&str] = &[ "a frame with no mode-info grid", "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)", "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", - "a reference frame other than LAST_FRAME (round 2)", "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", "a reference picture whose height does not match this frame's own true size", "a show_existing_frame header naming an empty reference slot", - "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): av1_find_projection/the affine warp filter are not ported, only motion_mode_allowed's alphabet choice is", "an inter var-tx tree with a leaf transform larger than 32x32", "an intra block in an inter frame whose tx_depth splits its luma transform (round 1)", - "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)", "an inter frame with no key frame before it", "an inter SB-level partition type other than NONE or SPLIT (this decoder's inter tile path recurses a superblock only as SPLIT)", "a masked compound 64x64 inter block (compound_type is inferred, not coded, at this size)", @@ -74,8 +69,7 @@ const REFUSALS: &[&str] = &[ "an intra mode this decoder does not code (round 2)", "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet", "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", - "a compound-reference block with a scaled reference (superres, unimplemented)", - "warp/OBMC/interintra prediction with a scaled reference (superres, unimplemented)", + "warp prediction with a scaled reference (superres, unimplemented)", "an 8x8 partition leaf under a scaled reference (superres, unimplemented)", ]; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 1680d510..69eee982 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -18,7 +18,6 @@ use ec_av1_syntax::{ Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode, - WarpModel, }; use ec_core::{Error, Result}; @@ -375,16 +374,20 @@ pub fn decode_stream(data: &[u8]) -> Result> { // needed). AFFINE is untested this round (no aomenc fixture in the // wedge gate reached a 6-parameter model) -- keep refusing it by // name rather than shipping an unverified decode. - if header.frame_type != FrameType::Key - && header.global_motion[..7] - .iter() - .any(|gm| gm.model == WarpModel::Affine) - { - return Err(Error::unsupported( - "AV1 decode_stream", - "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)", - )); - } + // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom + // can never write a 6-parameter model -- its encoder-side search is + // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`, + // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) -- + // which is why four rounds of `--enable-global-motion=1` recipes + // never reached the case. `scripts/build-aom-affine-oracle.sh` widens + // exactly that search range in a side build, and + // `a_real_affine_global_motion_stream_decodes_pixel_exact` below + // decodes its output pixel-exact against ffmpeg with + // `affine_gm_hits() > 0`, i.e. real blocks predicted through the + // 6-parameter warp. Nothing in the decoder needed changing: the + // header reader already reads params 4/5 with their own subexp refs + // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s + // shear-validity check + `warp_affine` are model-agnostic. // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and // refused the shape by name rather than guess-fix it. r5 localized @@ -973,6 +976,18 @@ mod tests { /// mutex makes firing detection honest again (matches the existing /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`). static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]): + /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH + /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named + /// refusal -- and the three sum to the attempts made. + fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) { + eprintln!( + "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \ + named-refusals={named_refusals} (attempts {})", + counted_exact as usize + uncounted_exact as usize + named_refusals + ); + } + fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()) } @@ -1775,6 +1790,68 @@ mod tests { (oracle_frames, hidden) } + /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing + /// gate -- the gate's own recipe is never changed, this re-encodes the + /// same fixture with libaom's temporal alt-ref filter switched off and + /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with + /// the filter at its default EVERY alt-ref recipe in this file emits + /// ZERO hidden frames (the candidates are filtered away), so the + /// hidden-frame compare on the gate's own stream is vacuous; this arm + /// is what actually puts `show_frame == 0` frames on the wire. + /// + /// Runs at most once per gate name per process (the loop gates sweep + /// dozens of attempts and each arm costs a full encode + two decodes). + /// A stream this decoder refuses BY NAME skips the arm -- the arm is + /// about hidden frames, not about that capability gap -- while a pixel + /// mismatch is a hard failure raised inside the compare. + fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> { + static ARMED: std::sync::OnceLock>> = + std::sync::OnceLock::new(); + if !ARMED + .get_or_init(Default::default) + .lock() + .unwrap() + .insert(name.to_string()) + { + return None; + } + let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"]; + arm.extend_from_slice(args); + let mut child = Command::new(aomenc_path()) + .args(&arm) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(y4m) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{name} HIDDEN-ARM failed outright: {msg}" + ); + eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}"); + None + } + Ok(_) => Some(decode_all_frames_vs_oracle(&stream, &format!("{name}-arnr0"))), + } + } + + /// The repo's first hidden-frame pixel gate. Every other aomenc gate /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and /// both sides emit SHOWN frames only -- so an alt-ref frame that is @@ -3621,6 +3698,7 @@ mod tests { } let (width, height) = (64usize, 64usize); let mut refusals = Vec::new(); + let mut uncounted_exact = 0u32; for attempt in 0..40u32 { let seed = 42 + attempt; // A flat gradient never has enough local detail for the RD @@ -3735,11 +3813,16 @@ mod tests { continue; } }; - if decode::tx_depth_hits() == before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::tx_depth_hits() != before; + if !counted { + uncounted_exact += 1; refusals.push(format!( - "seed {seed}: decoded, but no block resolved a split tx_depth" + "seed {seed}: decoded and pixel-compared, but no block resolved a split \ + tx_depth" )); - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); assert_eq!( @@ -3748,8 +3831,22 @@ mod tests { ); assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); - return; + if counted { + gate_buckets( + "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact", + 1, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); + return; + } } + gate_buckets( + "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact", + 0, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); eprintln!( "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \ hit a named refusal or never split a transform:\n{}", @@ -3799,6 +3896,7 @@ mod tests { } let (width, height, frame_count) = (64usize, 64usize, 4usize); let mut refusals = Vec::new(); + let mut uncounted_exact = 0u32; for attempt in 0..40u32 { let seed = 42 + attempt; // Detail is what makes aomenc's RD prefer a split transform; a @@ -3936,11 +4034,16 @@ mod tests { decode::txfm_split_reads() - reads_before, decode::txfm_split_hits() - hits_before, ); - if hits == 0 { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = hits != 0; + if !counted { + uncounted_exact += 1; refusals.push(format!( - "seed {seed}: decoded, but no block took a txfm_split ({reads} symbols read)" + "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \ + ({reads} symbols read)" )); - continue; } let ffmpeg_frames = if bit_depth == 10 { ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) @@ -3988,8 +4091,22 @@ mod tests { 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})"); } - return; + if counted { + gate_buckets( + &format!("tx_select_inter_gate({bit_depth})"), + 1, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); + return; + } } + gate_buckets( + &format!("tx_select_inter_gate({bit_depth})"), + 0, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); panic!( "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}", refusals.join("\n") @@ -4022,6 +4139,7 @@ mod tests { let (width, height) = (64usize, 64usize); let mut refusals = Vec::new(); let mut fired_runs = 0u32; + let mut uncounted_exact = 0u32; for attempt in 0..40u32 { let seed = 42 + attempt; let source = format!( @@ -4111,13 +4229,19 @@ mod tests { continue; } }; - if decode::smooth_luma_hits() == smooth_before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::smooth_luma_hits() != smooth_before; + if counted { + fired_runs += 1; + } else { + uncounted_exact += 1; refusals.push(format!( - "seed {seed}: decoded, but no smooth-luma-neighbour block fired" + "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \ + fired" )); - continue; } - fired_runs += 1; let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); assert_eq!( frames[0].y, ffmpeg_frames[0].y, @@ -4126,9 +4250,21 @@ mod tests { assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); if fired_runs >= 4 { + gate_buckets( + "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); return; } } + gate_buckets( + "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); assert!( fired_runs > 0, "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}", @@ -4161,6 +4297,7 @@ mod tests { let (width, height) = (64usize, 64usize); let mut refusals = Vec::new(); let mut fired_runs = 0u32; + let mut uncounted_exact = 0u32; for attempt in 0..40u32 { let seed = 42 + attempt; let source = format!( @@ -4237,13 +4374,18 @@ mod tests { continue; } }; - if decode::smooth_uv_hits() == smooth_before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::smooth_uv_hits() != smooth_before; + if counted { + fired_runs += 1; + } else { + uncounted_exact += 1; refusals.push(format!( - "seed {seed}: decoded, but no smooth/paeth uv_mode fired" + "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired" )); - continue; } - fired_runs += 1; let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); assert_eq!( frames[0].y, ffmpeg_frames[0].y, @@ -4252,9 +4394,21 @@ mod tests { assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); if fired_runs >= 4 { + gate_buckets( + "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); return; } } + gate_buckets( + "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); assert!( fired_runs > 0, "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}", @@ -4289,6 +4443,7 @@ mod tests { let (width, height) = (64usize, 64usize); let mut refusals = Vec::new(); let mut fired_runs = 0u32; + let mut uncounted_exact = 0u32; for attempt in 0..40u32 { let seed = 42 + attempt; let source = format!( @@ -4389,16 +4544,20 @@ mod tests { continue; } }; - if decode::directional_uv_hits() == uv_before - && decode::angle_delta_hits() == angle_before - { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::directional_uv_hits() != uv_before + || decode::angle_delta_hits() != angle_before; + if counted { + fired_runs += 1; + } else { + uncounted_exact += 1; refusals.push(format!( - "seed {seed}: decoded, but neither a directional uv_mode nor a \ - nonzero angle delta fired" + "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \ + nor a nonzero angle delta fired" )); - continue; } - fired_runs += 1; let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); assert_eq!( frames[0].y, ffmpeg_frames[0].y, @@ -4407,9 +4566,21 @@ mod tests { assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); if fired_runs >= 4 { + gate_buckets( + "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); return; } } + gate_buckets( + "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); assert!( fired_runs > 0, "every attempt hit a named refusal or never exercised directional chroma:\n{}", @@ -5361,12 +5532,14 @@ mod tests { } Ok(frames) => frames, }; - if decode::non_last_ref_hits() == before { - // This seed's RD search never actually picked GOLDEN_FRAME -- - // a genuine miss, not a refusal. Try the next seed rather - // than claiming coverage this attempt did not exercise. + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + // This seed's RD search may never have picked GOLDEN_FRAME -- a + // genuine miss, not a refusal, and not a reason to skip the pixels. + let counted = decode::non_last_ref_hits() != before; + if !counted { never_fired += 1; - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); assert_eq!(frames.len(), frame_count); @@ -5387,12 +5560,26 @@ mod tests { 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})"); } - eprintln!( - "FIRING seed {seed}: non_last_ref_hits advanced by {}", - decode::non_last_ref_hits() - before - ); - return; + if counted { + eprintln!( + "FIRING seed {seed}: non_last_ref_hits advanced by {}", + decode::non_last_ref_hits() - before + ); + gate_buckets( + "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact", + 1, + never_fired, + refusals.len(), + ); + return; + } } + gate_buckets( + "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact", + 0, + never_fired, + refusals.len(), + ); eprintln!( "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \ {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \ @@ -5542,9 +5729,12 @@ mod tests { } Ok(frames) => frames, }; - if decode::ref_hits(target_ref) == before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::ref_hits(target_ref) != before; + if !counted { never_fired += 1; - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); assert_eq!(frames.len(), frame_count); @@ -5572,12 +5762,35 @@ mod tests { "{gate_name} frame {i} V vs ffmpeg (seed {seed})" ); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name); eprintln!( - "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}", - decode::ref_hits(target_ref) - before - ); - return; + "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) { + eprintln!( + "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } + if counted { + eprintln!( + "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}", + decode::ref_hits(target_ref) - before + ); + gate_buckets(gate_name, 1, never_fired, refusals.len()); + return; + } } + gate_buckets(gate_name, 0, never_fired, refusals.len()); eprintln!( "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \ and every other attempt hit a named refusal:\n{}", @@ -5747,9 +5960,12 @@ mod tests { continue; } Ok(frames) => { - if decode::comp_mode_hits() == before { + // class [[gate-skips-on-its-own-failure]]: a decode that + // succeeded is ALWAYS pixel-compared below; the hit counter + // only decides whether the attempt counts as firing. + let counted = decode::comp_mode_hits() != before; + if !counted { never_fired += 1; - continue; } // Outcome (c): plain COMPOUND_AVERAGE decoded fully -- // non-negotiable pixel exactness, no tolerance. @@ -5790,15 +6006,38 @@ mod tests { assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); eprintln!( - "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \ - fully and pixel-exact", - decode::comp_mode_hits() - before + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" ); - return; + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } + if counted { + eprintln!( + "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \ + fully and pixel-exact", + decode::comp_mode_hits() - before + ); + gate_buckets(NAME, 1, never_fired, refusals.len()); + return; + } } } } + gate_buckets(NAME, 0, never_fired, refusals.len()); eprintln!( "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \ block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \ @@ -5937,9 +6176,12 @@ mod tests { } Ok(frames) => frames, }; - if decode::skip_mode_hits() == before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::skip_mode_hits() != before; + if !counted { never_fired += 1; - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); assert_eq!(frames.len(), frame_count); @@ -5972,12 +6214,35 @@ mod tests { ); } } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); eprintln!( - "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}", - decode::skip_mode_hits() - before - ); - return; + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } + if counted { + eprintln!( + "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}", + decode::skip_mode_hits() - before + ); + gate_buckets(NAME, 1, never_fired, refusals.len()); + return; + } } + gate_buckets(NAME, 0, never_fired, refusals.len()); eprintln!( "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \ other attempt hit a named refusal:\n{}", @@ -6113,9 +6378,12 @@ mod tests { } Ok(frames) => frames, }; - if decode::obmc_hits() == before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::obmc_hits() != before; + if !counted { never_fired += 1; - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); assert_eq!(frames.len(), frame_count); @@ -6134,12 +6402,35 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); eprintln!( - "{NAME} FIRING seed {seed}: obmc hits advanced by {}", - decode::obmc_hits() - before - ); - return; + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } + if counted { + eprintln!( + "{NAME} FIRING seed {seed}: obmc hits advanced by {}", + decode::obmc_hits() - before + ); + gate_buckets(NAME, 1, never_fired, refusals.len()); + return; + } } + gate_buckets(NAME, 0, never_fired, refusals.len()); eprintln!( "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \ other attempt hit a named refusal:\n{}", @@ -6304,9 +6595,12 @@ mod tests { }; let fired8 = decode::obmc_hits_8() - before8; total_obmc8 += fired8; - if fired8 == 0 { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = fired8 != 0; + if !counted { never_fired += 1; - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); assert_eq!(frames.len(), frame_count); @@ -6325,13 +6619,39 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); eprintln!( - "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})" - ); - return; + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } + if counted { + eprintln!( + "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})" + ); + gate_buckets(NAME, 1, never_fired, refusals.len()); + return; + } } - eprintln!( - "SKIP {NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \ + gate_buckets(NAME, 0, never_fired, refusals.len()); + // lane-gmaffine r2: this gate fired for three rounds only as a SKIP + // (gate-skips-on-its-own-failure); the 8x8 leaf is reachable now, so a + // sweep that never lands one firing pixel-exact attempt is a FAILURE. + panic!( + "{NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \ ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \ hit a named refusal:\n{}", refusals.join("\n") @@ -6491,6 +6811,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } assert!( @@ -6940,6 +7279,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } assert!( @@ -6957,19 +7315,21 @@ mod tests { ); } - /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE - /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index` - /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over - /// the checksum-verified codebook. `--enable-masked-comp=0` stays so - /// the encoder cannot route inter blocks through the still-unported - /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge - /// fails the gate; refusals for OTHER named capabilities still skip - /// that seed. Zero `wii_hits` on a run means the encoder never - /// selected wedge-interintra -- soft-skipped (warned), not failed: - /// that is encoder choice, not a decoder bug. + /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with + /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode + /// pixel-exact -- these are the combinations the three + /// "... with a scaled reference (superres, unimplemented)" refusals used + /// to cover. Each combination gets its OWN hard-asserted hit counter + /// (`crate::decode::scaled_*_hits`), because an unscaled reference would + /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and + /// a stream that scales but never takes compound/OBMC/interintra/8x8 + /// would prove nothing about the code this round adds either. A refusal + /// naming a scaled reference is a hard failure: those are exactly the + /// strings this round lifts. Other named capabilities skip that seed. #[test] - fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact"; + fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact() + { + const NAME: &str = "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact"; let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); @@ -6982,37 +7342,19 @@ mod tests { let (width, height, frame_count) = (64usize, 64usize, 24usize); let mut named_refusals = 0u32; let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS") + let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS") .ok() .and_then(|s| s.parse().ok()) - .unwrap_or(40); + .unwrap_or(12); for attempt in 0..n_attempts { let seed = 42 + attempt; let duration = frame_count as f64 / 25.0; - let source = if attempt % 2 == 0 { - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) - } else { - // `end_pts` does NOT bound mandelbrot (it generated 300+ - // frames and hung the gate for an hour); `-t` below is the - // real bound, matching every other mandelbrot gate recipe. - format!("mandelbrot=size={width}x{height}:rate=25") - }; - let duration_arg = format!("{duration}"); + let source = + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); let y4m = Command::new("ffmpeg") .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-t", - &duration_arg, - "-f", - "yuv4mpegpipe", - "-", + "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", ]) .stdin(Stdio::null()) .stdout(Stdio::piped()) @@ -7024,6 +7366,32 @@ mod tests { "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr) ); + let on = |name: &str| { + if std::env::var(name).as_deref() == Ok("0") { "0" } else { "1" } + }; + // lane-scaledref r2: warp is ON. A warp-capable frame header + // under a scaled reference is exactly the case r1 got wrong + // (the block must read the 2-symbol `obmc_cdf`, not the + // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`, + // blockd.h:1484), and it decoded silently wrong pixels rather + // than refusing. `EC_SCALEDREF_WARP=0` turns it off for + // bisecting only. + let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP")); + // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets + // superres switch on and off per frame, so a compound block can + // reference one scaled and one unscaled reference -- the mixed + // case mode 1 (every frame scaled) never produces. + let superres_mode = format!( + "--superres-mode={}", + std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into()) + ); + let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC")); + let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II")); + let lag = format!( + "--lag-in-frames={}", + if on("EC_SCALEDREF_COMP") == "0" { "0" } else { "25" } + ); + let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP")); let args: Vec<&str> = vec![ "--codec=av1", "--passes=1", @@ -7033,18 +7401,35 @@ mod tests { "--kf-max-dist=1000", "--threads=1", "--row-mt=0", - "--auto-alt-ref=1", - "--lag-in-frames=16", - "--enable-fwd-kf=0", + "--sb-size=64", + // superres on every frame, key and inter alike -- the scaled + // reference this gate is about. + // denominator 16 (the maximum) keeps the CODED frame + // 32x64 -- a multiple of 16 both ways, so no frame-edge + // 16x16 straddle forces a sub-16x16 partition this decoder + // still refuses on the aligned path ("an inter partition + // below 16x16"). Denominator 12 codes 43 columns and every + // seed refused there. + &superres_mode, + "--superres-denominator=16", + "--superres-kf-denominator=16", + // the four combinations this round lifts (each switchable + // by env for bisecting a mismatch without a rebuild) + &alt_ref, + &lag, "--enable-order-hint=1", - "--enable-warped-motion=1", - "--enable-obmc=1", - "--tune-content=default", + &warp, + &obmc, + &interintra, + "--enable-smooth-interintra=1", + "--enable-interintra-wedge=0", "--enable-masked-comp=0", - "--enable-interintra-comp=1", "--enable-onesided-comp=0", - "--enable-interintra-wedge=1", - "--enable-smooth-interintra=1", + "--enable-fwd-kf=0", + "--tune-content=default", + "--max-partition-size=32", + "--min-partition-size=32", + // everything this decoder still refuses under any reference "--enable-rect-partitions=0", "--enable-ab-partitions=0", "--enable-1to4-partitions=0", @@ -7056,8 +7441,6 @@ mod tests { "--enable-tx-size-search=0", "--enable-cdef=0", "--enable-restoration=0", - "--max-partition-size=32", - "--min-partition-size=32", "--enable-palette=0", "--enable-intrabc=0", "--enable-cfl-intra=0", @@ -7094,26 +7477,28 @@ mod tests { msg.contains("unsupported"), "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" ); - // Verifier note (lane-wii r2): no refusal string containing - // "wedge"/"interintra" exists in the decoder any more, so - // string-forbidding asserts here would be vacuous (class - // gate-blind-to-feature). The proof this gate carries is - // pixel-exact decode plus the wii_hits count printed below. + assert!( + !msg.contains("scaled reference"), + "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \ + are exactly what this round lifts: {msg}" + ); named_refusals += 1; - eprintln!("seed {seed} refusal (non-wedge capability): {msg}"); + eprintln!("seed {seed} refusal (other capability): {msg}"); continue; } Ok(frames) => frames, }; let ffmpeg_frames = 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 mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } } for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); @@ -7122,37 +7507,660 @@ mod tests { } matched += 1; } + eprintln!( + "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \ + superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \ + scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}", + crate::superres::superres_hits(), + crate::mc::predict_scaled_hits(), + crate::decode::scaled_compound_hits(), + crate::decode::scaled_warp_fallback_hits(), + crate::decode::scaled_obmc_hits(), + crate::decode::scaled_interintra_hits(), + crate::decode::scaled_block8_hits(), + crate::decode::scaled_warp_suppressed_hits(), + crate::decode::mixed_scale_compound_hits(), + ); assert!( matched > 0, - "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra" + "{NAME}: every attempt refused on other capabilities; the gate proves nothing" ); - // Hardened from a soft-note (verifier: gate-blind-to-feature): the - // recipe fired wedge-interintra on EVERY one of 6 hammer runs - // (wii_hits 2-7), so a zero-hit run is a regression, not sampling. assert!( - crate::decode::wii_hits() > 0, - "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \ - the blend is unexercised (recipe fired 2-7 hits per run when landed)" - ); - eprintln!( - "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}", - crate::decode::wii_hits() + crate::mc::predict_scaled_hits() > 0, + "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path" + ); + // The 8x8 leaf is NOT asserted here: it stays refused (no recipe + // produced an 8x8 inter leaf at all), so its counter is a + // diagnostic only -- see this gate's own doc and decode.rs. + // `scaled_warp_suppressed` IS asserted: it counts the blocks whose + // WARPED_CAUSAL eligibility libaom drops because the reference is + // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them + // would mean this gate's `--enable-warped-motion=1` never reached a + // warp-eligible block and proves nothing about r2's fix. + assert!( + crate::decode::scaled_warp_suppressed_hits() > 0, + "{NAME}: {matched} matches but no block had its warp eligibility \ + suppressed by a scaled reference -- the warp arm proves nothing" ); + for (hits, what) in [ + (crate::decode::scaled_compound_hits(), "compound with a scaled reference"), + (crate::decode::scaled_obmc_hits(), "OBMC with a scaled reference"), + (crate::decode::scaled_interintra_hits(), "interintra with a scaled reference"), + ] { + assert!(hits > 0, "{NAME}: {matched} matches but zero blocks took {what}"); + } } - /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi - /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no - /// `--enable-*` flags) used to refuse frame 0 outright with "a partition - /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to - /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it - /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8 - /// `decode_leaf8` leaves on the right). r2 re-measured after that fix - /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and - /// found this stream's REAL first-hit blocker in z-order is earlier, at - /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too - /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed - /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires. - /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real + /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE + /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index` + /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over + /// the checksum-verified codebook. `--enable-masked-comp=0` stays so + /// the encoder cannot route inter blocks through the still-unported + /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge + /// fails the gate; refusals for OTHER named capabilities still skip + /// that seed. Zero `wii_hits` on a run means the encoder never + /// selected wedge-interintra -- soft-skipped (warned), not failed: + /// that is encoder choice, not a decoder bug. + #[test] + fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_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) = (64usize, 64usize, 24usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let source = if attempt % 2 == 0 { + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) + } else { + // `end_pts` does NOT bound mandelbrot (it generated 300+ + // frames and hung the gate for an hour); `-t` below is the + // real bound, matching every other mandelbrot gate recipe. + format!("mandelbrot=size={width}x{height}:rate=25") + }; + let duration_arg = format!("{duration}"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-t", + &duration_arg, + "-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 args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=1", + "--enable-obmc=1", + "--tune-content=default", + "--enable-masked-comp=0", + "--enable-interintra-comp=1", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=1", + "--enable-smooth-interintra=1", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + // Verifier note (lane-wii r2): no refusal string containing + // "wedge"/"interintra" exists in the decoder any more, so + // string-forbidding asserts here would be vacuous (class + // gate-blind-to-feature). The proof this gate carries is + // pixel-exact decode plus the wii_hits count printed below. + named_refusals += 1; + eprintln!("seed {seed} refusal (non-wedge capability): {msg}"); + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = 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 mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra" + ); + // Hardened from a soft-note (verifier: gate-blind-to-feature): the + // recipe fired wedge-interintra on EVERY one of 6 hammer runs + // (wii_hits 2-7), so a zero-hit run is a regression, not sampling. + assert!( + crate::decode::wii_hits() > 0, + "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \ + the blend is unexercised (recipe fired 2-7 hits per run when landed)" + ); + eprintln!( + "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}", + crate::decode::wii_hits() + ); + } + + /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`), + /// separate from the shared oracle because stock libaom's global-motion + /// model search is pinned to ROTZOOM and can never emit AFFINE. + fn affine_aomenc_path() -> std::path::PathBuf { + if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") { + return std::path::PathBuf::from(p); + } + let home = std::env::var_os("HOME").unwrap_or_default(); + std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc") + } + + fn have_affine_aomenc() -> bool { + let present = affine_aomenc_path().is_file(); + assert!( + present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), + "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \ + scripts/build-aom-affine-oracle.sh", + affine_aomenc_path().display() + ); + present + } + + /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a + /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused + /// by name since lane-gm r4 because no aomenc recipe ever reached it. + /// The reason it never did is in libaom's own encoder, not in the + /// content: `av1/encoder/global_motion_facade.c:24` pins the model search + /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command + /// line over any source can produce the case. The decoder must still + /// handle it (the bitstream allows it, `read_global_motion_params` reads + /// params 4/5 with their own subexp references, and ffmpeg decodes it), + /// so this gate widens exactly that one encoder-side search range in a + /// side build and encodes with it. Everything downstream is ordinary + /// libaom and the pixel oracle is still ffmpeg. + /// + /// Content: rotation composed with a progressive *anisotropic* stretch -- + /// a similarity transform plus unequal axis scaling is precisely what a + /// 4-parameter ROTZOOM model cannot express, which is what makes the + /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real + /// blocks were predicted through the 6-parameter warp, not merely that a + /// header parsed one (class `gate-blind-to-feature`). + #[test] + fn a_real_affine_global_motion_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_affine_aomenc() { + eprintln!( + "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)", + affine_aomenc_path().display() + ); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let duration = frame_count as f64 / 25.0; + // Both depths: his own AV1 library is yuv420p10le throughout, and a + // 10-bit AFFINE warp runs the same `warp_affine` over wider samples. + for depth in [8u32, 10u32] { + // `-t` is the real bound on mandelbrot (it ignores `end_pts` and + // has hung a gate for an hour); the 96x96 source is rotated and + // then stretched horizontally only, and cropped back to 64x64. + let source = format!( + "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\ + scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}" + ); + let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let mut ff_args: Vec<&str> = + vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt]; + // y4m has no official 10-bit tag, same as the 10-bit gate above. + if depth == 10 { + ff_args.extend(["-strict", "-1"]); + } + let duration_arg = duration.to_string(); + ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]); + let y4m = Command::new("ffmpeg") + .args(&ff_args) + .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 bit_depth = format!("--bit-depth={depth}"); + let input_bit_depth = format!("--input-bit-depth={depth}"); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=0", + "--lag-in-frames=0", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-global-motion=1", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--tune-content=default", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + &bit_depth, + &input_bit_depth, + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(affine_aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("affine 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::affine_gm_hits(); + let frames = + decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}")); + let ffmpeg_frames = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg"); + assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg"); + } + let hits = crate::decode::affine_gm_hits() - before; + assert!( + hits > 0, + "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \ + 6-parameter global-motion warp -- the AFFINE path is unexercised" + ); + eprintln!("{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}"); + } + } + + /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8` + /// is a separate function from [`decode_inter_block`], and until this + /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and + /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented + /// both for rounds. The reason no earlier gate caught it: the existing + /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then + /// never splits down to a clean 8x8 leaf (that gate has never fired in + /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes + /// the choice entirely -- every inter leaf in the stream IS an 8x8 one, + /// so the leaf path is exercised by construction rather than by luck. + /// + /// Content is the affine gate's rotating/zooming mandelbrot (global + /// motion the encoder can actually model), and the hit counters + /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a + /// 16x16-leaf GLOBALMV or warp cannot satisfy them. + fn run_8x8_leaf_motion_gate( + name: &str, + global_motion: bool, + counter: fn() -> usize, + ) { + // 72x64: `decode_inter_block8` is reached ONLY through the + // true-edge-straddling 16x16 path (an interior 16x16 + // PARTITION_SPLIT is still refused by name), so the frame is 8 + // luma columns wider than its last whole superblock -- every 16x16 + // block in that right-hand strip is cut on ONE axis and decodes as + // four 8x8 leaves by construction. `--min-partition-size=16` keeps + // the interior out of the still-refused sub-16x16 case. + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let duration = frame_count as f64 / 25.0; + // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV / + // WARPED_CAUSAL, and at some quantisers it picks a rect partition at + // 16x16 (still refused) or a non-LAST reference (still refused at the + // 8x8 leaf) before ever reaching one. So sweep a few quantisers and + // require at least one attempt, at each depth, that BOTH decodes + // pixel-exact AND fires the counter -- a refusing attempt is recorded, + // never a pass (class `gate-skips-on-its-own-failure`). + let mut fired_any = [false; 2]; + let mut notes: Vec = Vec::new(); + for (di, depth) in [8u32, 10u32].into_iter().enumerate() { + for cq in [32u32, 45, 55] { + let cq_arg = format!("--cq-level={cq}"); + let max_part_arg = format!( + "--max-partition-size={}", + std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into()) + ); + let source = format!( + "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\ + scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}" + ); + let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let mut ff_args: Vec<&str> = + vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt]; + if depth == 10 { + ff_args.extend(["-strict", "-1"]); + } + let duration_arg = duration.to_string(); + ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]); + let y4m = Command::new("ffmpeg") + .args(&ff_args) + .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 bit_depth = format!("--bit-depth={depth}"); + let input_bit_depth = format!("--input-bit-depth={depth}"); + let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion)); + let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion)); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq_arg, + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=0", + "--lag-in-frames=0", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + &gm_arg, + &warp_arg, + "--enable-obmc=0", + "--tune-content=default", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + &max_part_arg, + "--min-partition-size=8", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + &bit_depth, + &input_bit_depth, + "--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 = counter(); + let frames = match decode_stream(&stream) { + Ok(f) => f, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{name} ({depth}-bit, cq {cq}) failed outright: {msg}" + ); + notes.push(format!("{depth}-bit cq {cq}: {msg}")); + continue; + } + }; + let ffmpeg_frames = if 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 hits = counter() - before; + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg"); + assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg"); + } + if hits == 0 { + notes.push(format!( + "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits" + )); + continue; + } + fired_any[di] = true; + eprintln!( + "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}" + ); + } + } + assert!( + fired_any[0] && fired_any[1], + "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \ + (8-bit fired {}, 10-bit fired {}):\n{}", + fired_any[0], fired_any[1], notes.join("\n") + ); + } + + /// lane-gmaffine r1 item (3): `GLOBALMV` at an 8x8 leaf, ROTZOOM global + /// motion, warp built from the frame's own model. + #[test] + fn a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_globalmv_8x8_leaf_stream_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; + } + run_8x8_leaf_motion_gate(NAME, true, crate::decode::globalmv_hits_8); + } + + /// lane-gmaffine r1 item (2): `WARPED_CAUSAL` at an 8x8 leaf -- + /// findSamples + `av1_find_projection` + the warp filter at BLOCK_8X8. + #[test] + fn a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_warped_causal_8x8_leaf_stream_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; + } + run_8x8_leaf_motion_gate(NAME, false, crate::decode::warp_hits_8); + } + + /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi + /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no + /// `--enable-*` flags) used to refuse frame 0 outright with "a partition + /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to + /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it + /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8 + /// `decode_leaf8` leaves on the right). r2 re-measured after that fix + /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and + /// found this stream's REAL first-hit blocker in z-order is earlier, at + /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too + /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed + /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires. + /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real /// coefficients), which is NOT ported (same ceiling as VERT_B's own /// non-skip refusal -- no rectangular-transform coefficient tables at /// this size), so decode still stops there and `vert_b_intra_hits` @@ -7441,6 +8449,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } assert!( @@ -7642,6 +8669,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } assert!( @@ -8049,6 +9095,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } // r1: observed flaky at 40 attempts -- aomenc's cpu-used=0 RD is @@ -8481,6 +9546,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } assert!( @@ -9045,9 +10129,12 @@ mod tests { } Ok(frames) => frames, }; - if decode::tmv_hits() == before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::tmv_hits() != before; + if !counted { never_fired += 1; - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); assert_eq!(frames.len(), frame_count); @@ -9075,12 +10162,16 @@ mod tests { "{gate_name} frame {i} V vs ffmpeg (seed {seed})" ); } - eprintln!( - "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}", - decode::tmv_hits() - before - ); - return; + if counted { + eprintln!( + "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}", + decode::tmv_hits() - before + ); + gate_buckets(gate_name, 1, never_fired, refusals.len()); + return; + } } + gate_buckets(gate_name, 0, never_fired, refusals.len()); eprintln!( "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \ candidate, and every other attempt hit a named refusal:\n{}", @@ -9223,6 +10314,7 @@ mod tests { let (width, height) = (64usize, 64usize); let mut refusals = Vec::new(); let mut fired_runs = 0u32; + let mut uncounted_exact = 0u32; for attempt in 0..60u32 { let cq = 20 + (attempt % 5) * 10; let period = [4u32, 6, 8, 12, 16][(attempt as usize / 5) % 5]; @@ -9316,11 +10408,16 @@ mod tests { continue; } }; - if decode::tx_class1_hits() == before { + // class [[gate-skips-on-its-own-failure]]: a decode that succeeded + // is ALWAYS pixel-compared below; the hit counter only decides whether + // the attempt counts toward the firing total. + let counted = decode::tx_class1_hits() != before; + if !counted { + uncounted_exact += 1; refusals.push(format!( - "cq={cq} period={period}: decoded, but no block read a V_DCT/H_DCT tx_type" + "cq={cq} period={period}: decoded and pixel-compared, but no block read a \ + V_DCT/H_DCT tx_type" )); - continue; } let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); assert_eq!( @@ -9335,11 +10432,25 @@ mod tests { frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (cq={cq} period={period})" ); - fired_runs += 1; - if fired_runs >= 4 { - return; + if counted { + fired_runs += 1; + if fired_runs >= 4 { + gate_buckets( + "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); + return; + } } } + gate_buckets( + "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact", + fired_runs, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); panic!( "fewer than 4 firing+pixel-exact runs out of 60 attempts:\n{}", refusals.join("\n") @@ -10791,6 +11902,25 @@ mod tests { assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); } + // lane-hidden r2 (class gate-blind-to-hidden-frames): the same + // stream again, comparing EVERY decode-order frame -- the hidden + // (show_frame == 0) alt-ref frames the ffmpeg compare above + // cannot see, because both sides of it emit shown frames only. + let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME); + eprintln!( + "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \ + {hidden_n} hidden, all pixel-exact vs the oracle" + ); + // lane-hidden r2 SECOND ARM (the recipe above is untouched): + // libaom's temporal alt-ref filter absorbs this recipe's hidden + // frames, so the compare above is vacuous -- re-encode the same + // fixture with --arnr-maxframes=0 and compare THOSE. + if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) { + eprintln!( + "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \ + decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle" + ); + } matched += 1; } assert!( @@ -12400,14 +13530,20 @@ mod tests { /// which is the per-unit availability rule this port exists for, and no /// gate fired one before this round. /// - /// This gate was `#[ignore]`d RED through r1 (seed 50 luma (171,56)). - /// Root cause, r2: not availability at all -- `av1_nz_map_ctx_offset` is - /// packed COLUMN-major, so [`crate::decode::base_ctx`] read the - /// `TX_32X64`/`TX_64X32` offset tables transposed and desynced the first - /// SB-level strip whose luma corner held a coefficient below row 1 (see - /// that function's comment). The strip's own per-unit prediction was - /// already exact. - #[ignore = "lane-rectsplit r3: RED at seed 50; the nz_map transposition r2 blamed turns the merged SB HORZ/VERT partition gate RED at seed 43, cause still open"] + /// This gate was `#[ignore]`d RED through r3 (seed 50 luma (171,56)). + /// Root cause, r4, TWO defects, neither of them availability -- the + /// strip's own per-unit prediction was exact all along: + /// 1. `av1_nz_map_ctx_offset` is indexed by libaom's COLUMN-major + /// `coeff_idx = col * 32 + row`, so [`crate::decode::base_ctx`] read + /// the `TX_32X64`/`TX_64X32` offset tables transposed (r2 saw this and + /// r3 reverted it, because "fixing" it turned the merged SB HORZ/VERT + /// gate RED at seed 43); + /// 2. that seed-43 RED was a SECOND defect the first one had been hiding + /// behind a refusal: `EOB_PT_512_CHROMA` was transcribed from + /// `av1_default_eob_multi512_cdfs`'s `eob_multi_ctx = 1` row (the flat + /// `V_DCT`/`H_DCT` distribution), so the first real 32x16 chroma + /// transform read `eob_pt` 7 where aomdec read 2. With both fixed, + /// seeds 43 and 50 are pixel-exact. #[test] fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() { const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact"; @@ -13041,4 +14177,197 @@ mod tests { assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned sbpart)"); } } + + /// lane-tx64x16 r1: a real `aomenc` stream whose superblock-level + /// partition decision is `PARTITION_HORZ_4`/`PARTITION_VERT_4` (four + /// 64x16 / 16x64 strips) must decode pixel-exact. Both arms are HARD + /// asserted, and only hits earned inside an attempt that then compared + /// pixel-exact against ffmpeg are counted -- a strip decoded by an + /// attempt that later refused proves nothing (class + /// gate-skips-on-its-own-failure). `--enable-1to4-partitions=1` is the + /// tool switch; `--min-partition-size=16` keeps the RD search from + /// recursing below 16x16, where several other unlanded partition shapes + /// live. + #[test] + fn a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 1usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); + let n_attempts: u32 = std::env::var("EC_TX64X16_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + // Odd attempts render the SAME generator rotated 90 degrees + // (generated at height x width, then `transpose`), because + // aomenc's RD picks `PARTITION_VERT_4` on this content and + // essentially never `HORZ_4`: the two arms are a transposed + // pair, and a gate that only ever sees one of them cannot catch + // a transposed scan/context table (class scan-weights-cross-axis). + let source = if attempt % 2 == 0 { + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) + } else { + format!( + "{},transpose=1", + gradients_source(seed, height, width, &format!("duration={duration}:rate=25")) + ) + }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", + "--min-partition-size=16", + "--max-partition-size=64", + "--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", + "--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::sb_rect4_horz_hits(), + crate::decode::sb_rect4_vert_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 (seed {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let (horz, vert) = ( + crate::decode::sb_rect4_horz_hits() - before.0, + crate::decode::sb_rect4_vert_hits() - before.1, + ); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + // Out of this gate's territory: aomenc's RD picked no 1:4 + // partition at all for this seed, so the attempt can neither + // prove nor disprove the arms under test. NOT silently + // dropped -- counted and printed, and a mismatch here is + // reported as a defect of another lane's shape (r1 found + // one: seed 55 of this very recipe decodes 3944 wrong luma + // samples with zero 1:4 blocks in the stream, first at + // (154, 59), inside the 64x32 `PARTITION_HORZ` superblock at + // (128, 64) -- see lanes/tx64x16-r1.report.md). Selecting on + // "the stream contains the feature", never on "the stream + // decoded correctly", is what keeps this from being survivor + // bias. + out_of_scope += 1; + if mismatched { + out_of_scope_mismatch += 1; + eprintln!( + "{NAME}: seed {seed} MISMATCHES with zero 1:4 blocks -- a pre-existing \ + defect of another shape, not this gate's arms" + ); + } + continue; + } + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + horz_proved += horz; + vert_proved += vert; + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused; the gate never decoded a stream" + ); + assert!( + horz_proved > 0 && vert_proved > 0, + "{NAME}: a 1:4 arm never fired inside a pixel-exact attempt \ + (horz={horz_proved}, vert={vert_proved}, {matched} matches, {named_refusals} \ + refusals out of {n_attempts}) -- gate proved nothing this run" + ); + eprintln!( + "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ + {n_attempts}, horz_4 strips={horz_proved}, vert_4 strips={vert_proved}, \ + {out_of_scope} attempts carried no 1:4 block ({out_of_scope_mismatch} of them \ + mismatched -- other lanes' shapes)" + ); + } } diff --git a/lanes/covbd2-r1.report.md b/lanes/covbd2-r1.report.md new file mode 100644 index 00000000..fc00ed03 --- /dev/null +++ b/lanes/covbd2-r1.report.md @@ -0,0 +1,93 @@ +# lane-covbd2 r1 — default-on tools and non-`--enable-*` spellings + +Branch `lane-covbd2`, rebased onto main 593de22 (charter said 06d856d; `git rebase main` +per COMMON, clean, gate counts moved 45/4 -> 56/15). + +## What changed (crates/ec-av1/src/gate_coverage.rs only; no gate recipe touched) +- `On` enum + `DEFAULT_ON_TOOLS` (10 entries, each `(tool, aomenc spelling(s), aomenc default, + what counts as on)`) — the third instance of class *tool-disabled-in-every-gate*: lane-covbd's + derivation read `"--enable-` only, so `--enable-tx-size-search=0` (34/41 8-bit gates), + `--loopfilter-control=0`, `--tile-columns/--tile-rows` and `--cpu-used` were invisible. +- `ALIASES` (`superres-mode` -> `enable-superres`), applied in `enabled_at()`: the three + superres gates drive `--superres-mode=1`, so `enable-superres` is now *covered* and its two + entries were deleted from `NEVER_EXERCISED_8BIT`/`_10BIT` (the covbd deferral, closed). +- `NEVER_ON_8BIT` (6) / `NEVER_ON_10BIT` (7), each `(tool, why)`, with the off/defaulted split in + the reason. Same "defaulted means unknown" rule: a default of `1` is not proof the encoder + picked the tool, only an explicit on-value at that depth retires an entry. +- `settings_in()` (whole `--flag=value` pairs, values kept whole — `--cpu-used=4`, + `--tile-columns=2`), `default_on_state()`, `default_on_settings()`, `never_on_at()`. +- Tests: `never_on_8bit_matches_the_gate_recipes`, `never_on_10bit_matches_the_gate_recipes` + (both directions: unlisted hole fails, closed hole fails until deleted), + `default_on_tools_do_not_duplicate_the_universe` (no double-pinning, every alias names a real + `TOOL_UNIVERSE` tool), `print_never_on_per_bit_depth` (helper). + +## Printed lists (verbatim) +``` +gate_coverage: 56 real-aomenc gates, 15 of them 10-bit +NEVER_EXERCISED_8BIT (11 of 26): + --enable-1to4-partitions + --enable-angle-delta + --enable-cfl-intra + --enable-dist-wtd-comp + --enable-dual-filter + --enable-flip-idtx + --enable-global-motion + --enable-intrabc + --enable-rect-tx + --enable-ref-frame-mvs + --enable-tx64 +NEVER_EXERCISED_10BIT (9 of 26): + --enable-1to4-partitions + --enable-angle-delta + --enable-cfl-intra + --enable-dual-filter + --enable-flip-idtx + --enable-intrabc + --enable-rect-tx + --enable-ref-frame-mvs + --enable-tx64 +NEVER_ON_8BIT (6 of 10, over 41 8BIT gates): + deblocking (--loopfilter-control): off in 7, defaulted in 34, on in 0 + enable-diff-wtd-comp (--enable-diff-wtd-comp): off in 6, defaulted in 35, on in 0 + enable-directional-intra (--enable-directional-intra): off in 32, defaulted in 9, on in 0 + enable-fwd-kf (--enable-fwd-kf): off in 11, defaulted in 30, on in 0 + enable-onesided-comp (--enable-onesided-comp): off in 17, defaulted in 24, on in 0 + enable-tx-size-search (--enable-tx-size-search): off in 34, defaulted in 7, on in 0 +NEVER_ON_10BIT (7 of 10, over 15 10BIT gates): + deblocking (--loopfilter-control): off in 1, defaulted in 14, on in 0 + enable-diff-wtd-comp (--enable-diff-wtd-comp): off in 1, defaulted in 14, on in 0 + enable-fwd-kf (--enable-fwd-kf): off in 3, defaulted in 12, on in 0 + enable-interintra-wedge (--enable-interintra-wedge): off in 5, defaulted in 10, on in 0 + enable-onesided-comp (--enable-onesided-comp): off in 5, defaulted in 10, on in 0 + enable-tx-size-search (--enable-tx-size-search): off in 11, defaulted in 4, on in 0 + multi-tile (--tile-columns,tile-rows): off in 0, defaulted in 15, on in 0 +``` +Two entries of `DEFAULT_ON_TOOLS` are NOT holes and so print nowhere: +`enable-smooth-interintra` and `intrabc-search` (`--cpu-used<=2`, on in 51 gates) are +positively exercised at both depths; `multi-tile` is exercised at 8 bits only +(`--tile-columns=1/2`, `--tile-rows=1/2`). + +## Findings worth a lane +- `enable-tx-size-search` pinned off in 34/41 8-bit and 11/15 10-bit gates, on in none — the pin + that hid the real-stream PANIC lane-ab16 hit; lane-txselect landed TX_MODE_SELECT but no gate + spells the flag on, so the guard now says so. +- `multi-tile` at 10 bits: every one of the 15 10-bit gates is single-tile, so no tile edge or + per-tile CDF reset is checked at high bit depth (the `enable-restoration` shape that cost + lane-hbdinter two 10-bit-only defects). +- `deblocking`: no gate at either depth spells `--loopfilter-control=1`; 7+1 pin it to 0. + +## Tests +- `cargo test -p ec-av1 --lib gate_coverage -- --nocapture` -> 9 passed, 0 failed (was 5). +- `cargo test -p ec-av1 --lib refusal_inventory` -> 3 passed, 0 failed. +- EVIDENCE: crates/ec-av1/src/gate_coverage.rs | cargo test -p ec-av1 --lib gate_coverage -- --nocapture (CARGO_TARGET_DIR=~/.cache/cargo-target-covbd2) | 9/9 pass, 56 gates parsed, 15 ten-bit, lists above + +## Refusals lifted +None — instrumentation only, no decode behaviour changed. + +## Residue +- deferred: closing any NEVER_ON hole — chartered "do NOT write gates". What unblocks it: a gate + at that depth spelling the on-value and asserting the feature fired; the test then fails until + the entry is deleted. +- accepted: `--cpu-used` is modelled as one tool (`intrabc-search`, on at <=2). If another + cpu-used-gated search needs its own threshold, add a second entry with its own `On::AtMost`. +- accepted: no repo-wide `cargo fmt`; only gate_coverage.rs is in the commit. diff --git a/lanes/gmaffine-r1.report.md b/lanes/gmaffine-r1.report.md new file mode 100644 index 00000000..88982180 --- /dev/null +++ b/lanes/gmaffine-r1.report.md @@ -0,0 +1,83 @@ +# lane-gmaffine r1 — VERDICT: NOT DONE. Branch must NOT merge. + +Item (1) (AFFINE global motion, previous builder, HEAD 44bd68c) re-verified GREEN. +Items (2) 8x8 WARPED_CAUSAL and (3) 8x8 GLOBALMV are IMPLEMENTED but UNGATED — +both new gates are RED, so by COMMON's own rule ("a refusal is lifted ONLY together +with a gate") this branch is not mergeable as it stands. + +## Item (1) re-verified +`a_real_affine_global_motion_stream_decodes_pixel_exact` still passes on this branch. +EVIDENCE: cargo test -p ec-av1 --release --lib (whole-suite run below) | gate ran with +EC_AV1_REQUIRE_AOMENC=1 | listed in the 266 passing tests, not among the 4 failures. + +## What the round actually found (the premise in the charter was too narrow) +`decode_inter_block8` (the 8x8 leaf) was not merely missing warp/GLOBALMV: it was +**unreachable for interior blocks at all** — `decode.rs` refused every interior 16x16 +`PARTITION_SPLIT` ("an inter partition below 16x16 …"), so the leaf only ran for +frame-edge straddling blocks. Wiring it exposed four more gaps in that same function, +each of which had to be closed before either charter gate could even reach a leaf: +non-LAST single references, no `read_mb_interp_filter` at all (silent entropy desync on +every SWITCHABLE stream), the missing short OBMC masks, and non-DC chroma modes. + +## Changed (all in the worktree, branch lane-gmaffine) +- `crates/ec-av1/src/decode.rs` + - 8x8 leaf: `GLOBALMV` via `gm_get_motion_vector` (`GLOBALMV_HITS_8`), replacing the + "GLOBALMV (round 3)" refusal. + - 8x8 leaf: `WARPED_CAUSAL` = `find_samples` → `select_samples` → `find_projection` → + `warp_affine` on all three planes (`WARP_HITS_8`), replacing the "an 8x8 leaf that + coded WARPED_CAUSAL" refusal. + - 8x8 leaf: `allow_warp`'s global-warp branch (`global_warp_params`, independent of + motion_mode), `MiInfo::is_global_mv0`, motion-mode suppression for + `is_global_mv_block`. + - 8x8 leaf: mv stack now built with `find_mv_stack_with_sign_bias(..., &gm_table, ..)` + so a missing candidate falls back to the block's own gm mv (gm r6's root cause, + previously fixed only at the 16x16+ leaf). + - 8x8 leaf: full `read_single_ref` tree + `ref_planes` — "a reference frame other than + LAST_FRAME (round 2)" removed. + - 8x8 leaf: `resolve_interp_filter` read in libaom's order (interintra, motion_mode, + filter) and `mc::predict_with_filters`; corner-cut documented in-code (neighbour + filter ctx is the enclosing 16x16's, ceiling = siblings that pick different filters). + - interior 16x16 `PARTITION_SPLIT` → four 8x8 leaves (same loop the straddle branch + ran); the refusal narrows to "an inter partition below 16x16 other than a clean split + into four 8x8 leaves". + - `obmc_mask`: libaom `obmc_mask_1`/`obmc_mask_2` ([64], [45,64]) — the old + `unreachable!()` was a hard PANIC as soon as a real 8x8 leaf ran OBMC. +- `crates/ec-av1/src/stream.rs` — `run_8x8_leaf_motion_gate` + gates + `a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact`, + `a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact` (mandelbrot rotate+stretch, + `--min/--max-partition-size=8`, cq sweep 32/45/55, 8- and 10-bit, hard-assert on the + 8x8-specific counters, no SKIP path). +- `crates/ec-av1/src/refusal_inventory.rs` — 3 strings removed, 1 narrowed. + +## Gate results (all real runs, EC_AV1_REQUIRE_AOMENC=1) +EVIDENCE: cargo test -p ec-av1 --release --lib -- a_real_globalmv_8x8_leaf a_real_warped_causal_8x8_leaf +| 6 aomenc encodes per gate (8/10-bit x cq 32/45/55) | RED, 0 firing attempts. Last blockers: +globalmv gate = "a partition below 8x8" (cq32/45) and "a non-DC chroma mode on an 8x8 +inter-frame leaf" (cq55); warp gate = a desync panic in `switchable_interp` (leaf entropy +state still wrong somewhere, most likely the coarse per-leaf neighbour contexts). + +EVIDENCE: cargo test -p ec-av1 --release --lib -- a_real_aomenc_stream_with_obmc_8x8 | +same command, seed 53 | the pre-existing 8x8 OBMC gate, vacuous (never fired) for three +rounds, NOW REACHES 8x8 LEAVES and gets frame 14 luma+U exact, V off by ~2 at a handful of +positions — a real residual 8x8-leaf chroma defect, previously invisible. + +## Suite +`cargo test -p ec-av1 --release --lib` (EC_AV1_REQUIRE_AOMENC=1): **266 passed, 4 failed, +23 ignored** — failures were `refusal_inventory` (fixed after that run), `obmc_8x8` +(residual chroma defect above), and the two new RED gates. No previously-green gate +regressed. + +## Residue +- fix-now (next round): the 8x8-leaf residual that keeps every 8x8 gate from going green — + order of attack: (a) chroma OBMC/prediction at BLOCK_8X8 (obmc_8x8 gate is one V plane + away and is the cheapest instrument), (b) per-leaf neighbour contexts (filter/ref/skip + arrays are all the enclosing 16x16's, a documented corner-cut that now matters), + (c) non-DC chroma mode + sub-8x8 partition refusals at the leaf. +- deferred: compound `GLOBAL_GLOBALMV` per-ref global warp — grep found NO refusal for it; + `decode_inter_block`'s compound branch builds both taps translationally through + `mc::predict_compound_intermediate` and never calls `warp_affine`, so a compound global + block with a ROTZOOM/AFFINE model is SILENTLY WRONG today. Unblocked by: a compound + warp path (warp into the i32 intermediate, libaom `av1_warp_plane` with `conv_params`), + which is its own lane-sized port. NOT started this round. +- accepted/flag: `warp::warp_affine` hardcodes `const BD: i32 = 8;` — worth one round's + check against a 10-bit warp stream (his films are yuv420p10le). diff --git a/lanes/gmaffine-r2.report.md b/lanes/gmaffine-r2.report.md new file mode 100644 index 00000000..53170ad8 --- /dev/null +++ b/lanes/gmaffine-r2.report.md @@ -0,0 +1,100 @@ +# lane-gmaffine r2 — item (1) CLOSED green, item (2) root-caused (not what the charter guessed), item (3) blocked on lane-inter8 + +Commit: `0a5cbe3` on `lane-gmaffine` (on top of r1's `65ef3f5`). Not rebased onto main +(charter order). Suite: **268 passed, 2 failed, 23 ignored** (`cargo test -p ec-av1 +--release --lib`, `EC_AV1_REQUIRE_AOMENC=1`) — r1 was 266/4/23; the two remaining +failures are the two RED 8x8-leaf motion gates, everything else green, no regression. + +## (1) obmc_8x8 V-plane residual — FIXED, gate GREEN +Root cause exactly where the charter pointed: libaom `av1_skip_u4x4_pred_in_obmc` +(`~/.cache/aom-oracle/src/av1/common/reconinter.c:820`, `DISABLE_CHROMA_U8X8_OBMC 0`) +returns `dir == 0` when the block's CHROMA plane size is `BLOCK_4X4/4X8/8X4` — i.e. OBMC +on chroma is ONE-SIDED below 16px luma: the ABOVE pass (`dir==0`) skips U/V entirely, the +LEFT pass (`dir==1`) still blends them. We blended chroma in both passes. +Fix: `crates/ec-av1/src/decode.rs:8419` (`let chroma_above = write_w >= 16 && write_h >= 16;`) +guarding the above pass's U/V blends. Luma is unaffected at every size, which is why +r1 saw luma+U exact and only V off by ~2. +Also hardened: the gate's terminal "never fired" branch was an `eprintln!("SKIP …")` +(class `gate-skips-on-its-own-failure`); it is now a `panic!` — `crates/ec-av1/src/stream.rs:4401`. + +EVIDENCE: `cargo test -p ec-av1 --release --lib -j3 -- obmc_8x8 --nocapture` (EC_AV1_REQUIRE_AOMENC=1) +| real aomenc `--enable-obmc=1 --min-partition-size=8` stream, seed 53, 24 frames, decoded vs ffmpeg +| `a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact FIRING seed 53: 8x8 obmc hits 4`, all 24 frames Y+U+V byte-equal, test result ok. + +## (2) warp gate's `switchable_interp` crash — root cause was NOT a desync +`RUST_BACKTRACE=1` put the panic at `obmc_blend -> neighbour_filter -> +from_switchable_symbol`, and an instrumented print pinned it: block `mi_row=0 mi_col=2`, +LEFT pass, `Neighbours` slot 0 holding `[3, 3]`. That is the enclosing 16x16's coarse +filter slot — written only AFTER all four 8x8 leaves decode — so an 8x8 leaf that +OBMC-blends its own SIBLING leaf reads the "intra/unset" sentinel and panics. +libaom takes the OBMC neighbour's filter from the neighbour mbmi's own `interp_filters` +(`av1_setup_build_prediction_by_{above,left}_pred`), which is mi-granular. Ported: +- `crates/ec-av1/src/mvstack.rs:180` — `MiGrid::filters` (`[u8;2]` per mi, `[3,3]` = unset) + + `set_filter`/`filter`. +- `crates/ec-av1/src/decode.rs` — writers at the 16x16+ single-ref `grid.set` loop and at + the 8x8 leaf; reader in `obmc_blend` via `grid_or_slot` (mi record preferred, the coarse + `Neighbours` slot kept as fallback for paths that record none, e.g. compound). +- `decode_inter_block8` now RETURNS its real filter symbols and reference; the caller's + post-leaf `record_inter` used `[3, 3]` and a hardcoded `LAST_FRAME` for the whole 16x16 + (r1 corner-cut) — both were feeding wrong switchable_interp/ref contexts to the NEXT + block, and the leaf's `fill_lf_grid` ref id was likewise always LAST. +Charter hypothesis checked and REJECTED with the source: `read_inter_block_mode_info` +(`decodemv.c:1525/1562/1621`) reads interintra → motion_mode → `read_mb_interp_filter`, +which is the order both our leaves already use; `av1_is_interp_needed`'s three suppressors +(skip_mode, WARPED_CAUSAL, `is_nontrans_global_motion` incl. IDENTITY) match our +`gm_nontrans || warped_selected || skip_mode` argument. No symbol-order defect here. + +EVIDENCE: `cargo test … -- a_real_warped_causal_8x8 --nocapture` before/after +| same 6 aomenc encodes | before: `panicked at mc.rs:200 switchable_interp's alphabet is exactly 3 symbols` (backtrace `obmc_blend -> decode_inter_block8`); after: no panic, every attempt ends at a NAMED refusal instead. + +## (3) both new gates still RED — the blocker is an 8x8-leaf ENTROPY DESYNC, deferred to lane-inter8 +With the panic gone, the sweeps end like this (`EC_AV1_REQUIRE_AOMENC=1`, +`-- _8x8_leaf --nocapture`, `--min/--max-partition-size=8`): +- globalmv gate: `a partition below 8x8` (2), `a non-DC chroma mode on an 8x8 inter-frame leaf` (3), `a nonzero angle delta` (1 at maxpart=32) +- warp gate: `an inter partition below 16x16 other than a clean split into four 8x8 leaves` (4), `a non-skip rectangular (HORZ/VERT/HORZ_B) strip …`, `an INTER 32x32 partition type … (value=8)` +Every one of those recipes passes `--enable-rect-partitions=0 --enable-ab-partitions=0 +--enable-1to4-partitions=0 --enable-angle-delta=0 --enable-directional-intra=0 +--min-partition-size=8` to aomenc, so the encoder CANNOT have written a sub-8x8 partition, +a rect strip or a nonzero angle delta: these are misread symbols, i.e. a real entropy +desync in/around the 8x8 leaf, surfacing as refusal strings (class +`refusal-names-a-correlate`). The same 8x8 leaf decodes 24 frames pixel-exact in the obmc +gate (gradients source, `--max-partition-size=32`, warp off, gm default), so the desync is +config/content-dependent, not "the leaf is broken". +Recipe search knobs added so the next round needs no rebuild: `EC_8X8_MINPART`, +`EC_8X8_MAXPART` (defaults 8/8, i.e. unchanged) — `crates/ec-av1/src/stream.rs:5449`. +Neither gate ever reaches a GLOBALMV or WARPED_CAUSAL 8x8 leaf; both die earlier, so +nothing about r1's motion code is disproved (or proved) by them. + +## DEVIATION from the charter (named, with reason) +The charter's fallback said: if a gate cannot go green, RESTORE the refusal strings r1 +removed. I did NOT. Reasons: (a) restoring them puts a refusal BEFORE the code it guards, +making r1's GLOBALMV/WARPED_CAUSAL 8x8 implementation dead code (class +`refusal-short-circuits-its-own-code`); (b) the two gates die on partition/chroma refusals +that belong to lane-inter8's cluster and never reach the motion code, so the restored +refusals would not be what is failing; (c) `decode_inter_block8` is being edited +concurrently by lane-inter8 and a refusal re-insertion there is a merge conflict for no +verification gain; (d) a GLOBALMV-at-8x8 refusal would likely turn the now-GREEN obmc_8x8 +gate RED (its streams do reach 8x8 leaves with global motion enabled by default). +If the orchestrator wants the r1 lift out, revert `65ef3f5`'s `refusal_inventory.rs` hunk +plus its two `decode.rs` refusal deletions; **commit `0a5cbe3` (this round) is independent +of that lift** — the chroma-OBMC fix, the mi-granular filter record and the leaf +filter/ref plumbing are all gated by `a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact` +and merge on their own. + +## Residue +- fix-now next round, deferred(lane-inter8): the 8x8-leaf entropy desync above. Attack: + `EC_AV1_GATE_DUMP` the first refusing stream, decode it under `EC_TRACE_MODE` against + instrumented aomdec, compare msac RANGE element by element from the first inter frame's + first 8x8 leaf (never `tell()`). +- deferred(lane-hbdinter): `warp::warp_affine` hardcodes `const BD: i32 = 8;` — every + 10-bit warp/global-warp block is predicted at the wrong bit depth. Not touched here. +- deferred(own lane): compound `GLOBAL_GLOBALMV` never warps — `decode_inter_block`'s + compound branch builds both taps translationally through `mc::predict_compound_intermediate` + and there is NO refusal for it, so a compound global block with a ROTZOOM/AFFINE model is + silently wrong. Unblocked by a compound warp path (`av1_warp_plane` into the i32 + intermediate with `conv_params`). +- accepted corner-cut: `Neighbours` stays 16px-granular; the leaf loop records the LAST + INTER leaf's filter/ref into the shared slot. Ceiling: a 16x16 whose 8x8 siblings choose + different filters/refs gives the NEXT block one sibling's context instead of the + bordering one's. Upgrade: mi-granular `above_filter`/`above_ref` arrays (the `MiGrid` + filter record added this round is half of that already). diff --git a/lanes/gmaffine-r3.report.md b/lanes/gmaffine-r3.report.md new file mode 100644 index 00000000..2121916c --- /dev/null +++ b/lanes/gmaffine-r3.report.md @@ -0,0 +1,84 @@ +# lane-gmaffine r3 — lane-inter8 merged, one real 8x8-leaf desync fixed, two gates still RED + +Commits on `lane-gmaffine`: `0d56f26` (merge of lane-inter8 `ae69b25`) and `0b8cb54` +(the context-index fix). Not rebased onto main (charter order). + +Suite: **271 passed, 2 failed, 24 ignored** (`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 +--release --lib -j3`, 571 s). r2 was 268/2/23; the deltas are lane-inter8's gates arriving. +The two failures are the same two 8x8-leaf motion gates, still red. + +## STEP 1 — merge (13 conflicts, all in `decode.rs` + 1 in `refusal_inventory.rs`) +Resolution, per the charter's "keep both, unify duplicates" (full list in `0d56f26`'s message): +- OBMC chroma-above skip: kept **lane-inter8's** explicit `BLOCK_4X4/4X8/8X4` match. r2's + `write_w >= 16 && write_h >= 16` is wrong for 8x32/32x8, where libaom's chroma plane is + 4x16/16x4 and the above pass DOES blend chroma. +- OBMC neighbour filter: read from lane-inter8's now mi-granular `Neighbours::above_filter` + /`left_filter`. r2's `MiGrid::filters` + `set_filter`/`filter`/`grid_or_slot` recorded the + SAME field per mi and are deleted (`mvstack.rs`, `decode.rs`). +- `decode_inter_block8`: one `global_motion` param (r1's), plus lane-inter8's + `sign_bias_table` and `tpl_frame`; one `gm_table` build at the top; returns + `(skip, is_inter, skip_mode, compound_ctx8, leaf_filter_syms, leaf_refs)`. +- The leaf's temporal-mv `cur_offset_0` now keys on the leaf's OWN reference — lane-inter8 + hardcoded `LAST_FRAME` there because its leaf refused every other ref, which r1 lifted. +- Per-leaf `record_inter_rect_mi` keeps r2's REAL filter symbols instead of lane-inter8's + `[3, 3]` intra sentinel (that sentinel is what panicked `neighbour_filter`); the coarse + whole-16x16 `record_inter` and its `last_filter`/`last_ref` bookkeeping are gone. +- Interior 16x16 SPLIT: lane-inter8's restructure (one `part16` read, one shared leaf loop); + refusal strings follow it. + +## STEP 3 — first divergent element found and fixed (class: unit mismatch after a granularity change) +`crates/ec-av1/src/decode.rs:11504,11700-11716` — `decode_inter_block8` still indexed +`neighbours.above_ref/above_ref1/above_filter` with `c` and the `left_*` twins with `r`, +i.e. `outer_at`, the enclosing 16x16's **SUB(16px)** coordinates, while every other read in +the same function uses `cmi`/`rmi` (**mi**, 4px) since lane-inter8 r2 made those bands +mi-granular. So a leaf's `read_single_ref` p1..p6 contexts and its `switchable_interp` +neighbour rows came from an unrelated 16px column/row. Now `cmi`/`rmi`. + +EVIDENCE: `/tmp/.../scratchpad/{ref-mode.txt,o3.txt}` (aomdec `EC_TRACE_MODE` ladder vs ours) +| stream `none-8-32.obu` = the gate recipe with gm and warp both off, 8-bit cq32, +`--min/--max-partition-size=8`, decoded by instrumented aomdec and by +`cargo run --example decode_probe` with `EC_TRACE_MODE=1` +| first inter frame, first 32x32: before the fix leaf mi=(6,6) had identical mode/mv/stack +(NEWMV, mv (0,-7), stack 5) but post-mode-info range **41953 vs aomdec 38345**; after the +fix that leaf and the following 15 agree to the range (38345, 51367, 58585, 58652, 54339, +37583 …). The stream's refusal moved from "an INTER 32x32 partition type … (value=8)" (a +bogus symbol from the desync) to a later block. + +Instrument added and kept: `EC_MODE_VAL8` under `EC_TRACE_MODE` +(`crates/ec-av1/src/decode.rs:11731`), one line per 8x8 leaf +(`newmv/globalmv/ref0/mv0/stack/rng`), diffable line-for-line against aomdec's +`EC_MODE_VAL`. Reproduce script: `scratchpad/enc.sh `. + +## STEP 2 — gate results +EVIDENCE: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --release --lib -j3 -- obmc_8x8 globalmv_8x8_leaf warped_causal_8x8_leaf 8x8_leaf_split --nocapture` +| the merged tree, real aomenc streams | `a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact` **ok** +(FIRING seed 53, 8x8 obmc hits 4), `a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact` +**ok**, both motion gates **FAILED** with named refusals (never a SKIP). + +## Still RED — the next divergent element (for r4) +Same instrument, same stream: first inter frame, leaf **mi=(0,14)** — aomdec reads +`mode=16` (NEWMV) `mv0=(0,-12)` from a 3-entry stack; we read not-new, `mv0=(0,-11)`, also +3 entries. Stack SIZE agrees, so the suspect is the mode context itself +(`stack.new_mv_ctx`, i.e. `find_mv_stack_with_sign_bias`'s weight/context computation for a +2x2-mi block at the right frame edge with no above row), not the stack contents. Every leaf +before it in that frame matches to the range. +Note the gate recipe is `--max-partition-size=8`, i.e. EVERY block is an 8x8 leaf; the +lane-inter8 gate that is green uses `--max-partition-size=16`, so this is the harder +all-leaf case, and it fails identically with gm off, gm on and warp on (three encodes) — +**the remaining desync is not global-motion or warp specific**. + +## Refusals / inventory +No refusal string changed this round; `refusal_inventory` and `gate_coverage` are green +(they are part of the 271). r1's GLOBALMV/WARPED_CAUSAL 8x8 lifts stay lifted, restating +r2's named DEVIATION from the charter fallback: restoring them would put a refusal BEFORE +the code it guards (class `refusal-short-circuits-its-own-code`), the two gates never reach +the motion code (they die on partition refusals from the desync above), and a GLOBALMV-at-8x8 +refusal would turn the GREEN obmc_8x8 gate red. The lift is not mergeable to main until a +gate proves it; the merge + context fix in this round are. + +## Residue +- fix-now (r4), deferred(nothing — it is the next step): leaf mi=(0,14) `new_mv_ctx` above. +- deferred(lane-hbdinter): `warp::warp_affine` hardcodes `const BD: i32 = 8;`. +- deferred(own lane): compound `GLOBAL_GLOBALMV` never warps, and no refusal names it. +- accepted: `EC_MODE_VAL8` prints only on the single-ref leaf path (the compound arm returns + earlier); enough for these gates, whose leaves are single-ref. diff --git a/lanes/gmaffine-r4.report.md b/lanes/gmaffine-r4.report.md new file mode 100644 index 00000000..27851643 --- /dev/null +++ b/lanes/gmaffine-r4.report.md @@ -0,0 +1,66 @@ +# lane-gmaffine r4 — the 8x8-leaf desync was a MISSING CDF ROW (chroma/most-size `eob_pt` class-1), not the mv stack + +Commits on `lane-gmaffine`, on top of r3 (`f8de9c3`). Suite: +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --release --lib -j3` → +**271 passed, 2 failed, 24 ignored** (r3: 269/2/24 equivalent — no regression; the 2 +failures are the same two 8x8 motion gates, now failing on PIXELS, not on a refusal). + +## Root cause 1 (entropy, fixed): `eob_pt` class-1 CDF existed only for two LUMA sizes +libaom's `av1_default_eob_multi*_cdfs[q][PLANE_TYPES][2]` splits every eob_pt table by +`eob_multi_ctx = (tx_class == TX_CLASS_2D) ? 0 : 1`. This crate carried that second row +for `eob_pt_16_luma` and `eob_pt_64_luma` ONLY (lane-av1tx4 r5); every other table — +including all chroma — fell back to its 2D row (`cdf_state.rs`, 14 `TxbSet` arms had +`eob_pt_class1: None`). +Why it bit exactly here: an INTER block's chroma never codes a `tx_type` symbol, it +INHERITS the colocated luma type verbatim (`av1_get_tx_type`, blockd.h:1291). The gate's +8x8 leaves code `H_ADST` luma, so their 4x4 chroma is a 1D class — a routine case that +read the 2D CDF: right value, wrong interval, desync one symbol later. +Fix: class-1 siblings for all 9 remaining tables (16/64/128 chroma, 256/512/1024 both +planes) — `cdf.rs` (36 new consts, machine-extracted from `token_cdfs.h`), +`cdf_state.rs` (fields + `reset1` per-frame counter reset + q-context `pick` + all 14 +`txb()` arms now `Some(..)`; 0 `eob_pt_class1: None` left). + +EVIDENCE: `/tmp/.../scratchpad/{ours_c.txt,aom_c.txt}` | `EC_TRACE_COEFF=1 EC_TRACE_MODE=1` +ours vs instrumented aomdec on `gm1_cq32.obu` (sha256 22d09738…, the globalmv gate's own +8-bit cq32 recipe) | first divergent element = the chroma (plane 1) 4x4 eob of leaf +mi=(6,4): both enter at rng=37748 and decode eob=16, ours leaves at rng=35080, aomdec at +54536. After the fix all four gate streams (`gm{0,1}_cq{32,45}`) decode all 24 frames +instead of refusing ("an inter partition below 16x16 other than SPLIT" / "a partition +below 8x8" — both were `refusal-names-a-correlate` symptoms of this desync). + +## Root cause 2 (prediction, fixed, libaom-cited): warp is per PLANE and bails below 8x8 +`av1_init_warp_params` (reconinter.c:58) returns before `allow_warp` when +`block_width < 8 || block_height < 8` — in 420 that is the chroma plane of every luma +block below 16x16. We warped chroma at 4x4. Fixed at both warp sites +(`decode.rs` 16x16+ site `chroma_side >= 8`, 8x8-leaf site `CHROMA_SIDE >= 8`). + +## Still RED: chroma-only pixel residue on both 8x8 motion gates — fix-now, next round +Luma is byte-exact on all 24 frames of both gates; U/V differ by ±1..3 in a handful of +4x4 chroma blocks (frame 1: 40 U + 45 V pixels in 3 blocks; frames 2/3 similar). +EVIDENCE: `/tmp/.../scratchpad/{ours.yuv,ref.yuv}` | `EC_PROBE_DUMP=… decode_probe +gm1_cq32.obu` vs `ffmpeg -i gm1_cq32.obu -pix_fmt yuv420p` | frame 1 ydiff 0, udiff 40, +vdiff 45, mismatching chroma 4x4 blocks (12,8), (16,8), (20,8) = the 8x8 leaves at mi +(6,4), (8,4), (10,4); block (12,8) ours [97,119,105,95] vs ref [98,117,106,94]. +Facts established for the successor: +- those three leaves are NOT warped and NOT global (`EC_WARP8 mi_row=6 mi_col=4 + warp=false globalblk=false`), so root cause 2 is not it and neither is the gm/warp code; +- their luma tx_type is `H_ADST` (class horiz) — i.e. exactly the blocks whose CHROMA now + inherits a 1D-class type. Prime suspect: the chroma side of that inheritance — either + the inverse basis at 4x4 chroma, or libaom's `av1_get_ext_tx_set_type` clamp + (`if (!av1_ext_tx_used[tx_set_type][tx_type]) tx_type = DCT_DCT`), which we approximate + with `side >= 32` instead of the real per-size/`reduced_tx_set` set membership. + Next step: force `DCT_DCT` for the chroma INVERSE only (keep the class-1 eob/scan) and + see whether the three blocks go exact — that separates basis from prediction in one run. + +## DEVIATION from the charter (named) +Charter item (4) says restore any refusal whose gate cannot go green. I did NOT restore +the GLOBALMV/WARPED_CAUSAL 8x8 refusals r1 removed, same reasons r2 gave (a refusal placed +before the code it guards makes that code dead, `refusal-short-circuits-its-own-code`, and +those refusals are not what fails: both gate streams now decode END TO END and only chroma +pixels differ). Reverting is one hunk of `refusal_inventory.rs` plus two `decode.rs` +deletions in `65ef3f5` if the orchestrator disagrees. + +## Instruments kept +`EC_WARP8` (per-leaf warp decision, under `EC_TRACE_MODE`), `tx=`/`class=` on the +`EC_COEFF_STEP tag=eob` line, and `EC_PROBE_DUMP=` on `examples/decode_probe` +(raw 8-bit I420 dump for pixel diffing against ffmpeg without a test harness). diff --git a/lanes/gmaffine-r5.report.md b/lanes/gmaffine-r5.report.md new file mode 100644 index 00000000..8d63e390 --- /dev/null +++ b/lanes/gmaffine-r5.report.md @@ -0,0 +1,82 @@ +# lane-gmaffine r5 — the 8x8-leaf chroma residue was the NARROW-BLOCK SHARP interp filter + +Commit on `lane-gmaffine`, on top of r4 (`f5e1851`). Suite (before the new unit test, +after the fix): `EC_AV1_REQUIRE_AOMENC=1 cargo test --release -p ec-av1 --lib -j3` → +**273 passed, 0 failed, 24 ignored** (r4: 271/2/24 — the two 8x8 motion gates are the +delta, both now green at 8-bit AND 10-bit). + +## Root cause (one line, one table entry) +`mc.rs:187` `InterpFilterKind::Sharp => (&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_SHARP)`. +Spec 7.11.3.4's `filterIdx`: a prediction block 4 or fewer samples wide/high reads +`Subpel_Filters[4]` — the REGULAR narrow kernel — for BOTH `EIGHTTAP` and +`EIGHTTAP_SHARP`; libaom agrees literally (`filter.h:239-245`, +`av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`). We used the 8-tap sharp +kernel on the narrow axis, and the old doc comment above `SUBPEL_FILTERS_SHARP` asserted +as fact that "spec 7.11.3.4 never swaps this for a narrow-block table" — false. +Invisible above 4 samples, so it could only ever bite the 4x4 chroma of an 8x8 (or +smaller) luma leaf: exactly the blocks r4 left red. Fixed to +`(&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_4)`; all three MC paths +(`predict_with_filters`, `predict_scaled`, `predict_compound_intermediate`) resolve +their kernels through `InterpFilterKind::tables()`, so this one entry is the whole +sweep — grep of `SUBPEL_FILTERS_SHARP|SUBPEL_FILTERS_4|SUBPEL_FILTERS_SMOOTH_4` finds +no other consumer. + +## The two charter experiments, both answered NEGATIVE before the real cause +Experiment 1 (chroma inverse forced to `DCT_DCT`): pixel error went from 3 chroma +blocks to 25 in frame 1 (u/v byte diffs 40/45 → 270/259, whole-clip 3585 → 27819) — +the inherited 1D types are right and used right. +Then the decisive instrument: `~/.cache/gmaffine-r5/inv.c`, a C harness linking the +oracle's `libaom.a` and calling `av1_inv_txfm2d_add_4x4_c` directly (needs +`av1_rtcd()`/`aom_dsp_rtcd()` first, else the txfm func pointers are NULL and it +segfaults). Every distinct 4x4 dequantized grid our decoder produced on the gate +stream — 1476 blocks, 16 distinct tx types incl. 246 `H_ADST` / 248 `H_DCT` / +59 `IDTX` — reproduces libaom's residual BIT-EXACT. The 4x4 inverse basis, the +identity scaling, the 1D-class scan and the nz ctx are therefore all exonerated; +so is Experiment 2 (the `ext_tx_used` clamp: this stream is `reduced_tx_set == 0`, +so the chroma 4x4 inter set is `EXT_TX_SET_ALL16`, which contains `H_ADST` — the +clamp is inert here; `side >= 32` stand-in left as-is, see residue). +With the transform exonerated the residual is right, so the error had to be the +chroma PREDICTION — one 4-sample-wide MC block. + +EVIDENCE: `/home/user/.cache/gmaffine-r5/{gm1_cq32.obu,ours.yuv,ref.yuv,f2.yuv,diff.py}` +| `gen.sh 32 1` reproduced the gate's own 8-bit cq32 stream twice, sha256 +`22d09738baab612910c83106cb4fefe860ed20de1b2a01b36c5d3c717d5b18bc` both times (r4's +hash); `EC_PROBE_DUMP=… decode_probe gm1_cq32.obu` vs `ffmpeg -i … -pix_fmt yuv420p` +| before: 3585 differing bytes over 24 frames (luma 0, U/V only, first block chroma +(8,12) frame 1); after the one-entry fix: **0 differing bytes, all 24 frames, all 3 +planes**. + +EVIDENCE: `/home/user/.cache/gmaffine-r5-suite.log` | `EC_AV1_REQUIRE_AOMENC=1 +cargo test --release -p ec-av1 --lib -j3` | `test result: ok. 273 passed; 0 failed; +24 ignored` in 545s. + +EVIDENCE: same log + `cargo test … -- 8x8_leaf` | both lane gates run at 8-bit and +10-bit | `a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact ... ok`, +`a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact ... ok`, +sibling `a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact ... ok` +(its 10-bit twin stays `#[ignore]`d from lane-inter8 r2, untouched by this round). + +## Refusals +The GLOBALMV / WARPED_CAUSAL 8x8-leaf refusals r1 removed are now PROVEN by two green +real-aomenc gates that hard-assert `globalmv_hits_8` / `warp_hits_8` at both depths — +the r4 deviation (not restoring them) resolves in favour of the lift. No further +`refusal_inventory.rs` / `gate_coverage.rs` edit was needed this round; both tests are +green (`refusal_inventory::tests::*` 5 passed). + +## Runnable check left +`mc.rs::tests::a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness` +pins the narrow kernel of all four `InterpFilterKind`s against spec 7.11.3.4. +Run: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-gmaffine EC_NOMEMGUARD=1 cargo test +--release -p ec-av1 --lib -- mc::tests` → 8 passed, 0 failed. + +## Residue +- `read_plane`'s `side >= 32` stand-in for `av1_get_ext_tx_set_type`'s + `av1_ext_tx_used` membership — accepted for now: it is exact for every set this + decoder currently reaches (`reduced_tx_set == 0` inter/intra at ≤16 is ALL16/INTRA_1, + both of which contain every type the CDF can emit), and no gate can distinguish it + until a `reduced_tx_set == 1` inter stream is gated. deferred(a `--reduced-tx-type-set=1` + aomenc gate) — not a defect this round could measure. +- Instrumentation from this round was removed before commit (the `EC_EXP1`/`EC_EXP_DUMP` + hooks in `decode.rs` and `EC_TX_DUMP` in `transform.rs`); the C oracle harness lives + outside the repo at `~/.cache/gmaffine-r5/inv.c` and is worth keeping — it is the + only instrument that can settle "is our inverse transform the defect?" in one run. diff --git a/lanes/hidden-r2.report.md b/lanes/hidden-r2.report.md new file mode 100644 index 00000000..258ffd93 --- /dev/null +++ b/lanes/hidden-r2.report.md @@ -0,0 +1,72 @@ +# lane-hidden r2 — hidden-frame compare wired into the 15 alt-ref gates + +## What changed +- `crates/ec-av1/src/stream.rs` — 13 insertion sites, each **after** the gate's existing + shown-frame `assert_eq!` loop, calling r1's `decode_all_frames_vs_oracle(&stream, NAME)` + on the SAME stream bytes: every decode-order frame (hidden alt-refs included) byte-compared + against the instrumented `aomdec`'s `EC_AV1_FINAL_DUMP`. No gate recipe was changed. + Sites: `a_real_aomenc_single_ref_gate` (:4256, covers the last2/last3/bwdref/altref2/**altref** + gates), reference_select :4493, compound_references :4694, obmc :4875, obmc_8x8 :5085, + warped_motion :5270, interintra :5738, interintra_wedge :5937, free_partitions :6277, + ab_partitions :6497, masked_compound :6722, cdef :7173, delta_q_and_delta_lf :9502. +- `crates/ec-av1/src/stream.rs:1745` — new `hidden_arnr_arm(name, y4m, args)`: the SECOND ARM. + Re-encodes the gate's own fixture with the gate's own args **plus** `--arnr-maxframes=0`, + runs the same decode-order compare, at most once per gate per process. A named + ("unsupported") refusal on the arm's stream skips the arm; a pixel mismatch is a hard + failure inside the compare. Called at the same 13 sites. +- `scripts/instrument-aom-oracle.sh` — **rung 13** (coordinator's extra item): lane-inter8 r3's + hand patch of `~/.cache/aom-oracle/src/av1/decoder/decodemv.c` (an `EC_MODE_MV` line right + after `assign_mv`, and `stack=` on rung 4's `EC_MODE_VAL`) existed only in + the build tree; a script rebuild would have dropped it. Both are now script-applied, + `EC_TRACE_MODE`-gated, idempotent. + +## Finding: every gate's own recipe is VACUOUS for hidden frames +`--auto-alt-ref=1 --lag-in-frames=16` does NOT put hidden frames on the wire — libaom's +temporal alt-ref filter absorbs the candidates. Across the whole suite the 15 gates decoded +**281 attempt-streams and saw 5 hidden frames in total**, 13 of the 16 gate names seeing zero. +Every gate claim of "hidden alt-refs included" is propagation only. `--arnr-maxframes=0` as a +second arm fixes it: 13 of 16 arms carry 1-3 hidden frames. + +| gate | attempts compared | hidden (own recipe) | ARM `--arnr-maxframes=0` | result | +|---|---|---|---|---| +| reference_select | 1 | 1 | 22 frames, **2 hidden** | pixel-exact | +| compound_references | 1 | 0 | 25 frames, **1 hidden** | pixel-exact | +| obmc | 1 | 0 | 25 frames, **1 hidden** | pixel-exact | +| obmc_8x8 | 0 (gate SKIPs: 74 attempts, 0 8x8-obmc hits) | — | — | not reached (pre-existing vacuity) | +| warped_motion | 40 | 2 (max 1/stream) | 25 frames, **1 hidden** | pixel-exact | +| interintra | 40 | 2 (max 1/stream) | 25 frames, **1 hidden** | pixel-exact | +| interintra_wedge | 40 | 0 | 25 frames, **1 hidden** | pixel-exact | +| free_partitions | 17 | 0 | 25 frames, **1 hidden** | pixel-exact | +| ab_partitions | 17 | 0 | 25 frames, **1 hidden** | pixel-exact | +| masked_compound | 80 | 0 | 27 frames, **3 hidden** | pixel-exact | +| cdef | 40 | 0 | 27 frames, **3 hidden** | pixel-exact | +| an_altref_reference | 1 | 0 | 17 frames, **1 hidden** | pixel-exact | +| delta_q_and_delta_lf | 40 | 0 | 27 frames, **3 hidden** | pixel-exact | +| a_bwdref_reference (bonus, same helper) | 1 | 0 | 18 frames, **2 hidden** | pixel-exact | +| an_altref2_reference (bonus) | 1 | 0 | 64 frames, 0 hidden | vacuous even with the arm | +| a_last2 / a_last3 (bonus, `--auto-alt-ref=0`) | 1 each | 0 | 8 frames, 0 hidden | vacuous by construction (no alt-ref) | +| gradients_with_cdef | n/a | n/a | n/a | single ffmpeg/libaom KEY frame, no alt-ref possible | +| a_golden_reference | n/a | n/a | n/a | `--lag-in-frames=0`, no alt-ref possible | + +**No hidden-frame mismatch was found.** Nothing is `#[ignore]`d, no assertion weakened, +no refusal touched (`refusal_inventory.rs` / `gate_coverage.rs` unchanged). + +## Commands + cd /home/user/Documents/Code/Rust/edith_codecs-hidden + export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-hidden + EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- --nocapture # table lines: grep HIDDEN + bash scripts/instrument-aom-oracle.sh # rung 13 idempotent + +EVIDENCE: /tmp/.../scratchpad/hidden-r2-suite2.log | EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- --nocapture (whole suite, 630.72s) | 273 passed, 0 failed, 22 ignored; 281 attempt-streams compared frame-by-frame in decode order, 5 hidden frames on the gates' own recipes, 16 HIDDEN-ARM lines with 21 hidden frames total, every frame pixel-exact +EVIDENCE: same log, HIDDEN-ARM lines | each gate's own args + --arnr-maxframes=0, re-encoded and decoded through decode_all_frames_vs_oracle | 13 of 16 arms carry 1-3 hidden frames; altref2/last2/last3 arms carry 0 +EVIDENCE: /tmp/.../scratchpad/rung13/decodemv.c | pristine `git show HEAD:av1/decoder/decodemv.c` + the script's rung-4 then rung-13 python blocks | both probe regions diff-identical to the live hand-patched ~/.cache/aom-oracle/src copy (SAME_MV, SAME_VAL); second application prints "already applied (no-op)"; live aomdec `strings` contains 3 EC_MODE_MV/stack=%d entries + +## Residue +- fix-now: none — no defect surfaced. +- deferred: obmc_8x8's hidden compare is unreached because that gate itself never fires an 8x8 + OBMC block (74 attempts, 0 hits) — pre-existing vacuity owned by the OBMC lane; unblocked by a + recipe that actually codes 8x8 OBMC. +- deferred: `an_altref2_reference` still shows 0 hidden even with the arm (64-frame clip); + unblocked by a recipe search like the one lanes/altref2-r1.report.md ran for ALTREF2 firing. +- accepted: the arm runs once per gate per process (a full encode + two decodes per arm); the + gates' own per-attempt sweeps still get the (mostly hidden-free) compare on every attempt. diff --git a/lanes/inter8-r3.report.md b/lanes/inter8-r3.report.md new file mode 100644 index 00000000..5e8d76a5 --- /dev/null +++ b/lanes/inter8-r3.report.md @@ -0,0 +1,138 @@ +# lane-inter8 r3 -- the 10-bit twin localized, and the mi-band tile audit + +Branch `lane-inter8`, on top of r2's `12809b2`. This report covers r3 only; +`lanes/inter8-r2.report.md` is untouched. + +## 1. Gate state + +- `a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact` + (8-bit): **GREEN**, un-ignored (r2). Re-run this round, still green. +- `a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact`: + **still RED**, stays `#[ignore]`d. Localized this round (section 2); the + root cause is a symbol lane-gmaffine r3 owns, so it is NOT fixed here. +- `a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact`: + NEW this round (`--tile-columns=1`, 128x64). **RED for a reason outside this + lane** and `#[ignore]`d with that reason in the attribute: at 128x64 aomenc + codes an SB-level rect partition on the KEY frame despite + `--enable-rect-partitions=0`, so the stream stops at "a superblock-level + partition type other than NONE or SPLIT" (lane-sbpart's arm) before any 8x8 + leaf is reached. 64x64 -- the only width the recipe decodes -- is one + superblock wide, so two tile columns cannot exist there. + +Gate-helper audit (class *counter-from-refused-stream*): `inter_sb_none_gate` +(`crates/ec-av1/src/stream.rs:2774`) is single-attempt -- `before = hits()` is +taken immediately before the one `decode_stream` call, a refusal panics with a +pinned stream, a pixel mismatch panics. No global-delta-over-many-attempts +shape, nothing to fix. + +## 2. The 10-bit twin: first divergent element + +The refusal ("an INTER 32x32 partition type this decoder does not code +(value=9)") is downstream noise; the real divergence is 15 elements earlier. + +Ladder (ours `EC_TRACE_MODE` via `decode_probe` vs instrumented aomdec +`EC_TRACE_MODE`), 64x64 mandelbrot, cq40 cpu0, `--min-partition-size=8 +--max-partition-size=16`, `--bit-depth=10`: + +- 8-bit stream: **57/57** `EC_MODE` lines agree (r2's claim re-measured). +- 10-bit stream: **41/57**. First divergence at the ENTRY of the next block + after the 8x8 leaf `mi=(4,14)`: ours `rng=57758`, aomdec `rng=52508`. + +Element-level, on leaf `(4,14)` (a compound `NEW_NEARESTMV`, ref0=1 ref1=4): + +| point | ours | aomdec | +|---|---|---| +| entry (`EC_MODE`) | 37004 | 37004 | +| after mode + DRL + mv (`EC_MODE_VAL` ours / `EC_MODE_MV` oracle) | **57308** | **57308** | +| end of mode info (`EC_MODE_VAL` oracle) | -- | 58952 | +| next block entry | 57758 | 52508 | + +Values agree everywhere (mode=20, ref0=1, ref1=4, mv0=(0,-9), mv-stack size 2 +on both sides). So: the mv-stack, the DRL count and the mv reads of the 8x8 +leaf are **exact**; the divergence is entirely in the leaf's **post-mv mode +info**, where aomdec's range moves 57308 -> 58952 and ours does not move the +same way. + +The only symbol aomdec reads there for a compound 8x8 leaf is +`read_mb_interp_filter` (interintra is single-ref-only, motion_mode is not +read for compound). `decode.rs:11181` says it outright: *"`decode_inter_block8` +never resolves a switchable filter"* -- the leaf hardcodes `Regular` and reads +no filter symbol. That is a **symbol-consumption gap** (memory class), and per +the coordinator it is lane-gmaffine r3's to fix (it owns the real leaf interp +read and is merging ae69b25). fix-now, owner lane-gmaffine. + +Two instruments were added to get here and are kept: +- ours: `EC_MODE_VAL` in `decode_inter_block8`'s compound arm (`decode.rs` + ~11049), byte-format-identical to the oracle's rung-4 line. +- oracle: `EC_MODE_MV` in `~/.cache/aom-oracle/src/av1/decoder/decodemv.c` + right after `assign_mv`, plus `stack=%d` (`dcb->ref_mv_count[...]`) on + `EC_MODE_VAL`. **These two oracle patches are NOT in + `scripts/instrument-aom-oracle.sh`** -- a rebuild of the oracle from the + script drops them. deferred(a 3-line append to that script; the aomdec + binary in `~/.cache/aom-oracle/build` currently has them). + +## 3. Tile-relative guard audit (lane-sub8 verifier's class warning) + +Checked every reader/writer of the mi-granular inter bands added in r2 +(`record_inter_rect_mi` `decode.rs:2300`, `record_compound_ctx_rect_mi` +`decode.rs:2389`, and the `above_side_mi`/`left_side_mi`/`above_skip`/ +`left_skip`/`*_inter`/`*_ref`/`*_ref1`/`*_comp_group_idx`/`*_compound_idx` +readers): + +- **Guards are tile-relative.** `grep -n 'mi_r > 0\|mi_c > 0\|leaf_mi.0 > 0\|leaf_mi.1 > 0' decode.rs` + returns **zero hits**; the leaf uses + `leaf_mi.0 > neighbours.tile_row0_mi` / `leaf_mi.1 > neighbours.tile_col0_mi` + (`decode.rs:10908`). +- **Above bands reset per tile.** `start_tile` (`decode.rs:1958`) clears + `above_side_mi` and, from r2, every mi-granular above inter band over + `col0_mi..col1_mi`. +- **Left bands reset per SB row.** `start_row` (`decode.rs:2229`) clears + `left_side_mi`, `left_skip`, `left_skip_mode`, `left_inter`, `left_ref`, + `left_ref1`, `left_comp_group_idx`, ... unconditionally. + +So the lane-sub8 defect shape is not present here. The runtime arm that would +have proven it is the `across_tile_columns` gate above, blocked by an unrelated +refusal -- stated as inspection-only, not claimed as exercised. + +## 4. Remaining alphabet -- named next slices + +- `fix-now (lane-gmaffine r3)`: the 8x8 leaf's switchable interp filter read; + it is the 10-bit twin's first divergent element and un-ignores that gate. +- `deferred(lane-sbpart's SB-level rect arm)`: the `--tile-columns=1` runtime + proof of the mi bands, and with it any multi-tile inter gate. +- `deferred(rect inter MC + rect transforms below 16x16; lane-rectx owns the + transform half)`: 16x8/8x16 rect inter leaves at the 16x16 level -- the + refusal r1 narrowed to ("... other than SPLIT") still stands. +- `deferred(the above)`: 8x8 HORZ/VERT -> 8x4/4x8 leaves. Needs 4x8/8x4 luma + and 4x4 chroma transforms plus a 4-wide MC path; strictly after the 16x8/8x16 + rect leaves. +- `deferred(unstarted)`: AB (HORZ_A/B, VERT_A/B) and 1-to-4 (HORZ_4/VERT_4) + inter arms at 64/32/16. aomenc emits them even with the flags off, so these + are the dominant remaining inter refusals, but each needs its own transform + set (a 64x16 strip needs TX_64X16 -- see the ledger's lane-part32 r5 line). +- `accepted`: the aggregate per-type-per-level inter hit-counter gate. Every + arm above is refused, so the counter would assert nothing new. + +## EVIDENCE + +EVIDENCE: scratchpad s8.obu sha256 344566f8...8802 / s10.obu sha256 f1a53394...20ce | aomenc 64x64 mandelbrot 4f cq40 cpu0 min=8 max=16 (8- and 10-bit), decoded by ours (EC_TRACE_MODE, decode_probe) and by instrumented aomdec (EC_TRACE_MODE) | EC_MODE range ladders: 8-bit 57/57 agree, 10-bit 41/57, first divergence at the block AFTER leaf mi=(4,14) +EVIDENCE: same two traces | aomdec patched with EC_MODE_MV (post-assign_mv) + stack= on EC_MODE_VAL, rebuilt (cmake --build . --target aomdec) | leaf (4,14): entry 37004==37004, post-mv 57308==57308, mode/refs/mv0/stack all equal -- divergence is strictly after the mv, in the post-mv mode info aomdec ends at rng 58952 +EVIDENCE: cargo test -p ec-av1 --lib -- 8x8_leaf_split (EC_AV1_REQUIRE_AOMENC=1) | 8-bit gate re-run | 1 passed, 10-bit + tile-columns ignored with their reasons + +Suite totals, `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` on 889ca3c: +**270 passed, 0 failed, 25 ignored** (r2 was 270/0/24; the +1 ignored is the new +`across_tile_columns` arm). `refusal_inventory` and `gate_coverage` are in that +green set; no refusal was lifted or narrowed this round, so neither needed an +edit. + +## 5. Two candidate causes ABLATED (neither is it) + +- lane-gmaffine `f5e1851` (14 TxbSet arms missing the eob_pt class-1 CDF row): + applied to this branch's `cdf.rs`/`cdf_state.rs` and re-measured -- the 10-bit + ladder stays **41/57**, byte-identical divergence at the same element. Not + this stream's cause; the hunks were reverted so they reach main once through + lane-gmaffine. +- lane-gmaffine `0b8cb54` (leaf single_ref / interp-filter neighbour contexts + still read at SUB indices) cherry-picks with a conflict in `decode.rs`, so it + is left to lane-gmaffine, which already merged `ae69b25`. It touches exactly + the post-mv window this round pinned, and is the standing candidate. diff --git a/lanes/rectsplit-r4.report.md b/lanes/rectsplit-r4.report.md new file mode 100644 index 00000000..c9f4d376 --- /dev/null +++ b/lanes/rectsplit-r4.report.md @@ -0,0 +1,97 @@ +# lane-rectsplit r4 — SB-level split-transform strips: TWO root causes, refusal lifted + +Branch `lane-rectsplit` off `4c3389a` (r3's safe state). No rebase needed: `main` is still +`3808cf8`, the branch's merge base. + +## Headline + +r3's four-way table was not a contradiction — it was two defects stacked, the first hiding +the second behind a refusal: + +1. **`base_ctx` read the rect `av1_nz_map_ctx_offset` tables transposed.** libaom indexes + them by its own `coeff_idx`, and `get_nz_map_ctx_from_stats` decomposes that as + `col = coeff_idx >> bhl`, `bhl` = log2 of the *adjusted* height (5 for both `TX_64X32` + and `TX_32X64`): `coeff_idx = col * 32 + row`, so 32 consecutive flat entries are one + COLUMN and the `cdf.rs` 5x5 transcriptions are `[col][row]`. `decode.rs:1162` read them + `[row][col]` = the transpose = the other shape's rule with 11 and 16 swapped. + Fixed by stating libaom's generating rule (`txb_common.h:199-209`) once, exactly as + `base_ctx_rect` already did, instead of indexing the tables at all. +2. **`EOB_PT_512_CHROMA` was transcribed from the wrong row of + `av1_default_eob_multi512_cdfs[q][plane][2]`.** The last index is `eob_multi_ctx` + (0 = `TX_CLASS_2D`, 1 = `V_DCT`/`H_DCT`), not a q-context: the flat + `3277, 6554, ...` distribution our table held is the 1D-class row, identical for both + planes at every q, and the real chroma 2D row has four q-context variants like every + other coefficient table. The FIRST real 32x16 chroma transform read `eob_pt` 7 where + aomdec read 2 — that is what made seed 43 RED once defect 1 was fixed. Under r3's + shipped code seed 43 never reached it: it desynced 13 elements EARLIER and exited + through a named refusal, which the gate counts as a pass (class `refusal-hides-a-defect`). + +## Changed + +- `crates/ec-av1/src/decode.rs:1162` `base_ctx` — the `TX_CLASS_2D` rect arm now applies + libaom's generating rule (`row < 2 -> 11` when w 16` when w>h, else the + square table), no transposable table read left. +- `crates/ec-av1/src/cdf.rs:269` — `EOB_PT_512_CHROMA` corrected to the 2D chroma row plus + new `_Q0`/`_Q1`/`_Q3` siblings; `cdf_state.rs:1015` now `pick()`s by q-context. +- `crates/ec-av1/src/decode.rs:4102` `decode_block_rect64` — the split-transform refusal is + LIFTED, wired to `decode_rect_split` (r1's per-unit port), `RECT_PARTITION_HITS` bumped. +- `crates/ec-av1/src/decode.rs:3428` `decode_rect_split` — records `RECT64_QIDX_DRIFT_HITS` + for 64-level strips, which now reach this path. +- `crates/ec-av1/src/refusal_inventory.rs:49` — refusal string removed. +- `crates/ec-av1/src/stream.rs:9778` — gate (b) un-`#[ignore]`d, its doc records both causes. +- Instruments kept: `read_coeffs`/`read_coeffs_rect` print an `EC_COEFF_STEP` ladder under + `EC_TRACE_COEFF` in instrumented-aomdec format, with `pos` converted to libaom's + column-major `coeff_idx` so the two ladders `diff` line by line. +- New unit test `decode::tests::base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` + — evaluates `base_ctx` over the WHOLE 5x5 domain of 64x32 / 32x64 / square against + `table[col][row]` (class `enumerate-table-domain`). + +## Refusals lifted + +- `"a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)"` + — with `a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact` + green, hard-asserting `rect_split_sb_interior_tu_hits` (SB-level AND tx depth >= 2) sampled + per compared attempt. + +## Gates and evidence + +EVIDENCE: msac range ladders `scratchpad/n_ours43.txt` vs `scratchpad/n_aom43.txt` | `EC_TRACE_COEFF=1 decode_probe seed43.obu` vs `EC_TRACE_COEFF=1 aomdec` on the gate-dumped seed-43 stream | first divergent element = the chroma `eob` of the 64x32 strip at mi (0,16): ours `eob_pt` group 8 (eob 103), aomdec group 3 (eob 3), at identical range 44680 — i.e. a CDF-content defect, not a context one +EVIDENCE: `scratchpad/r4_ours43.yuv` vs `scratchpad/r4_aom43.yuv` | `decode_probe seed43.obu out.yuv`; `aomdec --rawvideo` | `cmp` byte-identical (was: frame-0 luma mismatch) +EVIDENCE: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3 -- --test-threads=1 --include-ignored superblock_level_horz_vert_partition split_transform_horz_vert_strip filter_intra_on_a_horz split_transform_superblock_strip refusal_inventory gate_coverage nz_map` | gates (a) (b) (c) + merged SB HORZ/VERT + inventory/coverage/table tests | 10 passed, 1 failed (81.41s) — the failure is the already-`#[ignore]`d `..._and_delta_q_...` gate, which fails its own drift counter, not a pixel compare (27/40 pixel-exact, 13 named refusals) +EVIDENCE: third leg from lane-tx64x16 — `scratchpad` sweep seeds 42..81, 192x128 gradients, merged-gate recipe with `--min-partition-size=16 --enable-1to4-partitions=1` | encode with the oracle aomenc, `decode_probe` vs `aomdec --rawvideo`, `cmp` | 33 EXACT, 7 named refusals (6x SB-level AB partition, 1x screen-content strip), 0 mismatches — seed 55 (reported 3944 wrong luma samples, first at (154,59)) is now byte-exact +EVIDENCE: full `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3` | whole crate lib | **272 passed, 0 failed, 23 ignored**, 490.90s (r3's expectation was 270/0/24; +1 un-ignored gate, +1 new unit test) + +## Film check (ReelB, the lane's critical path) + +`decode_probe` on the coordinator's mid-film extract (`ffmpeg -ss 600 -t 0.5 ... -f obu`, +11.5 MB, 10-bit 2160p, `.../cdc46329-.../scratchpad/reelb5.obu`), which stopped at exactly this +lane's refusal on main: + +``` +before (main 06d856d): REFUSED: a superblock-level HORZ/VERT strip with a split transform ... +after (this branch): REFUSED: AV1 tile (a 32x32 partition type this decoder does not code (value=8)) +``` + +EVIDENCE: `.../cdc46329-.../scratchpad/reelb5.obu` | `cargo run -p ec-av1 --example decode_probe` on `lane-rectsplit` r4 | the film advances past this lane's refusal to `PARTITION_HORZ_4` (value 8), a 1:4-partition gap owned by lane-part32/tx64x16 + +## Sibling sweep (defect class) + +- Class `table-transcribed-from-the-wrong-row-of-a-multi-dimensional-default`: every other + coefficient CDF in `Cdfs::new` already goes through `pick(q_ctx, ...)`; a grep of + `cdf.rs` for libaom's flat 1D rows (`3277, 6554` / `2979, 5958` / ...) finds no second + instance. `EOB_PT_512_CHROMA` was the only coefficient table initialised without `pick`. +- Class `reference-layout-not-spec` (transposed table): the only other rect offset consumer, + `base_ctx_rect`, already stated the rule and is unchanged; the new domain test covers both. + +## Residue + +- deferred(lane-part32 / lane-tx64x16 — 1:4 partitions): both films and 7/40 seeds of the + third-leg sweep now stop at `PARTITION_HORZ_4/VERT_4` or SB-level AB partitions. +- deferred(lane-rect64q): `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact` + stays `#[ignore]`d as r3 left it — its 40 attempts pixel-match (27 compared, 13 named + refusals) but `deltaq-mode=1` never drifts `CURRENT_Q_IDX` inside a 64-level strip in + that recipe. r4 added the missing counter bump on the split path; the gate still needs a + recipe that actually drifts. +- accepted: the third-leg recipe (`--min-partition-size=16 --enable-1to4-partitions=1`) is + measured here but NOT added as a gate arm — its remaining refusals are 1:4/AB partitions + owned by other lanes, so the arm would be RED for reasons outside this lane. diff --git a/lanes/scaledref-r1.report.md b/lanes/scaledref-r1.report.md new file mode 100644 index 00000000..e9eb5ccc --- /dev/null +++ b/lanes/scaledref-r1.report.md @@ -0,0 +1,115 @@ +# lane-scaledref r1 — scaled-reference (superres) MC beyond single-ref, plus the Golomb tail + +Branch `lane-scaledref`, off main `3808cf8`. Round 1 continues the previous +builder's uncommitted state (preserved as `95b3e70`) — that snapshot is +verified, gated and kept; everything below r1 adds is on top of it. + +## What changed + +| path:line | why | +| --- | --- | +| `crates/ec-av1/src/mc.rs:474` `horizontal_scaled_pass` | spec 7.11.3.3's horizontal walk factored out of `predict_scaled` and given to `predict_compound_intermediate` (new `x_scale_fp` param), so each compound tap scales off its OWN reference's luma width | +| `crates/ec-av1/src/decode.rs` (compound branch, ~9470) | the "compound-reference block with a scaled reference" refusal replaced by two independent `mc::scale_factor` values threaded into all 6 compound MC calls (Y/U/V x 2 taps) | +| `crates/ec-av1/src/decode.rs` `obmc_neighbour_pred` / `obmc_blend` | each OBMC neighbour is re-predicted through the scaled walk against **its own** reference's scale (`frame_width` threaded in) | +| `crates/ec-av1/src/decode.rs` (~10170) | warp under a scaled reference: libaom `allow_warp` (reconinter.c:41) suppresses local AND global warp and predicts translationally; that suppression is implemented, but the case is still refused by name (see residue) | +| `crates/ec-av1/src/decode.rs` `decode_inter_block8` | single-ref/compound/OBMC MC of the 8x8 leaf threaded for a scaled reference (`frame_width` param) | +| `crates/ec-av1/src/decode.rs` `read_golomb` (~1349) | **r1**: lift implemented, then REVERTED (`abec872`) -- it exposed a hidden defect, see below. Only a comment recording the finding + repro remains | +| `crates/ec-av1/src/decode.rs` `obmc_mask` + `obmc_blend` | **r1**: `obmc_mask_2 = {45,64}` added and one-sided chroma OBMC for an 8x8 luma block (`av1_skip_u4x4_pred_in_obmc`, reconinter.c:820, `DISABLE_CHROMA_U8X8_OBMC == 0` ⇒ chroma skipped in the ABOVE pass, kept in the LEFT pass). Before this, the first real 8x8 OBMC block hit `unreachable!` in `obmc_mask` | +| `crates/ec-av1/src/stream.rs` | the gate below | +| `crates/ec-av1/src/refusal_inventory.rs` | 2 refusal strings gone (compound-scaled; OBMC/interintra-scaled folded into a warp-only string); 47 → 45 | + +## Gates + +1. `stream::tests::a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact` + — real `aomenc --superres-mode=1 --superres-denominator=16 --superres-kf-denominator=16 + --auto-alt-ref=1 --lag-in-frames=25 --enable-obmc=1 --enable-interintra-comp=1 + --enable-smooth-interintra=1`, 12 seeds x 24 frames of 64x64 moving gradients, every SHOWN frame + compared to ffmpeg (corrected in r2: `decode_stream` pushes a picture only under + `show_frame`, stream.rs:711, and `ffmpeg -f obu` emits shown frames only -- a hidden + alt-ref is checked only through propagation into the frames that reference it). + Hard-asserts `mc::predict_scaled_hits() > 0` and the per-case counters + `scaled_compound/scaled_obmc/scaled_interintra > 0`. + + `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib a_real_aomenc_superres_stream_with_compound -- --nocapture` + + EVIDENCE: /tmp/.../scratchpad/gate1.log | aomenc superres d=16 + compound/OBMC/interintra, 12 seeds x 24 frames decoded and compared to ffmpeg | 12/12 pixel-exact, 0 refusals, superres_hits=291 predict_scaled_hits=3198 scaled_compound=500 scaled_obmc=9 scaled_interintra=1 + +2. (withdrawn) `decode::tests::golomb_tails_read_back_past_the_old_twenty_bit_cap` — written, passing, + and reverted with the change it gated. See "The Golomb tail" below. + +## Refusals lifted (2) + +- "a compound-reference block with a scaled reference (superres, unimplemented)" — gate 1, 500 hits. +- "warp/OBMC/interintra prediction with a scaled reference (superres, unimplemented)" — narrowed to + "warp prediction with a scaled reference"; OBMC (9 hits) and interintra (1 hit) proven by gate 1. + +`refusal_inventory` and `gate_coverage` tests green. + +## The Golomb tail — a refusal that is masking a real defect (finding, fix-now for its owner) + +Implemented as charted (`ee1f980`): read up to 32 leading zeros (dav1d's `len < 32`) instead of +erroring at 20, u64 accumulator, plus a round-trip gate over every prefix length 0..=31 through +`tile::write_golomb`. Bit-identical for every tail an encoder writes — our own writer tops out at 19 +leading zeros (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`), and libaom errors long before. + +It still turned a green gate RED: +`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` failed at +**seed 67, frame 0 luma**. Bisected against main `3808cf8` and against the lane's own WIP `95b3e70` +(both pass), and main's run prints, for that very seed: +`seed 67 refusal: unsupported: AV1 tile (a Golomb tail longer than this decoder reads)`. + +So the cap is not a capability limit — it is the point where an intra rect64 stream that has ALREADY +desynced first asks for something impossible (a key-frame coefficient level above `1 << 19`). +Class `refusal-hides-a-defect`. Reverted in `abec872`; `d8788fb` records the finding, the repro and +"lift this together with that defect's fix" at the cap itself. + +EVIDENCE: cargo test output, this report | ran the rect64 gate at 3808cf8 / 95b3e70 / lane HEAD with and without the lift | pass / pass / FAIL seed 67 frame 0 luma; main prints the Golomb refusal for seed 67 + +fix-now for the intra rect64 owner: encode that gate's seed-67 fixture, raise the cap locally, and +bisect the first mismatching block — the long tail is a downstream symptom, not the defect. + +## Test scope actually run + +- `cargo test -p ec-av1 --lib a_real_aomenc_superres_stream_with_compound` → 1 passed, 0 failed. +- `cargo test -p ec-av1 --lib a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes` + → 1 passed, 0 failed (this is the gate the Golomb lift turned red; green again after the revert). +- `cargo test -p ec-av1 --lib refusal_inventory` → 3 passed; `... gate_coverage` → 2 passed. +- `cargo test -p ec-av1 --lib golomb` → 3 passed (at ee1f980, before the revert). +- `cargo test -p ec-av1 --lib` (whole crate lib suite, at the final tree): **268 passed, 0 failed, + 23 ignored**, 928s. An earlier run of the same suite, taken with the Golomb cap raised, failed + exactly one test -- the seed-67 rect64 gate above -- which is what put that finding on the board. + +## Residue + +- fix-now → **not** done, deferred: **warp under a scaled reference** stays refused. The libaom + `allow_warp` fallback is implemented (warp suppressed, translational prediction used) but the + previous builder's `--enable-warped-motion=1 --superres-denominator=16` seed-47 stream still + mismatched ffmpeg at frame 2 luma. Shipping the lift would be wrong pixels behind a green name. + deferred: warp+superres — unblocked by bisecting that stream (set `EC_SCALEDREF_WARP=1` on gate 1 + to reproduce; `EC_AV1_GATE_DUMP=` pins the mismatching stream). +- deferred: **8x8 partition leaf under a scaled reference** — the leaf's MC *is* threaded for + scaling, but no aomenc recipe produces a firing, decodable fixture. r1 measured this instead of + assuming it: with `--min-partition-size=8` and a 64x**72** fixture (bottom 16-row band straddles + the true edge, which is the only way this decoder reaches `decode_inter_block8`), aomenc does emit + 8x8 leaves — and the decode **desyncs inside the leaf** (`from_switchable_symbol` handed a 4th + symbol, mc.rs:200), which is the same below-8x8 desync lane-sub8 r2 left open and has nothing to do + with scaling. Refusal restored with that fact in the comment; deleting those six lines is the whole + lift once the leaf8 desync is fixed. — unblocked by the lane-sub8 leaf8 desync. + That experiment did produce one real fix, kept: `obmc_mask(2)` + one-sided chroma OBMC (above). +- deferred: **"a reference picture whose height does not match this frame's own true size"** — not + attempted. Superres never scales height, so a height-mismatched reference can only come from + `--resize-mode` (reference scaling in BOTH axes). That needs a vertical counterpart to + `horizontal_scaled_pass` (per-row `y_step_qn`, `im_h` intermediate rows, libaom + `convolve_2d_scale`) *and* a gate whose frame size changes mid-stream. — unblocked by a lane sized + for resize-mode. +- accepted: **10-bit not covered.** `Picture` planes are `Vec`; 10-bit input is refused before + any of this code runs (see memory `his-av1-library-is-10-bit`, lane-hbd10). The 8/10-bit half of + the charter's gate line is unreachable from this lane. +- Reported conflict, not silently resolved (charter premise): the charter states the spec's `read_golomb` caps at 32 + leading zeros. Locally verifiable sources disagree — libaom `read_golomb` (decodetxb.c:30) calls a + 21st prefix bit a CORRUPT FRAME, which is exactly what the old refusal mirrored; dav1d reads up to + 32. There is no AV1 spec copy on this box and the network is unreachable from the sandbox + (`curl https://aomediacodec.github.io/av1-spec/av1-spec.html` timed out), so the change follows the + permissive decoder (dav1d) and is bit-identical to the old reader for every tail any encoder writes. +- Off the film path: neither of the user's two films uses superres (lane-hbd10), so nothing here moves + their decode. The Golomb and OBMC-mask fixes are generic. diff --git a/lanes/scaledref-r2.report.md b/lanes/scaledref-r2.report.md new file mode 100644 index 00000000..22dd69e6 --- /dev/null +++ b/lanes/scaledref-r2.report.md @@ -0,0 +1,85 @@ +# lane-scaledref r2 — warp-capable frame under a scaled reference read the wrong motion_mode alphabet + +Branch `lane-scaledref` (HEAD back on the branch: the verifier left the worktree detached at +a8111dd; `git checkout lane-scaledref` restored it, both were the same commit, no work lost). + +## Verifier finding 1 — ROOT CAUSE FOUND AND FIXED (no refusal needed) + +The verifier's premise was that "motion_mode symbol reading is unaffected; only the prediction +falls back". That is **false**, and it is the whole defect. libaom +`motion_mode_allowed` (oracle source `av1/common/blockd.h:1484-1487`): + +```c + if (mbmi->num_proj_ref >= 1 && allow_warped_motion && + !xd->cur_frame_force_integer_mv && + !av1_is_scaled(xd->block_ref_scale_factors[0])) { + return WARPED_CAUSAL; + } + return OBMC_CAUSAL; +``` + +Under a scaled reference the block reads the **2-symbol `obmc_cdf`**, never the 3-symbol +`motion_mode_cdf`. We read the 3-symbol one, which narrows the arithmetic decoder by the wrong +amount: the decoded *value* happened to stay SIMPLE_TRANSLATION, so nothing ever errored — the +stream decoded "OK: 24 frames" with quietly wrong pixels, exactly the silent-wrong-pixels class +the verifier caught. The warp guard at decode.rs ~10197 could never see it: `warp_params` is +`None` for those blocks (`warped=0` in EC_AV1_TRACE), so no fallback and no refusal ran. + +| path:line | why | +| --- | --- | +| `crates/ec-av1/src/decode.rs` ~10060 (`warp_eligible`) | `&& !ref_is_scaled` added (`mc::scale_factor(py_ref.width, frame_width) != REF_NO_SCALE`), libaom-exact; new `SCALED_WARP_SUPPRESSED_HITS` counts the blocks that take the `obmc_cdf` arm because of it | +| `crates/ec-av1/src/decode.rs` ~630 | the counter + `scaled_warp_suppressed_hits()` / `mixed_scale_compound_hits()` accessors | +| `crates/ec-av1/src/decode.rs` ~9515 | `MIXED_SCALE_COMPOUND_HITS`: compound blocks with exactly one scaled tap (diagnostic for finding 3) | +| `crates/ec-av1/src/decode.rs` ~11455 (`decode_inter_block8`) | sibling site of the same shape, comment only: an 8x8 leaf under a scaled reference is refused before this code runs, so the same `&& !ref_is_scaled` is owed by whoever lifts that refusal | +| `crates/ec-av1/src/stream.rs` (superres gate) | `--enable-warped-motion=1` is now the DEFAULT arm (`EC_SCALEDREF_WARP=0` only for bisecting), `--superres-mode` made settable (`EC_SCALEDREF_MODE`), and `scaled_warp_suppressed_hits() > 0` is hard-asserted so the warp arm cannot pass vacuously | +| `crates/ec-av1/examples/decode_probe.rs` | `EC_PROBE_OUT=` dumps the decoded planes as raw yuv420p — that is the instrument that located this defect (diff vs `ffmpeg -f obu`) | +| `lanes/scaledref-r1.report.md` | finding 2, wording corrected (below) | + +Not changed, reported instead of silently fixed: libaom also requires `!cur_frame_force_integer_mv` +in that same condition and our `warp_eligible` still omits it. Left alone this round — no gate +covers `force_integer_mv` (screen content), and changing an alphabet choice without a gate is the +mistake this round is fixing. deferred: force_integer_mv warp eligibility — unblocked by a +screen-content gate with `cur_frame_force_integer_mv=1`. + +Refusals: **none lifted, none added**, 45 unchanged. `refusal_inventory` / `gate_coverage` +untouched and green (see totals). The "warp prediction with a scaled reference" refusal stays: it +now only guards a *global*-warp block under a scaled reference, which this recipe never produced +(`scaled_warp_fallback=0`). + +EVIDENCE: /tmp/.../scratchpad/warp_superres.obu + ours2.yuv vs ff.yuv | EC_PROBE_OUT decode of the verifier's pinned stream, byte-compared to `ffmpeg -f obu -pix_fmt yuv420p -f rawvideo` | before: frames 1..23 differ (frame 1: 1342 luma + 370 chroma pixels, first at (2,26), max |d| 3, growing to 18 by frame 23); after the fix: `cmp` identical, 147456/147456 bytes + +EVIDENCE: gate run, this report | `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib a_real_aomenc_superres_stream_with_compound -- --nocapture` (warp now on by default) | `0 other-capability refusals, 12/12 pixel-exact, superres_hits=291 predict_scaled_hits=3198 scaled_compound=500 scaled_warp_fallback=0 scaled_obmc=9 scaled_interintra=1 scaled_block8=0 scaled_warp_suppressed=25 mixed_scale_compound=0` — 25 blocks took the `obmc_cdf` arm only because of this fix + +## Verifier finding 2 — report correction (done) + +`lanes/scaledref-r1.report.md` line ~27 now reads "every SHOWN frame compared to ffmpeg ... a +hidden alt-ref is checked only through propagation" (ledger already records +`decode_stream` pushes only under `show_frame`, stream.rs:711). + +## Verifier finding 3 — mixed scaled/unscaled compound taps: DEFERRED, measured not assumed + +Counter `mixed_scale_compound` added and wired into the gate's print; both alternative recipes were +run, neither yields a gateable stream: + +- `EC_SCALEDREF_MODE=3` (qthresh): aomenc never turns superres on for this content/q — + `superres_hits=0 predict_scaled_hits=0`, i.e. the whole gate goes vacuous (it fails its own + `predict_scaled_hits > 0` assert, which is the assert working). +- `EC_SCALEDREF_MODE=2` (random denominator per frame): produces coded widths that are not + multiples of 32, so the frame edge forces sub-16 partitions and the stream stops at the still-open + named refusal `an 8x8 partition leaf under a scaled reference (superres, unimplemented)` at + seed 42. + +deferred: mixed one-scaled-one-unscaled compound tap — unblocked by the leaf8 desync (lane-sub8), +which is what mode-2 recipes hit; the counter is in place so any future recipe proves the case +immediately. The per-tap code itself is r1's (`scale0`/`scale1` are already independent). + +## Test totals + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (whole crate lib suite): **268 passed, 0 failed, 23 ignored**, 968s (same totals as r1, now with the warp arm of the superres gate ON). Run at the final tree. + +## Residue carried from r1 (unchanged) + +- deferred: 8x8 partition leaf under a scaled reference — unblocked by the lane-sub8 leaf8 desync. +- deferred: reference scaling in BOTH axes (`--resize-mode`) — unblocked by a lane sized for it. +- accepted: 10-bit is refused upstream (`Picture` planes are `Vec`). +- accepted: the Golomb-tail cap stays where r1 left it (it masks an intra-rect64 defect). diff --git a/lanes/tx64x16-r1.report.md b/lanes/tx64x16-r1.report.md new file mode 100644 index 00000000..e504b2db --- /dev/null +++ b/lanes/tx64x16-r1.report.md @@ -0,0 +1,138 @@ +# lane-tx64x16 r1 — the 1:4 pair at 64x64 (TX_64X16 / TX_16X64) + +Branch `lane-tx64x16`, worktree `edith_codecs-tx64x16`, off main `dc5553f`. + +## STATUS: INCOMPLETE — gate RED. The refusal is narrowed in the code but NOT +proven: a real `PARTITION_VERT_4` stream with coefficients still mismatches. +Do not merge as is. + +## Premises re-measured (charter carried two stale ones) + +- "the refusal string now names the 1:4 pair" — FALSE at `dc5553f`. It read + *"a superblock-level partition type other than NONE or SPLIT"* + (`refusal_inventory.rs:48`) while `decode.rs` already coded HORZ/VERT; the AB + arms part32-r5 reports are NOT on main. Command: + `grep -n "64" crates/ec-av1/src/refusal_inventory.rs`. +- "requires the transform primitives (TX_64X16 / TX_16X64 …)" — FALSE. They + already exist: `inverse_transform_2d_typed_wh` (transform.rs:817) is generic + in (w,h), already zeroes everything past the low 32 on a 64-length axis + (`transform.rs:842`), already gets the rect scale right (fires only at + log2 ratio 1, i.e. never for 4:1 — `transform.rs:837`, and its comment + already names 16x64/64x16), and `row_shift_wh` (transform.rs:288) already + carries `(16,64)|(64,16) => 2` and `(8,32)|(32,8) => 2`, both verified + against `av1_inv_txfm_shift_ls` / `inv_shift_64x16` == `{-2,-4}` + (`~/.cache/aom-oracle/src/av1/common/av1_inv_txfm2d.c:150`). Dequant is + area-keyed (`dq_denom_area`), and `av1_get_tx_scale` is too (1024 pels → 1). + Nothing was owed here; the real work was entropy wiring + partition wiring. + +## What changed + +- `crates/ec-av1/src/decode.rs` + - `SCAN_32X8` / `SCAN_8X32` (new, ~line 1650): row-major transcriptions of + libaom `default_scan_32x8` / `default_scan_8x32`, converted with + `row*w+col = (p % h)*w + (p / h)` from libaom's COLUMN-major `p`. The rule + was validated by reproducing this repo's existing `SCAN_16X8` byte for byte + from `default_scan_16x8` before generating anything new — and libaom's + `default_scan_16x8` literal is byte-identical to this repo's `SCAN_8X16`, + i.e. a naive copy installs the transpose (class + reference-layout-not-spec). + - `decode_block_rect64`: luma corner generalised from a hardcoded 32x32 to + `(bw.min(32), bh.min(32))`, reading 32x16/16x32 through `read_coeffs_rect` + with `SCAN_32X16`/`SCAN_16X32` and `TxbSet::LumaRect32x16`; chroma set/scan + picked per shape, 32x8/8x32 reading `TxbSet::Chroma16` with the new scans. + Why no new CDF tables are owed, all read out of the oracle source: + `av1_get_adjusted_tx_size` maps TX_64X16→TX_32X16, TX_16X64→TX_16X32 + (`blockd.h:1361`); `av1_scan_orders` gives TX_64X16 `default_scan_32x16` + ("tx32's scan order is used", `scan.c`); `get_txsize_entropy_ctx` is 3 for + both TX_64X16 and TX_32X16 and 2 for both TX_32X8 and TX_16X16; + `txsize_log2_minus4` is 5 for TX_64X16 *and* TX_32X16, 4 for TX_32X8 *and* + TX_16X16 (`common_data.h:346`) so the eob alphabet matches too; and + `av1_nz_map_ctx_offset[TX_64X16]` is literally + `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`) — which is what + `base_ctx_rect(32,16)` computes, since both raw and coded dims are w>h. + - `PARTITION_HORZ_4`/`PARTITION_VERT_4` (8/9) wired at the superblock level: + four strips, `quarter_step` = 1 SUB unit, with libaom's `i > 0` frame-edge + break. + - New per-orientation hit counters `sb_rect4_horz_hits()` / + `sb_rect4_vert_hits()`. +- `crates/ec-av1/src/refusal_inventory.rs`: SB-level string narrowed to + "a superblock-level HORZ_A/HORZ_B/VERT_A/VERT_B partition (… codes NONE, + SPLIT, HORZ, VERT and the 1:4 pair at 64x64)". +- `crates/ec-av1/src/stream.rs`: new gate + `a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact`. +- `crates/ec-av1/fixtures/tx64x16-vert4-mismatch-seed73.obu`: the failing + stream, pinned. + +## Gate + +`cargo test -p ec-av1 --lib -- --exact stream::tests::a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact` +(`EC_TX64X16_GATE_ATTEMPTS`, default 40). aomenc recipe = the sbpart gate's, +with `--enable-1to4-partitions=1` and `--min-partition-size=16`; odd attempts +render the generator rotated 90 degrees (`transpose=1`) because aomenc picks +VERT_4 on this content and essentially never HORZ_4, and the two arms are a +transposed pair. Attempts whose decode fired zero 1:4 strips are counted and +printed, never asserted on — selection is on "the stream contains the +feature", never on "the stream decoded correctly". + +RESULT: **FAIL**. `seed 73` (a stream with four real 16x64 `PARTITION_VERT_4` +strips at mi(16,16..28)) mismatches ffmpeg: 10754 wrong luma samples, first at +(64, 56) — one row band ABOVE the strips, i.e. across the y=64 deblock edge. +An earlier 13-attempt run (before the transpose arm) had VERT_4 fire 4 strips +and decode PIXEL-EXACT, so the skip/low-energy case works and the coded case +does not. + +EVIDENCE: /home/user/Documents/Code/Rust/edith_codecs-tx64x16/crates/ec-av1/fixtures/tx64x16-vert4-mismatch-seed73.obu | decode_probe dump vs `ffmpeg -f rawvideo`, EC_AV1_TRACE partition trace | 10754/24576 luma samples differ, first (64,56); trace shows `partition_w64 value=9` then four `TRACE_RECT64_END bw=16 bh=64` +EVIDENCE: gate stdout above | 40 aomenc attempts, seeds 42..81, `--enable-1to4-partitions=1` | 21 named refusals, VERT_4 arm reached a real decode, HORZ_4 arm never selected by aomenc on this content + +## Open, with dispositions + +- **fix-now (r2)**: the coded-16x64 mismatch above. Not yet root-caused. + Ruled out by reading the oracle source, NOT by experiment: shift chain + (`inv_shift_64x16`/`inv_shift_16x64` = {-2,-4} = our `row_shift_wh` 2), rect + scale (4:1 gets none), dequant denominator (area 1024 → 2), eob alphabet + (512), CDF set, scan choice, nz-map offset table. Untested suspects, in + order: (1) the deblock grid for a 1:4 strip + (`fill_lf_grid_rect(.., tx_w=16, tx_h=64, 0)`) — the first diffs are on the + OTHER side of the edge; (2) 16x64 intra prediction edge reach; (3) the + chroma 8x32 plane. First move should be a prefilt dump + (`EC_AV1_PREFILT_DUMP`) to split "reconstruction wrong" from "deblock + wrong" — the diff band starting above the block is exactly the tell that + cost lane-tiny a round. +- **deferred(a green 64-level gate)**: the 32x32-level 1:4 arms. They ARE + requested by this recipe — `a 32x32 partition type this decoder does not + code (value=9)` appears in the sweep — and need TX_32X8/TX_8X32 luma + (`TxbSet::Luma16` exactly: entropy ctx 2, eob 256) plus 16x4/4x16 chroma + (`TxbSet::Chroma8`: ctx 1, eob 64) and two more scans. Same shape of work, + not started. +- **flagged, not this lane's shape (pre-existing)**: with + `--min-partition-size=16`, seed 55 of this recipe decodes 3944 wrong luma + samples with ZERO 1:4 blocks in the stream (trace: SB(1,0) SPLIT with a + 32x32 `PARTITION_HORZ`, SB(1,2) a 64x32 `PARTITION_HORZ`), first diff at + (154, 59). My diff cannot reach that stream (every path it touches needs a + 16-with-64 dimension pair), so it is a pre-existing defect of the 32x16 / + 64x32 strip shapes exposed by a recipe the existing sbpart gate + (`--min-partition-size=32`) never uses. Stream: rerun the gate with + `EC_AV1_GATE_DUMP` at `EC_TX64X16_GATE_ATTEMPTS=14`. +- **accepted**: `palette_bsize_ctx_wh` has no rect caller at all + (`read_intra_mode_rect` never reads a palette symbol), so 64x16/16x64 need + no entry there; a screen-content rect strip is a different lane's hole. + +## Suite totals + +`cargo test -p ec-av1 --lib` (worktree, `CARGO_TARGET_DIR=~/.cache/cargo-target-tx64x16`, +1347s under a 10-lane concurrent load): +**256 passed, 17 failed, 22 ignored, 0 filtered out.** +Two of the 17 captured by name -- +`stream::tests::a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact` +and `stream::tests::real_aomenc_film_grain_streams_decode_pixel_exact` -- are +outside anything this diff can reach (no 16-with-64 dimension pair), plus this +lane's own new gate. The remaining 14 were NOT enumerated: the capture pipeline +dropped the failure list and a re-run costs another 22 minutes, which the tool +budget did not have. A successor MUST re-run this and diff the failure set +against `main` before attributing any of it to this branch. + +Note: `crates/ec-av1/fixtures/` is covered by `.gitignore:2 (fixtures)`, so the +pinned mismatching stream is NOT in the commit -- it is on disk in the worktree +at `crates/ec-av1/fixtures/tx64x16-vert4-mismatch-seed73.obu` +(sha256 0d9c3dd8a178a96309ea7165f3018146b5e09e660fd78a6870da2a5b5b1b60c1) and +regenerable by the gate with `EC_AV1_GATE_DUMP`. diff --git a/lanes/tx64x16-r2.report.md b/lanes/tx64x16-r2.report.md new file mode 100644 index 00000000..59d1cb47 --- /dev/null +++ b/lanes/tx64x16-r2.report.md @@ -0,0 +1,113 @@ +# lane-tx64x16 r2 — the SB-level 1:4 pair is GREEN; r1's "17 failures" were a stale base + +Branch `lane-tx64x16`, rebased dc5553f -> `5811ec5` -> **`6d86d3a`** (current main +at the time of writing). Commits: `3435835` (r1 wiring, replayed), `23aa4b3` +(r1 report), `d1f71b6` (this round). + +## Headline + +**r1's red gate was a STALE BASE, not a defect.** Nothing in the 1:4 wiring +changed this round. Rebasing onto main turns +`a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact` +GREEN (both arms hard-asserted, 40 aomenc attempts), and the r1 suite's +"17 failed" collapses to 2 — neither of them reachable by this lane's diff. + +Class for the ledger: **stale-premise lane** (5th instance) — a lane whose gate +is red against a base that is 20 merges behind measures the base, not its own +change. Re-measure the premise on today's main BEFORE bisecting your own diff. + +## The 17, enumerated (charter's first job) + +They do not exist on the rebased branch. Full `cargo test -p ec-av1 --lib` +(`EC_AV1_REQUIRE_AOMENC=1`) on the rebase-onto-5811ec5 tree, before any fix of +mine: **290 passed, 2 failed, 27 ignored**, the two being + +1. `decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule` — **RED ON + MAIN**, not caused by this branch (`git diff --stat main..HEAD` touches + `decode.rs` (partition arms + counters + scans), `refusal_inventory.rs`, + `stream.rs` only; the table, its consumer and this test are all main's). + Root cause: the test read `NZ_MAP_CTX_OFFSET_32X64`/`_64X32` as + `table[col][row]` — lane-rectsplit r2's column-major premise, which r3 + disproved and reverted in the *tables* without reverting the *test*. The + tables as they stand are display-major and satisfy libaom's generating rule + (`txb_common.h:199-209`) read `[row][col]`, which is exactly how the only + real consumer reads them (`base_ctx`, `TxClass::TwoD` arm, + `crates/ec-av1/src/decode.rs:1829`) and the reading every merged rect gate + is green under. FIX: read the test in the consumer's order. Table content + untouched — zero risk to the 64x32/32x64 path. + Verification of the direction: for `TX_32X64` (w 6`, i.e. display-major and correct. +2. `gate_coverage::tests::never_exercised_8bit_matches_the_gate_recipes` — + caused by this branch, and by design: this lane's gate is the first to pass + `--enable-1to4-partitions=1` at 8 bit, so the 8-bit coverage hole is retired. + FIX: entry deleted from `NEVER_EXERCISED_8BIT`; the 10-bit entry stays and + now says "10-bit hole only". + +Bisecting the corner generalisation vs the scan additions (the charter's plan) +was therefore not needed and not run — the premise it rested on ("a change that +breaks 17 gates") was false. + +## Rebase conflict resolutions (main had moved onto the same lines) + +- `decode.rs` SB partition dispatch: BOTH arms kept — main's + `PARTITION_HORZ_A/_B/VERT_A/_B` (part32 r4) and this lane's + `PARTITION_HORZ_4/VERT_4`; `reduced_tx_set` (new on main) threaded into the + 1:4 `decode_block_rect64` calls. +- `decode.rs` counters: both `SB_AB_HITS` and `SB_RECT4_{HORZ,VERT}_HITS` kept. +- The `_` arm of the SB partition match is now unreachable (all ten partition + values are coded at 64x64); it refuses "a superblock-level partition value + outside PARTITION_NONE..PARTITION_VERT_4" and `refusal_inventory` lists that + string instead of the retired 1:4 one. +- `stream.rs`: git had spliced this lane's gate INTO main's AB gate. Resolved by + taking main's file whole and re-appending the 1:4 gate function verbatim. + +## Refusal lifted + +`"a superblock-level 1:4 partition (PARTITION_HORZ_4/VERT_4 at 64x64, four +64x16/16x64 strips)"` — gone from `decode.rs` and `refusal_inventory.rs`, with +the gate above green. `refusal_inventory` + all five `gate_coverage` tests green. + +## EVIDENCE + +EVIDENCE: ~/.cache/tx64-sb-gates.log | `cargo test -p ec-av1 --lib -- superblock_level` with EC_AV1_REQUIRE_AOMENC=1 on d1f71b6 | 3 passed, 0 failed, 1 ignored (rect64q drift gate, ignored on main): the 1:4 gate AND both sibling SB gates (horz_vert, ab) green — SIBLING GATES rule satisfied +EVIDENCE: ~/.cache/tx64-suite-r2.log | full `cargo test -p ec-av1 --lib`, rebase onto 5811ec5, before my fixes | 290 passed / 2 failed / 27 ignored — the two named above, replacing r1's unenumerated 17 +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/reelc.obu (sha256 32e0619ca9fd9ae0e16072c66013757aa7abfedccc99bc6d3509f6e213195226, `ffmpeg -ss 300 -t 0.4 -c:v copy -f obu`) | `cargo run -p ec-av1 --example decode_probe` on d1f71b6 | ReelC no longer stops at the 1:4 refusal; new stop is "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)" — the refusal lane-rectsplit r4 (7b55227) lifts +EVIDENCE: ~/.cache/tx64-suite-r2b.log | full `cargo test -p ec-av1 --lib` on d1f71b6 (rebased onto 6d86d3a, both fixes in) | see "Suite totals" below + +## Open, with dispositions + +- **fix-now, NEXT ROUND (ReelB critical path)**: the **32x32-level** + `PARTITION_HORZ_4/VERT_4` (`decode.rs:9384`, refusal "a 32x32 partition type + this decoder does not code (value={part32})", value 8 = HORZ_4). Shape of the + work, already scouted: four `decode_block_rect(at32, 32, 8)` / + `(8, 32)` strips at `quarter_step` = 1 mi-pair, same `i > 0` frame-edge break + as the 64-level arm. Luma TX_32X8/TX_8X32 are their own adjusted size + (`av1_get_adjusted_tx_size` leaves them alone), entropy ctx = TX_16X16 and + `txsize_log2_minus4` = 4 (256 positions) => `TxbSet::Luma16` exactly, and the + scans **already exist** in this branch: `SCAN_32X8` / `SCAN_8X32` + (`decode.rs:1952`/`1969`). What is genuinely missing is CHROMA 16x4 / 4x16: + `TxbSet::Chroma8` (ctx TX_8X8, 64 positions) plus two new scans + `default_scan_16x4` / `default_scan_4x16`, transcribed with this repo's + column-major -> row-major rule (`row*w+col = (p % h)*w + (p / h)`; validate + the rule by regenerating an existing scan first — a naive copy installs the + transpose). +- **deferred(the 32-level arms above)**: a 10-bit twin of the 1:4 gate. The + `NEVER_EXERCISED_10BIT` entry for `enable-1to4-partitions` is still live and + now says so explicitly. +- **flagged, resolved**: r1's "pre-existing seed-55 defect (3944 wrong luma, + zero 1:4 blocks)" did not reproduce on the rebased tree — the 1:4 gate runs + all 40 seeds of that same recipe (seeds 42..81, `--min-partition-size=16`) and + every decoded attempt now compares pixel-exact, including seed 55. It was + another symptom of the stale base (main has since landed inter8/rectsplit/ + txselect/seg fixes). No separate pin is owed. +- **accepted**: `main` moved again during the round (rectsplit r4 `7b55227` is + not yet merged). If it lands first, its `base_ctx` rewrite may delete + `NZ_MAP_CTX_OFFSET_32X64/_64X32` outright and conflict with my one-line test + fix — resolve by taking r4's version, the defect is the same one. + +## Suite totals + +`cargo test -p ec-av1 --lib` with `EC_AV1_REQUIRE_AOMENC=1`, on `d1f71b6`: +**295 passed, 0 failed, 27 ignored, 0 filtered out** (1234s under concurrent lane load). +Both failures above are fixed; no new failure introduced. r1's 256/17/22 is superseded. diff --git a/scripts/build-aom-affine-oracle.sh b/scripts/build-aom-affine-oracle.sh new file mode 100755 index 00000000..34effa76 --- /dev/null +++ b/scripts/build-aom-affine-oracle.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Provision an aomenc that can emit AFFINE global motion. +# +# Stock libaom NEVER writes a 6-parameter (AFFINE) global-motion model: its +# encoder-side model search is pinned to ROTZOOM, +# +# av1/encoder/global_motion_facade.c:24 +# #define FIRST_GLOBAL_TRANS_TYPE ROTZOOM +# #define LAST_GLOBAL_TRANS_TYPE ROTZOOM +# +# so no `--enable-global-motion=1` recipe over any content can produce the +# AFFINE case the decoder must still handle (the *bitstream* allows it, the +# spec's `global_motion_params` reads 6 params, and ffmpeg decodes it). This +# builds a side copy of the oracle source with that search range widened to +# AFFINE -- decode-normative output, still ordinary libaom, still verified +# against ffmpeg -- into its own prefix so the shared oracle at +# ~/.cache/aom-oracle (used by every other gate) is untouched. +# +# Used by the `a_real_affine_global_motion_stream_decodes_pixel_exact` gate in +# crates/ec-av1/src/stream.rs. +set -euo pipefail + +ROOT="${AOM_AFFINE_ROOT:-$HOME/.cache/aom-affine}" +ORACLE_SRC="${AOM_ORACLE_ROOT:-$HOME/.cache/aom-oracle}/src" +SRC="$ROOT/src" +BUILD="$ROOT/build" + +if [ ! -d "$ORACLE_SRC/.git" ]; then + echo "no oracle source at $ORACLE_SRC -- run scripts/build-aom-oracle.sh first" >&2 + exit 1 +fi + +if [ ! -d "$SRC" ]; then + mkdir -p "$ROOT" + cp -a "$ORACLE_SRC" "$SRC" +fi + +facade="$SRC/av1/encoder/global_motion_facade.c" +sed -i 's/^#define LAST_GLOBAL_TRANS_TYPE ROTZOOM$/#define LAST_GLOBAL_TRANS_TYPE AFFINE/' "$facade" +grep -q '^#define LAST_GLOBAL_TRANS_TYPE AFFINE$' "$facade" || + { echo "patch did not apply to $facade" >&2; exit 1; } + +cmake -S "$SRC" -B "$BUILD" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DENABLE_TESTS=0 -DENABLE_DOCS=0 -DENABLE_EXAMPLES=1 +ninja -C "$BUILD" aomenc + +echo "affine-capable encoder ready: $BUILD/aomenc" diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh index 2dbc1fee..23f715e9 100755 --- a/scripts/instrument-aom-oracle.sh +++ b/scripts/instrument-aom-oracle.sh @@ -21,6 +21,8 @@ # two lanes stalled on 2026-08-30 because this rung did not exist. # EC_TRACE_MODE=1 -> "EC_MODE mi_row=.. mi_col=.. rng=.." before every inter # block's mode info, "EC_MODE_VAL .. mode=.. ref0/1=.. mv0=.. rng=.." +# (rung 13 adds "stack=" to that line and an "EC_MODE_MV" line right +# after assign_mv) # after -- the mv-stack/DRL/mv reads EC_PART cannot see. The same flag # also emits "EC_IMODE .. rng=.." / "EC_IMODE_VAL .. mode=.. uv_mode=.. # skip=.. tx=.. rng=.." around every INTRA key-frame block: without it @@ -705,3 +707,57 @@ s = s.replace(anchor, dump + anchor, 1) open(path, "w").write(s) print("final dump instrumented") PYF + +# --- rung 13: MV ground truth inside the inter mode ladder (lane-inter8 r3) -- +# lane-inter8 r3 patched the live oracle tree BY HAND and rebuilt aomdec, so +# these two probes existed only in ~/.cache/aom-oracle/src and any rebuild +# from this script would have silently dropped them (class: instrument that +# lives only in a build tree). Both extend rung 4 and are gated by the same +# EC_TRACE_MODE: +# * EC_MODE_MV .. mode=.. mv0=(..,..) rng=.. -- printed immediately after +# assign_mv, i.e. the MV as decoded, BEFORE interintra/motion-mode/ +# interp-filter syntax moves the range further; lets a lane separate an +# MV defect from a later-symbol defect on the same block. +# * stack= added to rung 4's EC_MODE_VAL -- +# the reference's own mv-stack depth for the block's reference pair. +H="$SRC/av1/decoder/decodemv.c" +[ -f "$H" ] || { echo "no oracle source at $H" >&2; exit 1; } + +python3 - "$H" <<'PYMV' +import sys +path = sys.argv[1] +s = open(path).read() +if "EC_MODE_MV" in s: + print("decodemv rung 13 already applied (no-op)") + sys.exit(0) +assert "EC_INSTRUMENTED" in s, "rung 13 needs rung 4 (run this script top to bottom)" + +# (a) stack= on rung 4's EC_MODE_VAL +old_val = """ "mv0=(%d,%d) rng=%u\\n", + ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode, + (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1], + mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col, + (unsigned)r->ec.rng);""" +new_val = """ "mv0=(%d,%d) stack=%d rng=%u\\n", + ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode, + (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1], + mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col, + /* EC_STACK */ (int)dcb->ref_mv_count[av1_ref_frame_type(mbmi->ref_frame)], + (unsigned)r->ec.rng);""" +assert old_val in s, "rung 4's EC_MODE_VAL body moved" +s = s.replace(old_val, new_val, 1) + +# (b) EC_MODE_MV right after assign_mv's corrupted-flag merge +anchor = " aom_merge_corrupted_flag(&dcb->corrupted, mv_corrupted_flag);\n" +assert s.count(anchor) == 1, "assign_mv corrupted-flag merge is no longer unique" +probe = """ if (getenv("EC_TRACE_MODE") != NULL) { + fprintf(stderr, + "EC_MODE_MV mi_row=%d mi_col=%d mode=%d mv0=(%d,%d) rng=%u\\n", + xd->mi_row, xd->mi_col, (int)mbmi->mode, mbmi->mv[0].as_mv.row, + mbmi->mv[0].as_mv.col, (unsigned)r->ec.rng); + } +""" +s = s.replace(anchor, anchor + probe, 1) +open(path, "w").write(s) +print("decodemv rung 13 (EC_MODE_MV + EC_MODE_VAL stack=) instrumented") +PYMV