diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index f0ec78f7..a8d4d1f6 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -326,6 +326,31 @@ pub const FILTER_INTRA: [[u16; 3]; 4] = [ /// `FILTER_INTRA_MODES` a `use_filter_intra` block picks. pub const FILTER_INTRA_MODE: [u16; 6] = [8949, 12776, 17211, 29558, 32768, 0]; +/// `default_tx_size_cdf[0]` (entropymode.c): an 8x8 block's `tx_depth` flag +/// (`TX8` vs `TX4`), indexed by `tx_size_context` (0..=2). +pub const TX_SIZE_CAT0: [[u16; 3]; 3] = [[19968, 32768, 0], [19968, 32768, 0], [24320, 32768, 0]]; +/// `default_tx_size_cdf[1]` (entropymode.c): a 16x16 block's `tx_depth` +/// (`TX16`/`TX8`/`TX4`), indexed by `tx_size_context`. +pub const TX_SIZE_CAT1: [[u16; 4]; 3] = [ + [12272, 30172, 32768, 0], + [12272, 30172, 32768, 0], + [18677, 30848, 32768, 0], +]; +/// `default_tx_size_cdf[2]` (entropymode.c): a 32x32 block's `tx_depth` +/// (`TX32`/`TX16`/`TX8`), indexed by `tx_size_context`. +pub const TX_SIZE_CAT2: [[u16; 4]; 3] = [ + [12986, 15180, 32768, 0], + [12986, 15180, 32768, 0], + [24302, 25602, 32768, 0], +]; +/// `default_tx_size_cdf[3]` (entropymode.c): a 64x64 block's `tx_depth` +/// (`TX64`/`TX32`/`TX16`), indexed by `tx_size_context`. +pub const TX_SIZE_CAT3: [[u16; 4]; 3] = [ + [5782, 11475, 32768, 0], + [5782, 11475, 32768, 0], + [16803, 22759, 32768, 0], +]; + /// `Default_Cfl_Alpha_Cdf` (spec 9.4): a `UV_CFL_PRED` block's per-plane /// alpha magnitude (spec 5.11.45's `cfl_alpha_u`/`cfl_alpha_v`), indexed by /// the joint sign's context (`CFL_CONTEXT_U`/`CFL_CONTEXT_V`, @@ -3733,3 +3758,153 @@ pub const INTRA_TX_TYPE_SET1_8: [[u16; 8]; 13] = [ /// at the flat 5-way default (unlike its trained `TX_16X16` neighbour, /// [`INTRA_TX_TYPE_SET2_16`]) -- every mode reads the same uniform CDF. pub const INTRA_TX_TYPE_SET2_8: [[u16; 6]; 13] = [[6554, 13107, 19661, 26214, 32768, 0]; 13]; +/// The full luma sub-range of spec `TXB_SKIP_CONTEXTS` (contexts 0..6, the +/// `plane_bsize != tx_size` `skip_contexts[top][left]` table plus its own +/// single `plane_bsize == tx_size` context 0), for a `TxMode::Select` block +/// whose luma transform is split into several transform units smaller than +/// the block itself -- the single-context `TXB_SKIP_LUMA_*` constants above +/// stay for every other caller, which only ever reads context 0. +pub const TXB_SKIP_LUMA_8_Q0_CTX: [[u16; 3]; 7] = [ + [31548, 32768, 0], + [1549, 32768, 0], + [10130, 32768, 0], + [16656, 32768, 0], + [18591, 32768, 0], + [26308, 32768, 0], + [32537, 32768, 0], +]; +pub const TXB_SKIP_LUMA_8_Q1_CTX: [[u16; 3]; 7] = [ + [31782, 32768, 0], + [1836, 32768, 0], + [10689, 32768, 0], + [17604, 32768, 0], + [21622, 32768, 0], + [27518, 32768, 0], + [32399, 32768, 0], +]; +pub const TXB_SKIP_LUMA_8_CTX: [[u16; 3]; 7] = [ + [31957, 32768, 0], + [3230, 32768, 0], + [11153, 32768, 0], + [18123, 32768, 0], + [20143, 32768, 0], + [26536, 32768, 0], + [31986, 32768, 0], +]; +pub const TXB_SKIP_LUMA_8_Q3_CTX: [[u16; 3]; 7] = [ + [31903, 32768, 0], + [2044, 32768, 0], + [7528, 32768, 0], + [14618, 32768, 0], + [16182, 32768, 0], + [24168, 32768, 0], + [31037, 32768, 0], +]; +pub const TXB_SKIP_LUMA_16_Q0_CTX: [[u16; 3]; 7] = [ + [29957, 32768, 0], + [5391, 32768, 0], + [18039, 32768, 0], + [23566, 32768, 0], + [22431, 32768, 0], + [25822, 32768, 0], + [32197, 32768, 0], +]; +pub const TXB_SKIP_LUMA_16_Q1_CTX: [[u16; 3]; 7] = [ + [31901, 32768, 0], + [10311, 32768, 0], + [18047, 32768, 0], + [24806, 32768, 0], + [23288, 32768, 0], + [27914, 32768, 0], + [32296, 32768, 0], +]; +pub const TXB_SKIP_LUMA_16_CTX: [[u16; 3]; 7] = [ + [32363, 32768, 0], + [10692, 32768, 0], + [19090, 32768, 0], + [24357, 32768, 0], + [24442, 32768, 0], + [28312, 32768, 0], + [32169, 32768, 0], +]; +pub const TXB_SKIP_LUMA_16_Q3_CTX: [[u16; 3]; 7] = [ + [32510, 32768, 0], + [8430, 32768, 0], + [17318, 32768, 0], + [24154, 32768, 0], + [23674, 32768, 0], + [28789, 32768, 0], + [32139, 32768, 0], +]; +pub const TXB_SKIP_LUMA_32_Q0_CTX: [[u16; 3]; 7] = [ + [17920, 32768, 0], + [1818, 32768, 0], + [7282, 32768, 0], + [25273, 32768, 0], + [10923, 32768, 0], + [31554, 32768, 0], + [32624, 32768, 0], +]; +pub const TXB_SKIP_LUMA_32_Q1_CTX: [[u16; 3]; 7] = [ + [26726, 32768, 0], + [1045, 32768, 0], + [11703, 32768, 0], + [20590, 32768, 0], + [18554, 32768, 0], + [25970, 32768, 0], + [31938, 32768, 0], +]; +pub const TXB_SKIP_LUMA_32_CTX: [[u16; 3]; 7] = [ + [30669, 32768, 0], + [3832, 32768, 0], + [11663, 32768, 0], + [18889, 32768, 0], + [19782, 32768, 0], + [23313, 32768, 0], + [31330, 32768, 0], +]; +pub const TXB_SKIP_LUMA_32_Q3_CTX: [[u16; 3]; 7] = [ + [31671, 32768, 0], + [2056, 32768, 0], + [11746, 32768, 0], + [16852, 32768, 0], + [18635, 32768, 0], + [24715, 32768, 0], + [31484, 32768, 0], +]; +pub const TXB_SKIP_LUMA_64_Q0_CTX: [[u16; 3]; 7] = [ + [6308, 32768, 0], + [117, 32768, 0], + [1638, 32768, 0], + [2161, 32768, 0], + [16384, 32768, 0], + [10923, 32768, 0], + [30247, 32768, 0], +]; +pub const TXB_SKIP_LUMA_64_Q1_CTX: [[u16; 3]; 7] = [ + [26584, 32768, 0], + [188, 32768, 0], + [8847, 32768, 0], + [24519, 32768, 0], + [22938, 32768, 0], + [30583, 32768, 0], + [32608, 32768, 0], +]; +pub const TXB_SKIP_LUMA_64_CTX: [[u16; 3]; 7] = [ + [28573, 32768, 0], + [3183, 32768, 0], + [17802, 32768, 0], + [25977, 32768, 0], + [26677, 32768, 0], + [27832, 32768, 0], + [32387, 32768, 0], +]; +pub const TXB_SKIP_LUMA_64_Q3_CTX: [[u16; 3]; 7] = [ + [31539, 32768, 0], + [8433, 32768, 0], + [20576, 32768, 0], + [27904, 32768, 0], + [27852, 32768, 0], + [30026, 32768, 0], + [32441, 32768, 0], +]; diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 8ed2ac40..9d4f5b61 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -41,6 +41,10 @@ pub(crate) enum TxbSet { /// block (lane-av1-rect). An `is_inter` leaf reads /// [`Luma8Inter`](TxbSet::Luma8Inter) instead. Luma8, + /// [`Luma8`](TxbSet::Luma8)'s `reduced_tx_set: false` counterpart (round + /// 8): the same coefficient tables, but the seven-symbol `TX_SET_INTRA_1` + /// `tx_type` table rather than `Luma8`'s five-symbol reduced one. + Luma8Set1, /// The 8x8 luma transform of an `is_inter` 8x8 leaf under a straddling /// 16x16 block (lane-av1inter8): the same coefficient tables /// [`Luma8`](TxbSet::Luma8) reads, but `get_tx_set` (spec 5.11.48) @@ -116,10 +120,14 @@ pub(crate) struct Cdfs { pub cfl_alpha: [[u16; 17]; 6], /// The angle a directional mode is nudged by. pub angle_delta: [[u16; 8]; 8], - /// The one-context all-zero flag of a 16x16 luma transform. - pub txb_skip_luma_16: [[u16; 3]; 1], - /// The one-context all-zero flag of an 8x8 luma transform. - pub txb_skip_luma_8: [[u16; 3]; 1], + /// The all-zero flag of a 16x16 luma transform, 7 contexts (index 0 for + /// a lone TU whose own bsize equals the block's; 1..6 the + /// `skip_contexts[top][left]` table when `TxMode::Select` splits the + /// block's luma into several smaller transform units, spec + /// `get_txb_ctx_general`). + pub txb_skip_luma_16: [[u16; 3]; 7], + /// The same, for an 8x8 luma transform. + pub txb_skip_luma_8: [[u16; 3]; 7], /// The all-zero flag of an 8x8 chroma transform. pub txb_skip_chroma_8: [[u16; 3]; 3], /// The all-zero flag of a 4x4 chroma transform. @@ -170,10 +178,10 @@ pub(crate) struct Cdfs { /// `PARTITION_NONE` is ever coded against it, but the alphabet still /// adapts on every read, same as every other partition table. pub partition_w8: [[u16; 5]; 4], - /// The one-context all-zero flag of a 32x32 luma transform. - pub txb_skip_luma_32: [[u16; 3]; 1], + /// The same as `txb_skip_luma_16`'s 7 contexts, for a 32x32 luma transform. + pub txb_skip_luma_32: [[u16; 3]; 7], /// The same, for a 64x64 luma transform. - pub txb_skip_luma_64: [[u16; 3]; 1], + pub txb_skip_luma_64: [[u16; 3]; 7], /// The all-zero flag of a 16x16 chroma transform. pub txb_skip_chroma_16: [[u16; 3]; 3], /// The all-zero flag of a 32x32 chroma transform. @@ -221,6 +229,13 @@ pub(crate) struct Cdfs { pub intra_tx_type_16: [[u16; 6]; 13], /// The transform type of an 8x8 intra luma transform, by luma mode. pub intra_tx_type_8: [[u16; 6]; 13], + /// The transform type of an 8x8 intra luma transform, by luma mode, when + /// `reduced_tx_set` is false (spec `TX_SET_INTRA_1`, seven types) -- + /// [`Self::intra_tx_type_8`]'s five-type table is only the + /// `reduced_tx_set` row (round 8: a real `aomenc` stream with + /// `reduced_tx_set` off desyncs an 8x8 TU read against this row's + /// wrong-length CDF). + pub intra_tx_type_8_set1: [[u16; 8]; 13], /// The transform type of an `is_inter` 32x32 luma transform (spec /// `TX_SET_INTER_3`, `TX_32X32` row) -- unlike the intra 16x16 table, it /// is not indexed by mode. @@ -260,6 +275,15 @@ pub(crate) struct Cdfs { pub filter_intra: [[u16; 3]; 4], /// Which `FILTER_INTRA_MODES` entry a `use_filter_intra` block picks. pub filter_intra_mode: [u16; 6], + /// `TxMode::Select`'s `tx_depth` flag at an 8x8 block, by `tx_size_context` + /// (0..=2) -- see [`cdf::TX_SIZE_CAT0`]. + pub tx_size_cat0: [[u16; 3]; 3], + /// `tx_depth` at a 16x16 block -- see [`cdf::TX_SIZE_CAT1`]. + pub tx_size_cat1: [[u16; 4]; 3], + /// `tx_depth` at a 32x32 block -- see [`cdf::TX_SIZE_CAT2`]. + pub tx_size_cat2: [[u16; 4]; 3], + /// `tx_depth` at a 64x64 block -- see [`cdf::TX_SIZE_CAT3`]. + pub tx_size_cat3: [[u16; 4]; 3], } /// One motion vector component's adapting state (spec 9.4's `Default_Mv_*`, @@ -417,6 +441,7 @@ impl Cdfs { reset2(&mut self.dc_sign_luma); reset2(&mut self.intra_tx_type_16); reset2(&mut self.intra_tx_type_8); + reset2(&mut self.intra_tx_type_8_set1); reset1(&mut self.inter_tx_type_32); reset1(&mut self.inter_tx_type_16); reset1(&mut self.inter_tx_type_8); @@ -434,6 +459,10 @@ impl Cdfs { .for_each(MvComponentCdfs::reset_counts); reset2(&mut self.filter_intra); reset1(&mut self.filter_intra_mode); + reset2(&mut self.tx_size_cat0); + reset2(&mut self.tx_size_cat1); + reset2(&mut self.tx_size_cat2); + reset2(&mut self.tx_size_cat3); } /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and @@ -451,20 +480,20 @@ impl Cdfs { cfl_sign: cdf::CFL_SIGN, cfl_alpha: cdf::CFL_ALPHA, angle_delta: cdf::ANGLE_DELTA, - txb_skip_luma_16: [pick( - q_ctx, - cdf::TXB_SKIP_LUMA_16_Q0, - cdf::TXB_SKIP_LUMA_16_Q1, - cdf::TXB_SKIP_LUMA_16, - cdf::TXB_SKIP_LUMA_16_Q3, - )], - txb_skip_luma_8: [pick( - q_ctx, - cdf::TXB_SKIP_LUMA_8_Q0, - cdf::TXB_SKIP_LUMA_8_Q1, - cdf::TXB_SKIP_LUMA_8, - cdf::TXB_SKIP_LUMA_8_Q3, - )], + txb_skip_luma_16: pick( + q_ctx, + cdf::TXB_SKIP_LUMA_16_Q0_CTX, + cdf::TXB_SKIP_LUMA_16_Q1_CTX, + cdf::TXB_SKIP_LUMA_16_CTX, + cdf::TXB_SKIP_LUMA_16_Q3_CTX, + ), + txb_skip_luma_8: pick( + q_ctx, + cdf::TXB_SKIP_LUMA_8_Q0_CTX, + cdf::TXB_SKIP_LUMA_8_Q1_CTX, + cdf::TXB_SKIP_LUMA_8_CTX, + cdf::TXB_SKIP_LUMA_8_Q3_CTX, + ), txb_skip_chroma_8: pick( q_ctx, cdf::TXB_SKIP_CHROMA_8_Q0, @@ -621,20 +650,20 @@ impl Cdfs { ), partition_w16: cdf::PARTITION_W16, partition_w8: cdf::PARTITION_W8, - txb_skip_luma_32: [pick( - q_ctx, - cdf::TXB_SKIP_LUMA_32_Q0, - cdf::TXB_SKIP_LUMA_32_Q1, - cdf::TXB_SKIP_LUMA_32, - cdf::TXB_SKIP_LUMA_32_Q3, - )], - txb_skip_luma_64: [pick( - q_ctx, - cdf::TXB_SKIP_LUMA_64_Q0, - cdf::TXB_SKIP_LUMA_64_Q1, - cdf::TXB_SKIP_LUMA_64, - cdf::TXB_SKIP_LUMA_64_Q3, - )], + txb_skip_luma_32: pick( + q_ctx, + cdf::TXB_SKIP_LUMA_32_Q0_CTX, + cdf::TXB_SKIP_LUMA_32_Q1_CTX, + cdf::TXB_SKIP_LUMA_32_CTX, + cdf::TXB_SKIP_LUMA_32_Q3_CTX, + ), + txb_skip_luma_64: pick( + q_ctx, + cdf::TXB_SKIP_LUMA_64_Q0_CTX, + cdf::TXB_SKIP_LUMA_64_Q1_CTX, + cdf::TXB_SKIP_LUMA_64_CTX, + cdf::TXB_SKIP_LUMA_64_Q3_CTX, + ), txb_skip_chroma_16: pick( q_ctx, cdf::TXB_SKIP_CHROMA_16_Q0, @@ -778,6 +807,7 @@ impl Cdfs { dc_sign_luma: cdf::DC_SIGN_LUMA, intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16, intra_tx_type_8: cdf::INTRA_TX_TYPE_SET2_8, + intra_tx_type_8_set1: cdf::INTRA_TX_TYPE_SET1_8, inter_tx_type_32: cdf::INTER_TX_TYPE_SET3_32, inter_tx_type_16: cdf::INTER_TX_TYPE_SET3_16, inter_tx_type_8: cdf::INTER_TX_TYPE_SET3_8, @@ -793,6 +823,10 @@ impl Cdfs { mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()], filter_intra: cdf::FILTER_INTRA, filter_intra_mode: cdf::FILTER_INTRA_MODE, + tx_size_cat0: cdf::TX_SIZE_CAT0, + tx_size_cat1: cdf::TX_SIZE_CAT1, + tx_size_cat2: cdf::TX_SIZE_CAT2, + tx_size_cat3: cdf::TX_SIZE_CAT3, } } @@ -865,6 +899,17 @@ impl Cdfs { dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.intra_tx_type_8[mode].as_mut_slice()), }, + TxbSet::Luma8Set1 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_64_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_8_set1[mode].as_mut_slice()), + }, TxbSet::Luma8Inter => TxbTables { side: 8, txb_skip: &mut self.txb_skip_luma_8, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 69d192ae..de893e05 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -61,6 +61,19 @@ static DEBLOCK_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicU pub(crate) fn deblock_hits() -> usize { DEBLOCK_HITS.load(std::sync::atomic::Ordering::Relaxed) } + +/// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than +/// the block's own side, across every call in the process -- the same +/// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream +/// actually exercised a *split* transform under `TxMode::Select` rather than +/// every block coincidentally resolving `depth=0` (indistinguishable from +/// `TxMode::Largest` pixel-wise). +static TX_DEPTH_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`TX_DEPTH_HITS`]. +pub(crate) fn tx_depth_hits() -> usize { + TX_DEPTH_HITS.load(std::sync::atomic::Ordering::Relaxed) +} const SUB_MI: u32 = 4; const MI: usize = 4; const SB: usize = 64; @@ -275,13 +288,20 @@ fn read_coeffs( } let mut tx_type = TxType::DctDct; if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { + // The CDF row's own width names its set: 7 symbols (8 slots) is + // `TX_SET_INTRA_1`, 5 (6 slots) the reduced `TX_SET_INTRA_2` (the + // inter sets we read share set 2's symbol order). + let set1 = tx_type_cdf.len() == 8; let t = dec.symbol(tx_type_cdf); if trace { - eprintln!("TRACE tx_type value={t}"); + eprintln!("TRACE tx_type value={t} set1={set1}"); + } + tx_type = if set1 { + TxType::from_symbol_set1(t) + } else { + TxType::from_symbol(t) } - tx_type = TxType::from_symbol(t).ok_or_else(|| { - unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")) - })?; + .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; } let eob = read_eob(dec, coding); @@ -368,17 +388,37 @@ fn read_coeffs( /// [`crate::tile`]'s own private `Neighbour`. #[derive(Clone, Copy, Default)] struct Neighbour { - coded: bool, + /// The transform unit's cumulative coefficient level (spec `cul_level`, + /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's + /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not" + /// boolean (`level != 0`) is enough for every context this decoder read + /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller + /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`) + /// needs the actual magnitude tier of its above/left neighbours, not + /// just whether they coded anything. + level: u8, dc: Option, } fn neighbour_state(grid: &[i32]) -> Neighbour { + let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum(); Neighbour { - coded: grid.iter().any(|&l| l != 0), + level: cul.min(7) as u8, dc: (grid[0] != 0).then_some(grid[0] < 0), } } +/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0, +/// transform unit smaller than the block it sits in): `top`/`left` are the +/// above/left neighbours' magnitude tiers, each already clamped to 4. +const SKIP_CONTEXTS: [[usize; 5]; 5] = [ + [1, 2, 2, 2, 3], + [2, 4, 4, 4, 5], + [2, 4, 4, 4, 5], + [2, 4, 4, 4, 5], + [3, 5, 5, 5, 6], +]; + /// The neighbour state a block's contexts are read from — a duplicate of /// [`crate::tile`]'s own private `Neighbours` (that module is another lane's /// territory this round), kept at the same two granularities the real writer @@ -588,14 +628,37 @@ impl Neighbours { for cell in 0..side_mi { let above = &self.above[mi_c + cell][plane]; let left = &self.left[mi_r + cell][plane]; - above_coded |= above.coded; - left_coded |= left.coded; + above_coded |= above.level != 0; + left_coded |= left.level != 0; vote += dc_vote(above.dc) + dc_vote(left.dc); } (above_coded, left_coded, vote) }) } + /// The luma `txb_skip_ctx` of a transform unit smaller than its own block + /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the + /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own + /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike + /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real + /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx` + /// is always 0, spec's `plane_bsize == tx_size` branch). + fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize { + let mut top = 0u8; + let mut left = 0u8; + for cell in 0..side_mi { + top |= self.above[mi_c + cell][0].level; + left |= self.left[mi_r + cell][0].level; + } + let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)]; + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}" + ); + } + ctx + } + /// Writes one coded block into every cell it covers, on both grids: the /// mode/side arrays up to `side`'s own width, and the coefficient-context /// arrays up to the true frame edge — the units past it are left at their @@ -658,6 +721,69 @@ impl Neighbours { }); } } + + /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit + /// inside a coded block whose luma transform is smaller than its own + /// side (`TxMode::Select`): the real per-transform-unit coefficient + /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the + /// coarse per-block `tx_grid`/`fill_lf_grid` state + /// [`Self::record_split_luma`] still writes once for the whole block. + /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone -- + /// the caller's own [`Self::record_split_luma`] call sets those once, + /// at the block's own true side, not this TU's. + fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) { + let state = neighbour_state(grid); + let side_mi = tx_px / MI; + for cell in 0..side_mi { + if mi_r + cell < self.mi_rows { + self.left[mi_r + cell][0] = state; + } + if mi_c + cell < self.mi_cols { + self.above[mi_c + cell][0] = state; + } + } + } + + /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a + /// block whose luma was decoded as several transform units through + /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single + /// whole-block luma write -- everything [`Self::record`] does except + /// plane 0, which is already correct per-TU by the time this runs. + fn record_split_luma( + &mut self, + at: (usize, usize), + side: usize, + mode: usize, + chroma_grids: [&[i32]; 2], + ) { + let (r, c) = at; + for cell in 0..side / SUB { + self.above_mode[c + cell] = mode; + self.left_mode[r + cell] = mode; + self.above_side[c + cell] = side; + self.left_side[r + cell] = side; + } + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + let side_mi = side / MI; + for cell in 0..side_mi { + self.left_side_mi[mi_r + cell] = side; + self.above_side_mi[mi_c + cell] = side; + } + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); + for (plane_idx, grid) in chroma_grids.into_iter().enumerate() { + let plane = plane_idx + 1; + let state = neighbour_state(grid); + for cell in 0..side_mi { + if cell < side_mi.min(bound_h.saturating_sub(mi_r)) { + self.left[mi_r + cell][plane] = state; + } + if cell < side_mi.min(bound_w.saturating_sub(mi_c)) { + self.above[mi_c + cell][plane] = state; + } + } + } + } } /// Reads one coded block's skip flag, luma mode, angle delta (if the mode @@ -956,9 +1082,16 @@ fn read_plane( base_q_idx: u8, cfl: Option<(i32, &[i32])>, filter_intra: Option, + // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is + // smaller than its own block (spec `get_txb_ctx_general`'s + // `plane_bsize != tx_size` branch), carrying the already-looked-up + // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any + // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours + // formula below. + luma_skip_ctx: Option, ) -> Result> { let skip_ctx = if plane_idx == 0 { - 0 + luma_skip_ctx.unwrap_or(0) } else { usize::from(around.0) + usize::from(around.1) }; @@ -1035,6 +1168,11 @@ fn decode_block( v: &mut PlaneBuf, base_q_idx: u8, enable_filter_intra: bool, + scan32: &[u16], + scan16: &[u16], + scan8: &[u16], + tx_select: bool, + reduced_tx_set: bool, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -1047,8 +1185,31 @@ fn decode_block( side, enable_filter_intra, )?; + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra + // block, skipped or not. `logical_tx` is what the loop filter's edge + // lookup and the next block's own `tx_size_context` want (the *nominal* + // transform size -- 64 even for the 64x64 corner-scanned case, spec + // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side, + // which only differs from it at that one corner case. + let (logical_tx, coeff_tx_side) = if tx_select { + let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side); + if resolved == 4 { + return Err(unsupported( + "a resolved 4x4 luma transform (TxMode::Select depth exhausted; this decoder has no 4x4 luma coefficient tables)", + )); + } + (resolved, if resolved == 64 { 32 } else { resolved }) + } else { + (side, luma_tx) + }; + let luma_set = if tx_select { + txbset_for(logical_tx, reduced_tx_set) + } else { + luma_set + }; + let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8); let reach = Reach::of(side, px, py, y.width, y.height); - let (luma_grid, u_grid, v_grid); let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; if skip { @@ -1085,16 +1246,20 @@ fn decode_block( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, ); - luma_grid = vec![0i32; side * side]; - u_grid = vec![0i32; chroma_side * chroma_side]; - v_grid = vec![0i32; chroma_side * chroma_side]; - } else { + let luma_grid = vec![0i32; side * side]; + let u_grid = vec![0i32; chroma_side * chroma_side]; + let v_grid = vec![0i32; chroma_side * chroma_side]; + neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]); + } else if !tx_select || logical_tx == side { + // A single luma transform unit -- the old path, unchanged (including + // the 64x64 corner case, `logical_tx == side == 64` with + // `coeff_tx_side == 32`). let around = neighbours.around(at, side); - luma_grid = read_plane( + let luma_grid = read_plane( dec, cdfs, luma_set, - scans.0, + luma_scan, 0, around[0], mode, @@ -1104,13 +1269,14 @@ fn decode_block( px, py, side, - luma_tx, + coeff_tx_side, base_q_idx, None, filter_intra, + None, )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); - u_grid = read_plane( + let u_grid = read_plane( dec, cdfs, chroma_set, @@ -1128,8 +1294,9 @@ fn decode_block( base_q_idx, alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + None, )?; - v_grid = read_plane( + let v_grid = read_plane( dec, cdfs, chroma_set, @@ -1147,14 +1314,104 @@ fn decode_block( base_q_idx, alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + None, )?; + neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]); + } else { + // Several luma transform units, raster order (spec + // `transform_block`'s loop): the block's resolved transform is + // genuinely smaller than its own side, so each tile of it predicts + // and codes independently, its own context read fresh off whatever + // the earlier tiles in this same block already wrote -- the same + // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf. + let n_axis = side / logical_tx; + for tu_row in 0..n_axis { + for tu_col in 0..n_axis { + let tu_mi = ( + mi_r + tu_row * (logical_tx / MI), + mi_c + tu_col * (logical_tx / MI), + ); + let tu_px = px + tu_col * logical_tx; + let tu_py = py + tu_row * logical_tx; + let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; + let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height); + // This transform unit's own bsize (`logical_tx`) is smaller + // than the block it sits in (`side`), so `txb_skip_ctx` is + // the neighbour-magnitude table, not the lone-TU 0 (spec + // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch). + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI); + let tu_grid = read_plane( + dec, + cdfs, + luma_set, + luma_scan, + 0, + tu_around, + mode, + mode, + tu_reach, + y, + tu_px, + tu_py, + logical_tx, + logical_tx, + base_q_idx, + None, + filter_intra, + Some(tu_skip_ctx), + )?; + neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid); + } + } + let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); + let chroma_around = neighbours.around(at, side); + let u_grid = read_plane( + dec, + cdfs, + chroma_set, + scans.1, + 1, + chroma_around[1], + mode, + DC_PRED, + Reach::none(), + u, + cpx, + cpy, + chroma_side, + chroma_tx, + base_q_idx, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), + None, + None, + )?; + let v_grid = read_plane( + dec, + cdfs, + chroma_set, + scans.1, + 2, + chroma_around[2], + mode, + DC_PRED, + Reach::none(), + v, + cpx, + cpy, + chroma_side, + chroma_tx, + base_q_idx, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), + None, + None, + )?; + neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]); } - neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]); neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip); neighbours.fill_lf_grid( (r * (SUB / MI), c * (SUB / MI)), side / MI, - side as u8, + logical_tx as u8, false, ); Ok(()) @@ -1183,6 +1440,8 @@ fn decode_leaf8( v: &mut PlaneBuf, base_q_idx: u8, enable_filter_intra: bool, + tx_select: bool, + reduced_tx_set: bool, ) -> Result { let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; @@ -1206,6 +1465,19 @@ fn decode_leaf8( 8, enable_filter_intra, )?; + // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only + // depths an 8x8 block offers are `TX8` (depth 0, this decoder's one + // supported case) and `TX4` (depth 1, which this crate has no 4x4 luma + // coefficient tables for) -- read to stay in sync, then refuse rather + // than silently miscode. + if tx_select { + let resolved = read_tx_size(dec, cdfs, neighbours, leaf_mi, 8); + if resolved == 4 { + return Err(unsupported( + "a resolved 4x4 luma transform (TxMode::Select depth exhausted; this decoder has no 4x4 luma coefficient tables)", + )); + } + } let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let reach = Reach::of(8, px, py, y.width, y.height); let (cpx, cpy) = (px / 2, py / 2); @@ -1241,7 +1513,11 @@ fn decode_leaf8( luma_grid = read_plane( dec, cdfs, - TxbSet::Luma8, + if reduced_tx_set { + TxbSet::Luma8 + } else { + TxbSet::Luma8Set1 + }, scans.0, 0, around[0], @@ -1256,6 +1532,7 @@ fn decode_leaf8( base_q_idx, None, filter_intra, + None, )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u_grid = read_plane( @@ -1276,6 +1553,7 @@ fn decode_leaf8( base_q_idx, alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + None, )?; v_grid = read_plane( dec, @@ -1295,6 +1573,7 @@ fn decode_leaf8( base_q_idx, alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + None, )?; } neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); @@ -1537,6 +1816,76 @@ fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { if chroma { luma_tx / 2 } else { luma_tx } } +/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom +/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each +/// present only when its neighbour exists inside the true frame -- whether +/// the block immediately above (at this block's own leftmost mi column) or +/// to the left (at its own topmost mi row) coded a transform at least as wide +/// as `own_side`. +fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize { + let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side; + let left = mi_c > 0 && tx_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side; + usize::from(above) + usize::from(left) +} + +/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under +/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to +/// the transform's own side in pixels (`side >> depth`) -- this decoder's +/// four square categories (8/16/32/64) each halve at most twice, matching +/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`). +fn read_tx_size( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + n: &Neighbours, + at_mi: (usize, usize), + side: usize, +) -> usize { + let ctx = tx_size_context(n, at_mi, side); + let depth = match side { + 8 => dec.symbol(&mut cdfs.tx_size_cat0[ctx]), + 16 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), + 32 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), + 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), + _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"), + }; + if depth != 0 { + TX_DEPTH_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + side >> depth +} + +/// The luma coefficient scan table for a resolved transform side -- 32/16/8, +/// the only three sizes a `TxMode::Select` block's coded coefficient grid +/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be. +fn scan_for<'a>(tx_px: usize, scan32: &'a [u16], scan16: &'a [u16], scan8: &'a [u16]) -> &'a [u16] { + match tx_px { + 32 => scan32, + 16 => scan16, + 8 => scan8, + _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"), + } +} + +/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables +/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case +/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching +/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at +/// `TX_8X8`: an intra `TX_16X16` always reads `TX_SET_INTRA_2` regardless of +/// the flag (`av1_get_ext_tx_set_type`'s `tx_size_sqr == TX_16X16` branch +/// ignores `use_reduced_set` once it is past the `TX_32X32`/reduced-set +/// checks), so only the 8x8 case has a second table +/// ([`TxbSet::Luma8Set1`]). +fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { + match tx_px { + 64 => TxbSet::Luma64, + 32 => TxbSet::Luma32, + 16 => TxbSet::Luma16, + 8 if reduced_tx_set => TxbSet::Luma8, + 8 => TxbSet::Luma8Set1, + _ => unreachable!("read_tx_size never resolves a block's own side to anything else"), + } +} + /// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the /// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on. fn unit_log2(px: u32) -> i32 { @@ -2077,6 +2426,8 @@ pub fn decode_key_frame_tile( enable_filter_intra: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, + tx_select: bool, + reduced_tx_set: bool, ) -> Result { decode_key_frame_tile_with_cdfs( data, @@ -2089,6 +2440,8 @@ pub fn decode_key_frame_tile( cdef, loop_filter, None, + tx_select, + reduced_tx_set, ) .map(|(picture, _)| picture) } @@ -2112,6 +2465,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( cdef: &CdefParams, loop_filter: &LoopFilterParams, initial_cdfs: Option, + tx_select: bool, + reduced_tx_set: bool, ) -> Result<(Picture, Cdfs)> { if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); @@ -2217,6 +2572,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut v, base_q_idx, enable_filter_intra, + &scan32, + &scan16, + &scan8, + tx_select, + reduced_tx_set, )?; } PARTITION_SPLIT => { @@ -2274,6 +2634,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut v, base_q_idx, enable_filter_intra, + &scan32, + &scan16, + &scan8, + tx_select, + reduced_tx_set, )?; } PARTITION_SPLIT => { @@ -2293,6 +2658,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let ctx16 = neighbours.partition_ctx(at16, SUB); if has_cols16 && has_rows16 { let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}", + at16.0, at16.1 + ); + } if part16 == PARTITION_NONE { decode_block( &mut dec, @@ -2311,6 +2682,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut v, base_q_idx, enable_filter_intra, + &scan32, + &scan16, + &scan8, + tx_select, + reduced_tx_set, )?; continue; } @@ -2354,6 +2730,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut v, base_q_idx, enable_filter_intra, + tx_select, + reduced_tx_set, )?; prev_leaf = Some((leaf_mi, leaf_mode)); } @@ -2416,6 +2794,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut v, base_q_idx, enable_filter_intra, + tx_select, + reduced_tx_set, )?; prev_leaf = Some((leaf_mi, leaf_mode)); } @@ -2982,6 +3362,7 @@ fn decode_inter_block( base_q_idx, None, None, + None, )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); u_grid = read_plane( @@ -3002,6 +3383,7 @@ fn decode_inter_block( base_q_idx, alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + None, )?; v_grid = read_plane( dec, @@ -3021,6 +3403,7 @@ fn decode_inter_block( base_q_idx, alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + None, )?; } } @@ -3377,6 +3760,7 @@ fn decode_inter_block8( base_q_idx, None, None, + None, )?; u_grid = read_plane( dec, @@ -3396,6 +3780,7 @@ fn decode_inter_block8( base_q_idx, None, None, + None, )?; v_grid = read_plane( dec, @@ -3415,6 +3800,7 @@ fn decode_inter_block8( base_q_idx, None, None, + None, )?; } } @@ -3808,7 +4194,9 @@ mod tests { 128, false, &CdefParams::default(), - &LoopFilterParams::default() + &LoopFilterParams::default(), + false, + true, ) .is_err() ); @@ -3849,6 +4237,8 @@ mod tests { false, &CdefParams::default(), &LoopFilterParams::default(), + false, + true, ) .unwrap(); assert_eq!(decoded.width, w, "{w}x{h}: decoded width"); @@ -3930,6 +4320,8 @@ mod tests { false, &CdefParams::default(), &LoopFilterParams::default(), + false, + true, ) .unwrap(); assert!( @@ -4113,6 +4505,8 @@ mod tests { false, &CdefParams::default(), &LoopFilterParams::default(), + false, + true, ) .unwrap(); assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg"); @@ -4183,6 +4577,8 @@ mod tests { false, &CdefParams::default(), &LoopFilterParams::default(), + false, + true, ) .unwrap(); assert_eq!( @@ -4456,6 +4852,8 @@ mod tests { false, &CdefParams::default(), &LoopFilterParams::default(), + false, + true, ) .unwrap(); assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg"); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index cd0c8197..ec9afea8 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -92,22 +92,22 @@ pub fn decode_stream(data: &[u8]) -> Result> { "a frame with cdef_bits > 0 (this decoder never reads the per-64x64 cdef_idx symbol)", )); } - // Every `decode_block` call below assumes the block's transform is - // its own full size (`TxMode::Largest`, which is all this crate's own - // encoder ever writes, spec `read_tx_size` inferring the max depth - // with no bits) -- it never reads a `tx_depth` symbol at all. A real - // encoder's `TxMode::Select` (spec 5.9.2's `tx_mode` bit) codes one - // per intra block, and skipping that read does not error -- the - // decoder just goes on consuming the next bits as if they were the - // uv_mode/coefficient symbols they are not, so the block "decodes" - // syntactically clean into low-energy garbage: lane-av1real r3's - // luma-near-flat-vs-ffmpeg-gradient bug. Refuse before that, the same - // way as the CDEF case above, rather than silently miscode every - // `TxMode::Select` stream. - if header.tx_mode == TxMode::Select { + // An intra frame's `decode_key_frame_tile*` now reads `tx_depth` + // under `TxMode::Select` (lane-av1txsel, spec 5.11.16): the key-frame + // decode path threads `tx_select` through `decode_block`/ + // `decode_leaf8`, and refuses on its own (a named `unsupported`, not + // a silent desync) the one case it still cannot code -- a resolved + // 4x4 luma transform, which has no coefficient tables here. This + // refusal is narrowed to what genuinely still has no reader at all: + // `decode_inter_frame`'s inter path never threads `tx_select` + // through its own block loop, so an inter frame under + // `TxMode::Select` still desyncs the same way the comment above used + // to describe for every frame -- lane-av1real r3's + // luma-near-flat-vs-ffmpeg-gradient bug. + if header.tx_mode == TxMode::Select && header.frame_type != FrameType::Key { return Err(Error::unsupported( "AV1 decode_stream", - "a frame using TxMode::Select (this decoder never reads a tx_depth symbol, so it desyncs after the first intra block's mode)", + "an inter frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)", )); } // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`, @@ -214,6 +214,8 @@ pub fn decode_stream(data: &[u8]) -> Result> { &header.cdef, &header.loop_filter, initial_cdfs, + header.tx_mode == TxMode::Select, + header.reduced_tx_set, )? } else { let last_slot = header.ref_frame_idx[0] as usize; @@ -339,6 +341,9 @@ mod tests { false, &ec_av1_syntax::CdefParams::default(), &ec_av1_syntax::LoopFilterParams::default(), + false, + // Our own encoder always writes `reduced_tx_set: true`. + true, ) .unwrap(); let via_stream = decode_stream(&encoded.stream).unwrap(); @@ -996,6 +1001,171 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg"); } + /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`], + /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other + /// recipe in this file pins off specifically to keep the stream on + /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick + /// `TxMode::Select` and split some blocks' luma transform below their own + /// side (spec 5.11.16), which is what this test's `tx_depth_hits()` + /// counter proves actually happened -- a stream that resolves every + /// `tx_depth` to 0 would pixel-match by construction (identical to + /// `TxMode::Largest`) without exercising the new split-TU decode path at + /// all. Same multi-seed retry shape as + /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]: + /// aomenc's own RD is free (with tx-size search on) to also occasionally + /// pick `allow_screen_content_tools` on this content, a separate, + /// already-named refusal -- try several seeds, and the first stream that + /// both decodes AND actually split a transform must be pixel-exact. + #[test] + fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height) = (64usize, 64usize); + let mut refusals = Vec::new(); + for attempt in 0..40u32 { + let seed = 42 + attempt; + // A flat gradient never has enough local detail for the RD + // search to prefer a split transform over the block's own full + // size -- `mandelbrot`'s fractal boundary gives every attempt + // (a different `start_scale`) sharp, varied-frequency edges. + // start_scale 5.0 is the proven first try (decodes pixel-exact + // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs); + // later attempts walk down for variety when aomenc's RD flips + // elsewhere. + let source = format!( + "mandelbrot=size=64x64:start_scale={}:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + // Desaturated: chroma stays flat (constant 128) so + // `uv_mode` always resolves to `DC_PRED` and this + // decoder's still-unsupported directional-chroma round-2 + // gap never fires, leaving the luma detail alone to + // drive whether `TxMode::Select`'s RD splits a block. + "-vf", + "hue=s=0", + "-pix_fmt", + "yuv420p", + "-t", + "0.04", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + // Every non-DC intra tool off: directional chroma and + // angle deltas are separate round-2 gaps, and DC-only + // residual is exactly what gives the RD search a reason + // to split a transform. + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-cdef=0", + // Loop restoration is a named refusal (aomenc's RD picks + // Sgrproj on this kind of content) -- off in every recipe + // whose test targets a different surface. + "--enable-restoration=0", + "--max-partition-size=32", + // 16x16 blocks are what split into the TX8 TUs whose + // set-1 tx_type rows this gate exists to prove; some + // scales resolve depth 2 (TX4, a named refusal) and the + // attempt loop just moves on. + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--obu", + "-o", + "-", + "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::tx_depth_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + refusals.push(format!("seed {seed}: {e}")); + continue; + } + }; + if decode::tx_depth_hits() == before { + refusals.push(format!( + "seed {seed}: decoded, but no block resolved a split tx_depth" + )); + continue; + } + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed {seed})" + ); + 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; + } + 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{}", + refusals.join("\n") + ); + } + /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0 /// --auto-alt-ref=0` keep every non-key frame a simple forward /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index ae89866c..7ad050ec 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -314,6 +314,12 @@ pub enum TxType { AdstDct, /// DCT down the column axis, ADST across the row axis. DctAdst, + /// DCT down the column axis, identity across the row axis + /// (`V_DCT` -- `TX_SET_INTRA_1` only). + VDct, + /// Identity down the column axis, DCT across the row axis + /// (`H_DCT` -- `TX_SET_INTRA_1` only). + HDct, } impl TxType { @@ -329,6 +335,24 @@ impl TxType { } } + /// The inverse of `Tx_Type_Intra_Inv_Set1`'s CDF symbol order + /// (`av1_ext_tx_inv[EXT_TX_SET_DTT4_IDTX_1DDCT]`, entropymode.h: + /// `{9, 0, 10, 11, 3, 1, 2}` = IDTX, DCT_DCT, V_DCT, H_DCT, ADST_ADST, + /// ADST_DCT, DCT_ADST) -- the seven-type set a `reduced_tx_set == 0` + /// frame's small intra transforms read from. + pub fn from_symbol_set1(t: usize) -> Option { + match t { + 0 => Some(Self::Idtx), + 1 => Some(Self::DctDct), + 2 => Some(Self::VDct), + 3 => Some(Self::HDct), + 4 => Some(Self::AdstAdst), + 5 => Some(Self::AdstDct), + 6 => Some(Self::DctAdst), + _ => None, + } + } + /// `(row, col)`: the transform `inverse_transform_2d_typed`'s row pass /// (`htx_tab`, spec/libaom "horizontal") and column pass (`vtx_tab`, /// "vertical") each run. Read off libaom's `av1_inv_txfm2d.c` `vtx_tab`/ @@ -343,6 +367,9 @@ impl TxType { Self::AdstAdst => (Adst, Adst), Self::AdstDct => (Dct, Adst), Self::DctAdst => (Adst, Dct), + // `av1_inv_txfm2d.c`: V_DCT vtx=DCT htx=IDTX, H_DCT the mirror. + Self::VDct => (Identity, Dct), + Self::HDct => (Dct, Identity), } } }