diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index e26bd9c2..7b2a2f58 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -25,6 +25,33 @@ pub const PARTITION_W64: [[u16; 11]; 4] = [ /// `Default_Skip_Cdf` (spec 9.4): indexed by how many of the blocks above /// and left were skipped. +/// `default_txfm_partition_cdf` (entropymode.c): an inter block's +/// `txfm_split` flag (spec 5.11.17 `read_var_tx_size`), indexed by +/// `txfm_partition_context` -- `category * 3 + above + left`, 21 contexts. +pub const TXFM_PARTITION: [[u16; 3]; 21] = [ + [28581, 32768, 0], + [23846, 32768, 0], + [20847, 32768, 0], + [24315, 32768, 0], + [18196, 32768, 0], + [12133, 32768, 0], + [18791, 32768, 0], + [10887, 32768, 0], + [11005, 32768, 0], + [27179, 32768, 0], + [20004, 32768, 0], + [11281, 32768, 0], + [26549, 32768, 0], + [19308, 32768, 0], + [14224, 32768, 0], + [28015, 32768, 0], + [21546, 32768, 0], + [14400, 32768, 0], + [28165, 32768, 0], + [22401, 32768, 0], + [16088, 32768, 0], +]; + pub const SKIP: [[u16; 3]; 3] = [[31671, 32768, 0], [16515, 32768, 0], [4576, 32768, 0]]; /// `Default_Intra_Frame_Y_Mode_Cdf` (spec 9.4): the thirteen luma intra @@ -1429,6 +1456,20 @@ pub const INTER_TX_TYPE_SET2_16: [u16; 13] = [ 770, 2421, 5225, 12907, 15819, 18927, 21561, 24089, 26595, 28526, 30529, 32768, 0, ]; +/// `Default_Inter_Ext_Tx_Cdf`'s `TX_SET_INTER_1` (`EXT_TX_SET_ALL16`) row for +/// `TX_4X4` (lane-txselect): the sixteen-symbol transform type of an +/// `is_inter` 4x4 luma transform when `reduced_tx_set == 0` (libaom +/// `entropymode.c` `default_inter_ext_tx_cdf[1][TX_4X4]`). +pub const INTER_TX_TYPE_SET1_4: [u16; 17] = [ + 4458, 5560, 7695, 9709, 13330, 14789, 17537, 20266, 21504, 22848, 23934, 25474, 27727, 28915, + 30631, 32768, 0, +]; + +/// `Default_Inter_Ext_Tx_Cdf`'s `TX_SET_INTER_3` (`EXT_TX_SET_DCT_IDTX`) row +/// for `TX_4X4` (lane-txselect), the reduced two-symbol counterpart of +/// [`INTER_TX_TYPE_SET1_4`] (`default_inter_ext_tx_cdf[3][TX_4X4]`). +pub const INTER_TX_TYPE_SET3_4: [u16; 3] = [16384, 32768, 0]; + /// `Default_Inter_Ext_Tx_Cdf`'s `TX_SET_INTER_1` (`EXT_TX_SET_ALL16`) row for /// `TX_8X8` (lane-cdffwd2): the full sixteen-symbol transform type of an /// `is_inter` 8x8 luma transform when `reduced_tx_set == 0` @@ -5044,3 +5085,44 @@ pub const INTRA_TX_TYPE_SET1_4: [[u16; 8]; 13] = [ [277, 4369, 5255, 8905, 16465, 22271, 32768, 0], [3409, 5436, 10599, 15599, 19687, 24040, 32768, 0], ]; + +/// The `TX_CLASS_HORIZ`/`TX_CLASS_VERT` siblings of [`EOB_PT_256_LUMA`], +/// [`EOB_PT_256_CHROMA`], [`EOB_PT_64_CHROMA`] and [`EOB_PT_16_CHROMA`] +/// (`av1_default_eob_multi{256,64,16}_cdfs[q][plane][1]`, `token_cdfs.h`) -- +/// lane-txselect r2: the class dimension libaom keeps on *every* eob_pt +/// table. Only 4x4/8x8 luma carried it here, so the first `V_DCT`/`H_DCT` +/// 16x16 luma TU (a var-tx leaf of a 32x32 inter block, `EXT_TX_SET_ +/// DTT9_IDTX_1DDCT`) read the 2D table and desynced at its `eob`. 32-point +/// and larger transforms need no sibling: their tx sets (`DCT_IDTX`, +/// `DCTONLY`) hold no 1D type. +pub const EOB_PT_256_LUMA_CLASS1_Q0: [u16; 10] = + [998, 1850, 2998, 5604, 17341, 19888, 22899, 25583, 32768, 0]; +pub const EOB_PT_256_LUMA_CLASS1_Q1: [u16; 10] = + [399, 1019, 1749, 3038, 10444, 15546, 22739, 27294, 32768, 0]; +pub const EOB_PT_256_LUMA_CLASS1: [u16; 10] = + [1084, 2358, 3488, 5122, 11483, 18103, 26023, 29799, 32768, 0]; +pub const EOB_PT_256_LUMA_CLASS1_Q3: [u16; 10] = + [2453, 4474, 6307, 8777, 16474, 22975, 29000, 31547, 32768, 0]; + +pub const EOB_PT_256_CHROMA_CLASS1_Q0: [u16; 10] = + [2203, 4130, 7435, 10739, 20652, 23681, 25609, 27261, 32768, 0]; +pub const EOB_PT_256_CHROMA_CLASS1_Q1: [u16; 10] = + [1674, 3252, 5734, 10159, 22397, 23802, 24821, 30940, 32768, 0]; +pub const EOB_PT_256_CHROMA_CLASS1: [u16; 10] = + [6571, 9610, 15516, 21826, 29092, 30829, 31842, 32708, 32768, 0]; +pub const EOB_PT_256_CHROMA_CLASS1_Q3: [u16; 10] = + [9998, 17661, 25178, 28097, 31308, 32038, 32403, 32695, 32768, 0]; + +pub const EOB_PT_64_CHROMA_CLASS1_Q0: [u16; 8] = + [1563, 2700, 4876, 10911, 14706, 22480, 32768, 0]; +pub const EOB_PT_64_CHROMA_CLASS1_Q1: [u16; 8] = + [1923, 3127, 5867, 9703, 14277, 27100, 32768, 0]; +pub const EOB_PT_64_CHROMA_CLASS1: [u16; 8] = + [4034, 6290, 10235, 14982, 21214, 28491, 32768, 0]; +pub const EOB_PT_64_CHROMA_CLASS1_Q3: [u16; 8] = + [8726, 12378, 19409, 26450, 30038, 32462, 32768, 0]; + +pub const EOB_PT_16_CHROMA_CLASS1_Q0: [u16; 6] = [1904, 3354, 7763, 14647, 32768, 0]; +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]; diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 866988bc..cd587b45 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -71,6 +71,16 @@ pub(crate) enum TxbSet { /// `is_inter` block has no writer path yet, so this crate has no /// `Luma4Inter` counterpart to [`Luma8Inter`](TxbSet::Luma8Inter). Luma4, + /// The 4x4 luma transform of an `is_inter` block whose `TxMode::Select` + /// var-tx tree splits an 8x8 unit all the way down (lane-txselect): the + /// same coefficient tables [`Luma4`](TxbSet::Luma4) reads (libaom's + /// coefficient CDFs are keyed by plane type, not intra/inter), with the + /// inter `tx_type` set in place of the intra one. + Luma4Inter, + /// [`Luma4Inter`](TxbSet::Luma4Inter)'s `reduced_tx_set: false` + /// counterpart -- the sixteen-symbol `EXT_TX_SET_ALL16` table + /// ([`crate::cdf::INTER_TX_TYPE_SET1_4`]). + Luma4InterSet1, /// [`Luma4`](TxbSet::Luma4)'s `reduced_tx_set: false` counterpart, same /// split as [`Luma8Set1`](TxbSet::Luma8Set1). Luma4Set1, @@ -158,6 +168,10 @@ pub(crate) struct Cdfs { /// The partition symbol of a 32x32 block. pub partition_w32: [[u16; 11]; 4], /// Whether a block carries no residual at all. + /// `txfm_partition_cdf`: an inter block's `txfm_split` flag under + /// `TxMode::Select` (lane-txselect, spec 5.11.17), indexed by + /// `txfm_partition_context` -- see [`cdf::TXFM_PARTITION`]. + pub txfm_partition: [[u16; 3]; 21], pub skip: [[u16; 3]; 3], /// The luma mode of a key frame's block, under the two neighbours' modes. pub kf_y_mode: [[[u16; 14]; 5]; 5], @@ -200,6 +214,17 @@ 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. + 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. + pub eob_pt_256_chroma_class1: [u16; 10], + pub eob_pt_64_chroma_class1: [u16; 8], + pub eob_pt_16_chroma_class1: [u16; 6], /// 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. @@ -342,6 +367,11 @@ pub(crate) struct Cdfs { /// (lane-cdffwd2): the sixteen-symbol `EXT_TX_SET_ALL16` row, not /// indexed by mode. pub inter_tx_type_8_set1: [u16; 17], + /// The 4x4 counterparts of [`Self::inter_tx_type_8`]/ + /// [`Self::inter_tx_type_8_set1`] (lane-txselect). + pub inter_tx_type_4: [u16; 3], + /// See [`Self::inter_tx_type_4`]. + pub inter_tx_type_4_set1: [u16; 17], /// The DC sign of a chroma coefficient, shared by both chroma sets. pub dc_sign_chroma: [[u16; 3]; 3], /// Whether an inter frame's block is coded as intra. @@ -583,6 +613,7 @@ impl Cdfs { pub(crate) fn reset_counts(&mut self) { reset2(&mut self.partition_w64); reset2(&mut self.partition_w32); + reset2(&mut self.txfm_partition); reset2(&mut self.skip); reset3(&mut self.kf_y_mode); reset2(&mut self.uv_mode_no_cfl); @@ -602,6 +633,10 @@ 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_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); reset2(&mut self.eob_extra_luma_16); reset2(&mut self.eob_extra_luma_8); reset2(&mut self.eob_extra_luma_4); @@ -660,6 +695,8 @@ impl Cdfs { reset1(&mut self.inter_tx_type_8); reset1(&mut self.inter_tx_type_16_set2); reset1(&mut self.inter_tx_type_8_set1); + reset1(&mut self.inter_tx_type_4); + reset1(&mut self.inter_tx_type_4_set1); reset2(&mut self.dc_sign_chroma); reset2(&mut self.intra_inter); reset3(&mut self.single_ref); @@ -821,6 +858,34 @@ impl Cdfs { cdf::EOB_PT_64_LUMA_CLASS1, cdf::EOB_PT_64_LUMA_CLASS1_Q3, ), + eob_pt_256_luma_class1: pick( + q_ctx, + cdf::EOB_PT_256_LUMA_CLASS1_Q0, + cdf::EOB_PT_256_LUMA_CLASS1_Q1, + cdf::EOB_PT_256_LUMA_CLASS1, + cdf::EOB_PT_256_LUMA_CLASS1_Q3, + ), + eob_pt_256_chroma_class1: pick( + q_ctx, + cdf::EOB_PT_256_CHROMA_CLASS1_Q0, + cdf::EOB_PT_256_CHROMA_CLASS1_Q1, + cdf::EOB_PT_256_CHROMA_CLASS1, + cdf::EOB_PT_256_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_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_extra_luma_16: pick( q_ctx, cdf::EOB_EXTRA_LUMA_16_Q0, @@ -1149,6 +1214,8 @@ impl Cdfs { inter_tx_type_8: cdf::INTER_TX_TYPE_SET3_8, inter_tx_type_16_set2: cdf::INTER_TX_TYPE_SET2_16, inter_tx_type_8_set1: cdf::INTER_TX_TYPE_SET1_8, + inter_tx_type_4: cdf::INTER_TX_TYPE_SET3_4, + inter_tx_type_4_set1: cdf::INTER_TX_TYPE_SET1_4, dc_sign_chroma: cdf::DC_SIGN_CHROMA, intra_inter: cdf::INTRA_INTER, single_ref: cdf::SINGLE_REF, @@ -1158,6 +1225,7 @@ impl Cdfs { uni_comp_ref: cdf::UNI_COMP_REF, comp_ref: cdf::COMP_REF, comp_bwdref: cdf::COMP_BWDREF, + txfm_partition: cdf::TXFM_PARTITION, skip_mode: cdf::SKIP_MODE, obmc: cdf::OBMC, motion_mode: cdf::MOTION_MODE, @@ -1263,7 +1331,7 @@ impl Cdfs { br: &mut self.br_luma_16, dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.intra_tx_type_16[mode].as_mut_slice()), - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_256_luma_class1), }, TxbSet::Luma16Inter => TxbTables { side: 16, @@ -1275,7 +1343,7 @@ impl Cdfs { br: &mut self.br_luma_16, dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.inter_tx_type_16.as_mut_slice()), - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_256_luma_class1), }, TxbSet::Luma16InterSet1 => TxbTables { side: 16, @@ -1287,7 +1355,7 @@ impl Cdfs { br: &mut self.br_luma_16, dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.inter_tx_type_16_set2.as_mut_slice()), - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_256_luma_class1), }, TxbSet::Luma8 => TxbTables { side: 8, @@ -1325,6 +1393,30 @@ impl Cdfs { tx_type: Some(self.intra_tx_type_4[mode].as_mut_slice()), eob_pt_class1: Some(&mut self.eob_pt_16_luma_class1), }, + TxbSet::Luma4Inter => TxbTables { + side: 4, + txb_skip: &mut self.txb_skip_luma_4, + eob_pt: &mut self.eob_pt_16_luma, + eob_extra: &mut self.eob_extra_luma_4, + base: &mut self.base_luma_4, + base_eob: &mut self.base_eob_luma_4, + 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, + }, + TxbSet::Luma4InterSet1 => TxbTables { + side: 4, + txb_skip: &mut self.txb_skip_luma_4, + eob_pt: &mut self.eob_pt_16_luma, + eob_extra: &mut self.eob_extra_luma_4, + base: &mut self.base_luma_4, + base_eob: &mut self.base_eob_luma_4, + br: &mut self.br_luma_4, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_4_set1.as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_16_luma_class1), + }, TxbSet::Luma4Set1 => TxbTables { side: 4, txb_skip: &mut self.txb_skip_luma_4, @@ -1371,7 +1463,7 @@ impl Cdfs { br: &mut self.br_chroma_8, dc_sign: &mut self.dc_sign_chroma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_64_chroma_class1), }, TxbSet::Chroma4 => TxbTables { side: 4, @@ -1383,7 +1475,7 @@ impl Cdfs { br: &mut self.br_chroma_4, dc_sign: &mut self.dc_sign_chroma, tx_type: None, - eob_pt_class1: None, + eob_pt_class1: Some(&mut self.eob_pt_16_chroma_class1), }, TxbSet::Chroma16 => TxbTables { side: 16, @@ -1395,7 +1487,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_256_chroma_class1), }, TxbSet::Chroma32 => TxbTables { side: 32, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index fb699972..a9df2d55 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -759,6 +759,38 @@ pub(crate) fn tx_depth_hits() -> usize { TX_DEPTH_HITS.with(|c| c.get()) } +// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree +// read, and how many of those actually took the split, on the current thread +// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a +// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block +// coincidentally coding one whole-block transform. +thread_local! { + static TXFM_SPLIT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static TXFM_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits, + // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] -- + // `decode_inter_block` already carries forty parameters and both are + // frame-constant. + static TX_SELECT_INTER: std::cell::Cell = const { std::cell::Cell::new(false) }; + static REDUCED_TX_SET_INTER: std::cell::Cell = const { std::cell::Cell::new(true) }; +} + +/// Current value of [`TXFM_SPLIT_READS`]. +pub(crate) fn txfm_split_reads() -> usize { + TXFM_SPLIT_READS.with(|c| c.get()) +} + +/// Current value of [`TXFM_SPLIT_HITS`]. +pub(crate) fn txfm_split_hits() -> usize { + TXFM_SPLIT_HITS.with(|c| c.get()) +} + +/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]. +pub(crate) fn set_inter_tx_mode(tx_select: bool, reduced_tx_set: bool) { + TX_SELECT_INTER.with(|c| c.set(tx_select)); + REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set)); +} + // How many `partition_w16` reads (a 16x16 block's own partition symbol, key // intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a // plain default-settings aomenc run over lavfi mandelbrot hits this arm on @@ -2393,6 +2425,16 @@ struct Neighbours { /// `left_skip`. above_skip: Vec, left_skip: Vec, + /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at + /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in + /// pixels last written over each unit by `set_txfm_ctxs`/ + /// `txfm_partition_update`, which is what an inter block's `txfm_split` + /// symbol reads its context from (lane-txselect, spec 5.11.17). + /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left` + /// array is exactly libaom's per-superblock-row reset, since each mi row + /// is only ever visited inside one superblock row. + above_txfm: Vec, + left_txfm: Vec, /// Whether the block above/left of this column/row coded `skip_mode` /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup, /// lane-av1comp round 14. @@ -2523,6 +2565,8 @@ impl Neighbours { left_side: vec![SB; rows], above_side_mi: vec![SB; cols * (SUB / MI)], left_side_mi: vec![SB; rows * (SUB / MI)], + above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], + left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an // 8x8 inter leaf's left neighbour is the OTHER leaf row of the // 16x16 block beside it, which a SUB-grid slot cannot name @@ -5890,7 +5934,7 @@ fn decode_block( // 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); + let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None); (resolved, if resolved == 64 { 32 } else { resolved }) } else { (side, luma_tx) @@ -6325,7 +6369,7 @@ fn decode_leaf8( // transform units, same raster-order per-TU pattern `decode_block`'s // multi-TU branch runs). let resolved = if tx_select { - read_tx_size(dec, cdfs, neighbours, leaf_mi, 8) + read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None) } else { 8 }; @@ -6842,6 +6886,33 @@ fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize usize::from(above) + usize::from(left) } +/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`), +/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays +/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the +/// inter path maintains), except that an *inter* neighbour contributes its +/// own BLOCK size rather than its transform size -- the two differ the moment +/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid +/// approximation coincides with this only while every neighbour codes one +/// whole-block transform, which is exactly what `TxMode::Select` ends. +fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize { + let has_above = mi_r > n.tile_row0_mi; + let has_left = mi_c > n.tile_col0_mi; + let mut above = usize::from(n.above_txfm[mi_c]) >= side; + let mut left = usize::from(n.left_txfm[mi_r]) >= side; + if has_above && n.above_inter[mi_c / (SUB / MI)] { + above = n.above_side_mi[mi_c] >= side; + } + if has_left && n.left_inter[mi_r / (SUB / MI)] { + left = n.left_side_mi[mi_r] >= side; + } + match (has_above, has_left) { + (true, true) => usize::from(above) + usize::from(left), + (true, false) => usize::from(above), + (false, true) => usize::from(left), + (false, false) => 0, + } +} + /// `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 @@ -6853,8 +6924,12 @@ fn read_tx_size( n: &Neighbours, at_mi: (usize, usize), side: usize, + // lane-txselect: `get_tx_size_context`'s real context, for the callers + // that have one -- see [`tx_size_context_txfm`]. `None` keeps the + // key-frame path's own deblock-grid approximation. + ctx_override: Option, ) -> usize { - let ctx = tx_size_context(n, at_mi, side); + let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, side)); let depth = match side { 8 => { dec.symbol(&mut cdfs.tx_size_cat0[ctx]) @@ -6883,6 +6958,349 @@ fn read_tx_size( side >> depth } +/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's +/// `txfm_split` context -- a category from the block's own largest square +/// transform and whether this unit already sits below it, times three, plus +/// the two neighbour terms (whether the transform last written above/left of +/// this unit is narrower/shorter than the unit itself). +fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize { + let above = usize::from(usize::from(above_px) < tx_px); + let left = usize::from(usize::from(left_px) < tx_px); + // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the + // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as + // `log2(px) - 2`. + let max_tx = blk_max_px.min(64); + let max_idx = max_tx.trailing_zeros() as usize - 2; + let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2; + category * 3 + above + left +} + +/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit +/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the +/// resolved transform's own size. +fn txfm_partition_update( + n: &mut Neighbours, + (mi_r, mi_c): (usize, usize), + tx_px: usize, + txb_px: usize, +) { + for i in 0..txb_px / MI { + if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { + *cell = tx_px as u8; + } + if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { + *cell = tx_px as u8; + } + } +} + +/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the +/// same contexts -- a skipped *inter* block records its own block size rather +/// than its transform size. +fn set_txfm_ctxs( + n: &mut Neighbours, + (mi_r, mi_c): (usize, usize), + tx_px: usize, + w_mi: usize, + h_mi: usize, + skip_inter: bool, +) { + let bw = if skip_inter { w_mi * MI } else { tx_px }; + let bh = if skip_inter { h_mi * MI } else { tx_px }; + for i in 0..w_mi { + if let Some(cell) = n.above_txfm.get_mut(mi_c + i) { + *cell = bw as u8; + } + } + for i in 0..h_mi { + if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { + *cell = bh as u8; + } + } +} + +/// The value libaom initialises both transform contexts to -- NOT zero: +/// `av1_zero_above_context` memsets the txfm row to +/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same +/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64 +/// pixels, so an unwritten neighbour reads as the *widest* possible +/// transform, not the narrowest. +const TXFM_CTX_INIT: u8 = 64; + +/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most +/// twice below its own largest transform. +const MAX_VARTX_DEPTH: usize = 2; + +/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c` +/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one +/// max-transform-sized unit of an inter block, collecting the resolved leaf +/// transform units into `out` as `(row offset, col offset, side)` in mi units +/// -- exactly the order `decode_reconstruct_tx` later reads their +/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block; +/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/ +/// `max_block_high`). +#[allow(clippy::too_many_arguments)] +fn read_var_tx_size( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + n: &mut Neighbours, + at_mi: (usize, usize), + blk_max_px: usize, + (max_w_mi, max_h_mi): (usize, usize), + tx_px: usize, + depth: usize, + blk_row: usize, + blk_col: usize, + out: &mut Vec<(usize, usize, usize)>, +) { + if blk_row >= max_h_mi || blk_col >= max_w_mi { + return; + } + let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col); + if depth == MAX_VARTX_DEPTH { + out.push((blk_row, blk_col, tx_px)); + txfm_partition_update(n, unit, tx_px, tx_px); + return; + } + let ctx = txfm_partition_ctx(n.above_txfm[unit.1], n.left_txfm[unit.0], blk_max_px, tx_px); + let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; + TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1)); + if std::env::var_os("EC_TRACE_MODE_STEP").is_some() { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}", + unit.0, + unit.1, + u8::from(split) + ); + } + if !split { + out.push((blk_row, blk_col, tx_px)); + txfm_partition_update(n, unit, tx_px, tx_px); + return; + } + TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + let sub = tx_px / 2; + if sub == 4 { + // libaom's `sub_txs == TX_4X4` early return: the whole 8x8 unit is + // marked 4x4 (four transform units, raster order) without recursing. + for row in 0..2 { + for col in 0..2 { + if blk_row + row < max_h_mi && blk_col + col < max_w_mi { + out.push((blk_row + row, blk_col + col, 4)); + } + } + } + txfm_partition_update(n, unit, 4, tx_px); + return; + } + for row in (0..tx_px / MI).step_by(sub / MI) { + for col in (0..tx_px / MI).step_by(sub / MI) { + read_var_tx_size( + dec, + cdfs, + n, + at_mi, + blk_max_px, + (max_w_mi, max_h_mi), + sub, + depth + 1, + blk_row + row, + blk_col + col, + out, + ); + } + } +} + +/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx +/// branch): every block of a `TxMode::Select` inter frame codes its transform +/// size right after its own mode info -- an inter non-skip block through the +/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns), +/// every other block through the intra `tx_depth` symbol (a skipped inter +/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the +/// block's own resolved transform side and the leaf list, the latter only +/// when the tree resolved to more than one transform unit. +#[allow(clippy::too_many_arguments)] +fn read_block_tx_size( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + n: &mut Neighbours, + at_mi: (usize, usize), + side: usize, + (mi_cols, mi_rows): (usize, usize), + is_inter: bool, + skip: bool, +) -> Result<(usize, Option>)> { + if !TX_SELECT_INTER.with(std::cell::Cell::get) { + return Ok((side, None)); + } + let side_mi = side / MI; + if is_inter && !skip { + let max_tx = side.min(64); + let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1)); + let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0)); + let mut leaves = Vec::new(); + let step = max_tx / MI; + for row in (0..side_mi).step_by(step) { + for col in (0..side_mi).step_by(step) { + read_var_tx_size( + dec, + cdfs, + n, + at_mi, + side, + (max_w_mi, max_h_mi), + max_tx, + 0, + row, + col, + &mut leaves, + ); + } + } + let single = leaves.len() == 1 && leaves[0].2 == side; + if !single && leaves.iter().any(|leaf| leaf.2 > 32) { + // Only a block wider than a superblock's own 64x64 max transform + // reaches here; this crate has no 64-point *inter* coefficient + // table set ([`inter_txbset_for`] stops at 32). + return Err(unsupported( + "an inter var-tx tree with a leaf transform larger than 32x32", + )); + } + let resolved = leaves.last().map_or(side, |l| l.2); + return Ok((resolved, (!single).then_some(leaves))); + } + let tx = if is_inter { + side.min(64) + } else { + let resolved = read_tx_size( + dec, + cdfs, + n, + at_mi, + side, + Some(tx_size_context_txfm(n, at_mi, side)), + ); + if resolved != side { + // An intra block inside an inter frame whose `tx_depth` splits its + // luma transform needs the per-transform-unit intra prediction + // loop `decode_block` runs for a key frame; this path predicts the + // whole block at once, so refuse rather than mis-reconstruct. + return Err(unsupported( + "an intra block in an inter frame whose tx_depth splits its luma transform \ + (round 1)", + )); + } + resolved + }; + set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter); + Ok((tx, None)) +} + +/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8 +/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single +/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in +/// raster order, each reading its own coefficient context off the units +/// already decoded before it. Returns the block's luma grid (all-zero in the +/// split case, whose reconstruction has already happened unit by unit) and +/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup, +/// which for a split block lands on the top-left unit. +#[allow(clippy::too_many_arguments)] +fn read_inter_luma8( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + leaf_mi: (usize, usize), + y: &mut PlaneBuf, + px: usize, + py: usize, + pred_y: &[u16], + mode_for_tx: usize, + base_q_idx: u8, + scan8: &[u16], + scan4: &[u16], + reduced_tx_set: bool, + split: bool, +) -> Result<(Vec, TxType)> { + if !split { + return read_inter_plane( + dec, + cdfs, + if reduced_tx_set { + TxbSet::Luma8Inter + } else { + TxbSet::Luma8InterSet1 + }, + scan8, + 0, + neighbours.around_mi(leaf_mi, 8)[0], + mode_for_tx, + y, + px, + py, + 8, + base_q_idx, + pred_y, + None, + None, + ); + } + let mut first = TxType::DctDct; + for tu_row in 0..2 { + for tu_col in 0..2 { + let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col); + let mut tu_pred = Vec::with_capacity(16); + for rr in 0..4 { + let start = (tu_row * 4 + rr) * 8 + tu_col * 4; + tu_pred.extend_from_slice(&pred_y[start..start + 4]); + } + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); + let (tu_grid, tu_tx_type) = read_inter_plane( + dec, + cdfs, + if reduced_tx_set { + TxbSet::Luma4Inter + } else { + TxbSet::Luma4InterSet1 + }, + scan4, + 0, + neighbours.around_mi(tu_mi, 4)[0], + mode_for_tx, + y, + px + tu_col * 4, + py + tu_row * 4, + 4, + base_q_idx, + &tu_pred, + None, + Some(tu_skip_ctx), + )?; + if tu_row == 0 && tu_col == 0 { + first = tu_tx_type; + } + neighbours.record_mi_luma(tu_mi, 4, &tu_grid); + } + } + Ok((vec![0i32; 64], first)) +} + +/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its +/// coefficient tables from -- the inter counterpart of [`txbset_for`]. +fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet { + match tx_px { + 32 => TxbSet::Luma32Inter, + 16 if reduced_tx_set => TxbSet::Luma16Inter, + 16 => TxbSet::Luma16InterSet1, + 8 if reduced_tx_set => TxbSet::Luma8Inter, + 8 => TxbSet::Luma8InterSet1, + 4 if reduced_tx_set => TxbSet::Luma4Inter, + 4 => TxbSet::Luma4InterSet1, + _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"), + } +} + /// The luma coefficient scan table for a resolved transform side -- 32/16/8/4, /// the only four sizes a `TxMode::Select` block's coded coefficient grid /// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be. @@ -9420,9 +9838,15 @@ fn read_inter_plane( // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true // `DCT_DCT` default at 32-point+) already resolves it without help. inherited_luma_tx_type: Option, + // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than + // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size` + // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block + // transform every non-var-tx caller reads, whose plane-0 context is the + // lone-transform-unit 0. + luma_skip_ctx: Option, ) -> Result<(Vec, TxType)> { let skip_ctx = if plane_idx == 0 { - 0 + luma_skip_ctx.unwrap_or(0) } else { usize::from(around.0) + usize::from(around.1) }; @@ -10633,6 +11057,12 @@ fn decode_inter_block( // common `record_inter` call below (which would otherwise stamp the // single-ref ALTREF-special-case default over it). let mut compound_ctx: Option<(i8, u8, u8)> = None; + // lane-txselect: `read_block_tx_size`'s leaf transform units (spec + // 5.11.17), `Some` only when this block's var-tx tree resolved to more + // than one luma transform -- read back by the residual loop, the + // coefficient-context write-back and the loop-filter grid fill below. + let mut vartx_leaves: Option> = None; + let at_mi = (r * (SUB / MI), c * (SUB / MI)); if is_inter { let above_nbr = has_above.then(|| NeighbourRef { is_inter: above_inter, @@ -11377,6 +11807,17 @@ fn decode_inter_block( mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v); } + vartx_leaves = read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1; if skip { y.reconstruct_mc_rect( px, @@ -11411,22 +11852,70 @@ fn decode_inter_block( } else { let around = neighbours.around(at, side); let luma_tx_type; - (luma_grid, luma_tx_type) = read_inter_plane( - dec, - cdfs, - luma_set_inter, - scan_luma, - 0, - around[0], - mode_for_tx, - y, - px, - py, - side, - base_q_idx, - &pred_y, - None, - )?; + if let Some(leaves) = vartx_leaves.clone() { + // spec 5.11.17's transform tree, leaf by leaf in the order + // `read_var_tx_size` coded it: each unit reads its own + // coefficients against the neighbour magnitudes the + // earlier units already wrote, and reconstructs over its + // own slice of the block's motion-compensated predictor. + let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get); + let mut first_tx_type = TxType::DctDct; + for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() { + let tu_mi = (at_mi.0 + row, at_mi.1 + col); + let (tu_px, tu_py) = (px + col * MI, py + row * MI); + let mut tu_pred = Vec::with_capacity(tx_px * tx_px); + for rr in 0..tx_px { + let start = (row * MI + rr) * side + col * MI; + tu_pred.extend_from_slice(&pred_y[start..start + tx_px]); + } + let scan = default_scan(tx_px); + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); + let (tu_grid, tu_tx_type) = read_inter_plane( + dec, + cdfs, + inter_txbset_for(tx_px, reduced), + &scan, + 0, + neighbours.around_mi(tu_mi, tx_px)[0], + mode_for_tx, + y, + tu_px, + tu_py, + tx_px, + base_q_idx, + &tu_pred, + None, + Some(tu_skip_ctx), + )?; + if idx == 0 { + first_tx_type = tu_tx_type; + } + neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid); + } + // `av1_get_tx_type`'s chroma lookup scales the chroma + // position back to luma, so an inter block's chroma + // inherits the *first* (top-left) luma unit's coded type. + luma_tx_type = first_tx_type; + luma_grid = vec![0i32; side * side]; + } else { + (luma_grid, luma_tx_type) = read_inter_plane( + dec, + cdfs, + luma_set_inter, + scan_luma, + 0, + around[0], + mode_for_tx, + y, + px, + py, + side, + base_q_idx, + &pred_y, + None, + None, + )?; + } u_grid = read_inter_plane( dec, cdfs, @@ -11442,6 +11931,7 @@ fn decode_inter_block( base_q_idx, &pred_u, Some(luma_tx_type), + None, )? .0; v_grid = read_inter_plane( @@ -11459,6 +11949,7 @@ fn decode_inter_block( base_q_idx, &pred_v, Some(luma_tx_type), + None, )? .0; } @@ -12076,6 +12567,17 @@ fn decode_inter_block( interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v); } + vartx_leaves = read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1; if skip { y.reconstruct_mc_rect( px, @@ -12110,22 +12612,70 @@ fn decode_inter_block( } else { let around = neighbours.around(at, side); let luma_tx_type; - (luma_grid, luma_tx_type) = read_inter_plane( - dec, - cdfs, - luma_set_inter, - scan_luma, - 0, - around[0], - mode_for_tx, - y, - px, - py, - side, - base_q_idx, - &pred_y, - None, - )?; + if let Some(leaves) = vartx_leaves.clone() { + // spec 5.11.17's transform tree, leaf by leaf in the order + // `read_var_tx_size` coded it: each unit reads its own + // coefficients against the neighbour magnitudes the + // earlier units already wrote, and reconstructs over its + // own slice of the block's motion-compensated predictor. + let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get); + let mut first_tx_type = TxType::DctDct; + for (idx, &(row, col, tx_px)) in leaves.iter().enumerate() { + let tu_mi = (at_mi.0 + row, at_mi.1 + col); + let (tu_px, tu_py) = (px + col * MI, py + row * MI); + let mut tu_pred = Vec::with_capacity(tx_px * tx_px); + for rr in 0..tx_px { + let start = (row * MI + rr) * side + col * MI; + tu_pred.extend_from_slice(&pred_y[start..start + tx_px]); + } + let scan = default_scan(tx_px); + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI); + let (tu_grid, tu_tx_type) = read_inter_plane( + dec, + cdfs, + inter_txbset_for(tx_px, reduced), + &scan, + 0, + neighbours.around_mi(tu_mi, tx_px)[0], + mode_for_tx, + y, + tu_px, + tu_py, + tx_px, + base_q_idx, + &tu_pred, + None, + Some(tu_skip_ctx), + )?; + if idx == 0 { + first_tx_type = tu_tx_type; + } + neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid); + } + // `av1_get_tx_type`'s chroma lookup scales the chroma + // position back to luma, so an inter block's chroma + // inherits the *first* (top-left) luma unit's coded type. + luma_tx_type = first_tx_type; + luma_grid = vec![0i32; side * side]; + } else { + (luma_grid, luma_tx_type) = read_inter_plane( + dec, + cdfs, + luma_set_inter, + scan_luma, + 0, + around[0], + mode_for_tx, + y, + px, + py, + side, + base_q_idx, + &pred_y, + None, + None, + )?; + } u_grid = read_inter_plane( dec, cdfs, @@ -12141,6 +12691,7 @@ fn decode_inter_block( base_q_idx, &pred_u, Some(luma_tx_type), + None, )? .0; v_grid = read_inter_plane( @@ -12158,6 +12709,7 @@ fn decode_inter_block( base_q_idx, &pred_v, Some(luma_tx_type), + None, )? .0; } @@ -12266,6 +12818,16 @@ fn decode_inter_block( } } + read_block_tx_size( + dec, + cdfs, + neighbours, + at_mi, + side, + (mi_cols as usize, mi_rows as usize), + false, + skip, + )?; let reach = Reach::of(side, px, py, y.width, y.height); if skip { y.reconstruct( @@ -12391,14 +12953,22 @@ fn decode_inter_block( r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 ); } - neighbours.record_rect( - at, - write_w, - write_h, - mode_for_tx, - uv_predict_mode, - &[luma_grid, u_grid, v_grid], - ); + if vartx_leaves.is_some() { + // Plane 0 is already correct per transform unit + // ([`Neighbours::record_mi_luma`] above); this writes everything else + // [`Neighbours::record_rect`] would (a var-tx block is always square, + // so `write_w == write_h == side`). + neighbours.record_split_luma(at, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]); + } else { + neighbours.record_rect( + at, + write_w, + write_h, + mode_for_tx, + uv_predict_mode, + &[luma_grid, u_grid, v_grid], + ); + } neighbours.record_inter_rect( at, write_w, @@ -12435,6 +13005,25 @@ fn decode_inter_block( ref_frame_for_lf }, ); + // lane-txselect: a var-tx block's deblock edges follow its own transform + // units, not the block. Chroma still reads `tx_h_grid / 2` (the block's + // uv transform is not split) -- a known corner-cut of this round. + if let Some(leaves) = &vartx_leaves { + for &(row, col, tx_px) in leaves { + neighbours.fill_lf_grid_rect( + (at_mi.0 + row, at_mi.1 + col), + tx_px / MI, + tx_px / MI, + tx_px as u8, + tx_px as u8, + if globalmv_for_lf { + -ref_frame_for_lf + } else { + ref_frame_for_lf + }, + ); + } + } Ok(()) } @@ -12552,6 +13141,11 @@ fn decode_inter_block8( let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let (cpx, cpy) = (px / 2, py / 2); + // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took + // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) -- + // read back by the luma residual read and the tail's neighbour/loop-filter + // bookkeeping. Always `false` outside a `TxMode::Select` inter frame. + let mut split8 = false; const SIDE: usize = 8; const CHROMA_SIDE: usize = 4; @@ -13001,6 +13595,18 @@ fn decode_inter_block8( mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v); } + split8 = read_block_tx_size( + dec, + cdfs, + neighbours, + leaf_mi, + SIDE, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1 + .is_some(); if skip { y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]); u.reconstruct_mc( @@ -13022,27 +13628,23 @@ fn decode_inter_block8( v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; } else { let around = neighbours.around_mi(leaf_mi, 8); - let luma_tx_type; - (luma_grid, luma_tx_type) = read_inter_plane( + let (grid8, luma_tx_type) = read_inter_luma8( dec, cdfs, - if reduced_tx_set { - TxbSet::Luma8Inter - } else { - TxbSet::Luma8InterSet1 - }, - scan8, - 0, - around[0], - mode_for_tx, + neighbours, + leaf_mi, y, px, py, - SIDE, - base_q_idx, &pred_y, - None, + mode_for_tx, + base_q_idx, + scan8, + scan4, + reduced_tx_set, + split8, )?; + luma_grid = grid8; u_grid = read_inter_plane( dec, cdfs, @@ -13058,6 +13660,7 @@ fn decode_inter_block8( base_q_idx, &pred_u, Some(luma_tx_type), + None, )? .0; v_grid = read_inter_plane( @@ -13075,6 +13678,7 @@ fn decode_inter_block8( base_q_idx, &pred_v, Some(luma_tx_type), + None, )? .0; } @@ -13350,6 +13954,18 @@ fn decode_inter_block8( interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v); } + split8 = read_block_tx_size( + dec, + cdfs, + neighbours, + leaf_mi, + SIDE, + (mi_cols as usize, mi_rows as usize), + true, + skip, + )? + .1 + .is_some(); if skip { y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]); u.reconstruct_mc( @@ -13371,27 +13987,23 @@ fn decode_inter_block8( v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; } else { let around = neighbours.around_mi(leaf_mi, 8); - let luma_tx_type; - (luma_grid, luma_tx_type) = read_inter_plane( + let (grid8, luma_tx_type) = read_inter_luma8( dec, cdfs, - if reduced_tx_set { - TxbSet::Luma8Inter - } else { - TxbSet::Luma8InterSet1 - }, - scan8, - 0, - around[0], - mode_for_tx, + neighbours, + leaf_mi, y, px, py, - SIDE, - base_q_idx, &pred_y, - None, + mode_for_tx, + base_q_idx, + scan8, + scan4, + reduced_tx_set, + split8, )?; + luma_grid = grid8; u_grid = read_inter_plane( dec, cdfs, @@ -13407,6 +14019,7 @@ fn decode_inter_block8( base_q_idx, &pred_u, Some(luma_tx_type), + None, )? .0; v_grid = read_inter_plane( @@ -13424,6 +14037,7 @@ fn decode_inter_block8( base_q_idx, &pred_v, Some(luma_tx_type), + None, )? .0; } @@ -13488,6 +14102,16 @@ fn decode_inter_block8( } } + read_block_tx_size( + dec, + cdfs, + neighbours, + leaf_mi, + SIDE, + (mi_cols as usize, mi_rows as usize), + false, + skip, + )?; let reach = Reach::of(SIDE, px, py, y.width, y.height); if skip { y.reconstruct( @@ -13599,8 +14223,38 @@ fn decode_inter_block8( )?; } } + // lane-txselect: a split leaf's plane-0 neighbour context is per 4x4 + // transform unit (written by `record_mi_luma` inside `read_inter_luma8`), + // but `record_mi` rewrites all three planes of these cells at once -- so + // save plane 0 across it, exactly as `record_split_luma` leaves plane 0 + // alone at the bigger block sizes. + let saved_luma_ctx = split8.then(|| { + ( + [ + neighbours.left[leaf_mi.0][0], + neighbours.left[leaf_mi.0 + 1][0], + ], + [ + neighbours.above[leaf_mi.1][0], + neighbours.above[leaf_mi.1 + 1][0], + ], + ) + }); 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 }); + if let Some((left, above)) = saved_luma_ctx { + for (cell, state) in left.into_iter().enumerate() { + neighbours.left[leaf_mi.0 + cell][0] = state; + } + for (cell, state) in above.into_iter().enumerate() { + neighbours.above[leaf_mi.1 + cell][0] = state; + } + } + neighbours.fill_lf_grid( + leaf_mi, + 2, + if split8 { 4 } else { 8 }, + if is_inter { LAST_FRAME } else { 0 }, + ); Ok((skip, is_inter, skip_mode, compound_ctx8, leaf_refs)) } @@ -13671,6 +14325,9 @@ pub fn decode_inter_frame_tile( false, [0; 2], true, + // `tx_select`: this raw entry point decodes this crate's own encoder's + // streams, which always write `TxMode::Largest`. + false, false, false, false, @@ -13737,6 +14394,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // `Set1` coefficient tables at 16x16/8x8 rather than the reduced // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]). reduced_tx_set: bool, + // lane-txselect: this frame header's own `tx_mode == TxMode::Select` + // bit (spec 5.9.14). Together with `reduced_tx_set` it is stashed in a + // thread-local by [`set_inter_tx_mode`] rather than threaded through + // `decode_inter_block`'s forty parameters -- both are frame-constant, and + // only [`read_block_tx_size`]/the var-tx residual loop read them. + tx_select: bool, // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/ // `allow_warped_motion` bits, threaded to every `decode_inter_block`/ // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`). @@ -13753,6 +14416,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // param -- only `q_present`/`q_res` are read. delta: DeltaParams, ) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> { + set_inter_tx_mode(tx_select, reduced_tx_set); let tpl_frame = tpl_field.map(|field| TplFrameArgs { field, order_hint_bits, diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 798be65d..82e5486b 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -64,7 +64,8 @@ const REFUSALS: &[&str] = &[ "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 frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)", + "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)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 06737bf3..7104356f 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -225,24 +225,13 @@ pub fn decode_stream(data: &[u8]) -> Result> { // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so // a `cdef_bits > 0` stream no longer needs this refusal. - // 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", - "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)", - )); - } + // Both frame types now read their transform size under + // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads + // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's + // `decode_inter_block`/`decode_inter_block8` read the recursive + // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the + // blanket inter-frame refusal that used to stand here is gone. What + // remains refused is named at its own site in `read_block_tx_size`. // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`, // libaom decodemv.c): three more per-block/per-SB symbols this crate // never reads at all, each gated by a header field this decoder @@ -679,6 +668,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.skip_mode_present, header.skip_mode_frame, header.reduced_tx_set, + header.tx_mode == TxMode::Select, header.is_motion_mode_switchable, header.allow_warped_motion, header.allow_screen_content_tools, @@ -3423,6 +3413,245 @@ mod tests { ); } + /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT + /// `--enable-tx-size-search=0`, the flag every other inter recipe in this + /// file pins off precisely to keep the stream on `TxMode::Largest`. + /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is + /// what both of the user's real films use), and an inter block's + /// transform size is then the recursive `txfm_split` tree of spec + /// 5.11.17 rather than one whole-block transform. A stream that decoded + /// pixel-exact while every `txfm_split` symbol resolved to "no split" + /// would prove nothing (it is `TxMode::Largest` by another name), so this + /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read + /// AND at least one split actually taken. Exhausting every attempt is a + /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate. + #[test] + fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() { + tx_select_inter_gate(8); + } + + /// The 10-bit arm of the gate above (lane-txselect r2): both of the + /// user's films are `yuv420p10le` and var-tx is exactly the tool they + /// use, so an 8-bit-only proof would not reach them. Same recipe plus + /// `-b 10 --input-bit-depth=10`. + #[test] + fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() { + tx_select_inter_gate(10); + } + + fn tx_select_inter_gate(bit_depth: u32) { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 4usize); + let mut refusals = Vec::new(); + for attempt in 0..40u32 { + let seed = 42 + attempt; + // Detail is what makes aomenc's RD prefer a split transform; a + // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s + // fractal boundary is the same source the sibling intra tx-select + // gate uses, at a different `start_scale` per attempt. + let source = format!( + "mandelbrot=size=64x64:start_scale={}:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + // Desaturated chroma: `uv_mode` stays DC_PRED, so the + // still-refused directional-chroma gap never fires and + // luma detail alone drives the transform split. + "-vf", + "hue=s=0", + "-pix_fmt", + if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }, + // y4m carries no official 10-bit tag; ffmpeg writes one + // only under `-strict -1` (a no-op at 8 bit). + "-strict", + "-1", + "-t", + "0.16", + "-f", + "yuv4mpegpipe", + "-strict", + "-1", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_args: &[&str] = if bit_depth == 10 { + &["-b", "10", "--input-bit-depth=10"] + } else { + &[] + }; + let mut child = Command::new(aomenc_path()) + .args(depth_args) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=55", + "--cpu-used=0", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--enable-order-hint=0", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-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", + // DELIBERATELY ABSENT: --enable-tx-size-search=0. + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + // Sub-16 inter partitions are a separate named refusal + // (this decoder codes no inter block below 16x16 through + // the square path this gate drives), and detailed content + // makes aomenc's RD reach for them on nearly every seed. + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let (reads_before, hits_before) = + (decode::txfm_split_reads(), decode::txfm_split_hits()); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "tx-select inter decode failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + }; + let (reads, hits) = ( + decode::txfm_split_reads() - reads_before, + decode::txfm_split_hits() - hits_before, + ); + if hits == 0 { + refusals.push(format!( + "seed {seed}: decoded, 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) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + eprintln!( + "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}" + ); + // Name the first differing sample before the assert fires: a + // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for + // locating a desync. + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + for (plane, (g, w)) in [ + ("Y", (&got.y, &want.y)), + ("U", (&got.u, &want.u)), + ("V", (&got.v, &want.v)), + ] { + let stride = if plane == "Y" { width } else { width / 2 }; + if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { + eprintln!( + "txselect gate seed={seed}: frame {i} {plane} first diff at \ + ({}, {}) got {} want {} ({} samples differ)", + at % stride, + at / stride, + g[at], + w[at], + g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), + ); + let coords: Vec = g + .iter() + .zip(w.iter()) + .enumerate() + .filter(|(_, (a, b))| a != b) + .take(12) + .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride)) + .collect(); + eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}"); + } + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); + } + return; + } + panic!( + "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}", + refusals.join("\n") + ); + } + /// lane-chroma r2 stage 1: a real aomenc key frame with /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`) /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still- diff --git a/lanes/txselect-r1.report.md b/lanes/txselect-r1.report.md new file mode 100644 index 00000000..d6a1cc27 --- /dev/null +++ b/lanes/txselect-r1.report.md @@ -0,0 +1,128 @@ +# lane-txselect r1 — inter var-tx (`TxMode::Select`), spec 5.11.17 + +Branch `lane-txselect`, commit `138c558` (on top of the orchestrator's WIP +snapshot `16d83e4`, itself off main `3808cf8`). + +## What changed + +- `crates/ec-av1/src/decode.rs` + - `read_block_tx_size` / `read_var_tx_size` / `txfm_partition_ctx` / + `txfm_partition_update` / `set_txfm_ctxs` — the recursive `txfm_split` + tree, max square transform down to `MAX_VARTX_DEPTH = 2`, ported against + `av1/decoder/decodeframe.c:1029-1090` and `av1/common/av1_common_int.h` + (WIP snapshot; verified line by line against the oracle source this round). + - `TXFM_CTX_INIT = 64` (`decode.rs`, next to `MAX_VARTX_DEPTH`) — **root + cause of the first gate failure this round**. The WIP initialised + `Neighbours::above_txfm`/`left_txfm` to 0 with a comment claiming that is + "libaom's own tile-start value". It is not: + `av1_common_int.h:1624` memsets the above txfm row to + `tx_size_wide[TX_SIZES_LARGEST]` and `:1632` the left buffer to + `tx_size_high[TX_SIZES_LARGEST]` — 64. An unwritten neighbour reads as the + *widest* transform, so every frame-edge block took the wrong + `txfm_partition` context. + - `read_inter_luma8` + `split8` in `decode_inter_block8` — the 8x8 inter + leaf now reads its own `txfm_split` symbol (a `BLOCK_8X8` does signal one) + and, when it splits, decodes four 4x4 units, keeping plane-0 neighbour + context per unit across the tail `record_mi`. All three of that function's + branches (compound, single-ref, intra-in-inter) now call + `read_block_tx_size`; without this an 8x8 inter block under `Select` + desynced at its first coefficient. + - two narrow refusals at their own site: a var-tx leaf larger than 32x32 (no + 64-point *inter* coefficient tables here) and an intra block in an inter + frame whose `tx_depth` splits (that path predicts the whole block at once). +- `crates/ec-av1/src/cdf.rs`, `cdf_state.rs` (WIP): `TXFM_PARTITION` (21 + contexts) in the table set, adaptation and the per-frame counter reset; + `Luma4Inter`/`Luma4InterSet1` coefficient sets. +- `crates/ec-av1/src/stream.rs` + - the blanket refusal *"an inter frame using TxMode::Select …"* is deleted, + and `tx_mode == TxMode::Select` is threaded into + `decode_inter_frame_tile_with_cdfs` (new `tx_select` param → thread-local + `set_inter_tx_mode`). + - new gate `a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact`. +- `crates/ec-av1/src/refusal_inventory.rs`: −1 blanket refusal, +2 narrow ones. + `gate_coverage.rs` needs no change: it derives only `--enable-*` tool flags, + and `--enable-tx-size-search` is *present* (as `=0`) in the sibling gates, so + the tool was never on its `NEVER_EXERCISED` list. + +## How the existing inter gates restricted tx-mode + +`--enable-tx-size-search=0` — it appears **39** times in `stream.rs` +(`grep -c '"--enable-tx-size-search=0"'`), i.e. every inter gate. That flag is +exactly what pins a stream to `TxMode::Largest`. The new gate is the same +recipe as `a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact` +with that flag DELIBERATELY ABSENT (plus `--min-partition-size=16`, because +detailed content otherwise makes aomenc pick sub-16 inter partitions — a +separate, already-named refusal, hit on 30+ of 40 seeds). + +## Gate result — RED, honestly + +``` +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-txselect EC_AV1_REQUIRE_AOMENC=1 \ + cargo test -p ec-av1 --lib a_real_aomenc_inter_sequence_with_tx_select +``` + +EVIDENCE: cargo test stderr (seed 43) | aomenc default tx-mode, 4-frame 64x64 +mandelbrot inter sequence, decode_stream vs ffmpeg per frame | +`txfm_split reads=22 splits taken=8`; frame 0 (key) and frame 1 (first inter +frame, var-tx active) pixel-exact on Y/U/V; frame 2 Y first differs at (59,14) +`got 143 want 144`, 1774/4096 samples; frame 3 differs from (0,0). + +So: the var-tx read + per-TU residual path is real and correct for a whole key +frame and a whole inter frame, and the gate fires (8 splits actually taken). +It does not yet pass. **No refusal should be considered "proven lifted" on this +evidence** — the branch is not merge-ready. + +Before the `TXFM_CTX_INIT` fix the same gate failed at frame 2 (32,0) with +3209/4096 samples differing; after it, the first divergence moved to (59,14) +with 1774 — the fix is a real advance, not a reshuffle. + +## Residue + +- fix-now (next round, blocks the merge): frame 2 divergence. Shape: rows 0..13 + of frame 2 match everywhere; the first differing samples are on rows 14/15 + (x 34..62) with deltas of 1..3, then the error spreads to 43% of the frame. + That is a late-in-block divergence inside the second/third 16x16..32x32 + block of the top block row, not a whole-frame desync from symbol 0. + Next step is the ledger's blessed rung, not more reasoning: instrumented + `aomdec` range ladder (`EC_TRACE=1`) vs our `EC_TRACE_MODE_STEP` on frame 2 + only, comparing msac RANGE element by element (never `tell()`), starting at + the first block of frame 2. Prime suspects, in order: (1) `txfm_partition` + CDF *adaptation* forwarded into frame 2 (frame 1 is clean, frame 2 is the + first frame that inherits an adapted copy — the "CDF counter not reset" + class, though `reset_counts` does list it); (2) `tx_size_context` for an + intra block in an inter frame, which still reads the deblock `tx_grid` + instead of libaom's `above_txfm_context`/`left_txfm_context` with the + `is_inter_block` → block-size override (`pred_common.h:342-371`) — a known, + unported divergence introduced the moment inter neighbours carry split + transforms; (3) the deblock tx grid written per var-tx leaf. +- deferred(the frame-2 fix): 10-bit gate — his films are `yuv420p10le` and + 10-bit is a separate standing refusal (`Picture` planes are `Vec`), so a + 10-bit tx-select gate would prove nothing this round. +- deferred(the frame-2 fix): film probe (`decode_probe` on 0.4 s of each film) + — pointless until the 8-bit gate is green. +- accepted (documented corner-cut, in the code): a var-tx block's chroma + deblock edges read `tx_h_grid / 2`, i.e. they follow the luma leaves even + though the block's uv transform is not split. + +## Suite totals + +``` +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-txselect cargo test -p ec-av1 --lib +test result: FAILED. 267 passed; 1 failed; 23 ignored; 0 measured; 0 filtered out; +finished in 1146.75s +``` + +The single failure is this lane's own new gate +(`a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact`), red for the +frame-2 reason above. No pre-existing test regressed: the same 267 pass with the +blanket `TxMode::Select` inter refusal removed. + +Measured at `138c558`. Two commits landed after it: +- `ecc71ec` — this report only, no code. +- `3c174b6` — `tx_size_context_txfm`, reachable from exactly one call site + (`read_block_tx_size`'s intra branch, new code this lane); `read_tx_size`'s + new `ctx_override` is `None` at both pre-existing key-frame call sites + (`decode.rs:4934`, `:5346`), so it cannot move any of the 267. Re-verified + after it: the gate (still red, byte-identical failure), plus + `refusal_inventory` + `gate_coverage` (5 passed, 0 failed). The full 1146 s + suite was NOT re-run at `3c174b6`. diff --git a/lanes/txselect-r2.report.md b/lanes/txselect-r2.report.md new file mode 100644 index 00000000..e527c9dd --- /dev/null +++ b/lanes/txselect-r2.report.md @@ -0,0 +1,114 @@ +# lane-txselect r2 — the frame-2 divergence: a missing eob_pt class dimension + +Branch `lane-txselect`, on top of `fb6b74f` (r1's report commit, off main `3808cf8`). + +## Root cause + +`read_eob` picks between the 2D and the `TX_CLASS_HORIZ`/`TX_CLASS_VERT` +eob_pt CDF (`decode.rs:1384`, libaom `decodetxb.c:200` +`eob_multi_ctx = (tx_class == TX_CLASS_2D) ? 0 : 1`). Only the 4x4 and 8x8 +LUMA sets ever carried a class-1 sibling (`eob_pt_16_luma_class1`, +`eob_pt_64_luma_class1`, added by lane-av1tx4 r5); every other `TxbSet` had +`eob_pt_class1: None`, so a 1D-class TU silently read (and adapted) the +class-0 table. Instance of [[cdf-row-held-constant]] / the class dimension +half of [[table-indexed-by-raw-size]]. + +`TxMode::Select` is what made it reachable: a 32x32 inter block's var-tx +leaf is a **16x16** luma TU, whose inter tx set is +`EXT_TX_SET_DTT9_IDTX_1DDCT` — the only 16x16 set holding `V_DCT`/`H_DCT`. +(16x16 intra reads `TX_SET_INTRA_2`, all-2D; 32x32 and up read +`DCT_IDTX`/`DCTONLY`, also all-2D — so 16x16 inter is exactly the hole.) + +Sweep of the same shape: every reachable size now carries its sibling — +`eob_pt_256_luma_class1` plus the three chroma ones +(`eob_pt_256/64/16_chroma_class1`; an *inter* block's chroma TU inherits its +luma unit's `tx_type`, so 1D classes reach chroma too). 32-point and larger +need none, by their tx sets. + +## What changed + +- `crates/ec-av1/src/cdf.rs` (EOF): `EOB_PT_256_LUMA_CLASS1*`, + `EOB_PT_256_CHROMA_CLASS1*`, `EOB_PT_64_CHROMA_CLASS1*`, + `EOB_PT_16_CHROMA_CLASS1*` — `av1_default_eob_multi{256,64,16}_cdfs[q][plane][1]`, + `token_cdfs.h:773/811/851`, all four q-contexts. +- `crates/ec-av1/src/cdf_state.rs`: the four fields, their `pick(q_ctx, …)` + defaults, their lines in the per-frame counter reset (class + [[cdf-counter-not-reset]]), and `eob_pt_class1: Some(…)` on + `Luma16`/`Luma16Inter`/`Luma16InterSet1`/`Chroma16`/`Chroma8`/`Chroma4`. +- `crates/ec-av1/src/stream.rs`: the gate body becomes + `tx_select_inter_gate(bit_depth)` with two `#[test]` arms — the existing + 8-bit one and a new `…_decodes_pixel_exact_10bit` (`-b 10 + --input-bit-depth=10`, `yuv420p10le` fixture under `-strict -1`, compared + through `ffmpeg_decode_sequence_10bit`). + +No refusal string changed this round (r1 lifted the blanket +`TxMode::Select` one; it is now actually proven). + +## Method (what found it, in order) + +1. Pinned the r1 failing stream: seed-43 recipe → `s43.obu`, + sha256 `d0ba79bbdd34317fa3864c824026e0b905dea0d9add540e646281a1ae23e3d57`. +2. `EC_AV1_PREFILT_DUMP` ours vs instrumented aomdec: frame 2 already + differed BEFORE the loop filter (1721 luma samples, chroma clean) — so + not the deblock tx grid, which was r1's leading suspect. +3. `EC_TRACE_MODE_STEP` matched everywhere (it only instruments the intra + path); `EC_TRACE_COEFF` on both, compared by msac RANGE: the first + divergent element is the **`eob` of the 16x16 luma var-tx leaf at + mi (4,8)** of the 32x32 block at mi (0,8) — entry `rng=42600` + (`all_zero`) and `rng=33264` (`tx_type`) identical, then ref + `eob=248 rng=65032` vs ours `eob=247 rng=56584`. +4. `EC_EOBPT_DUMP` on aomdec gave `tx_size=2 eob_multi_size=4 txs_ctx=2`; + ours read `tx_type value=1 len=13` = `V_DCT` (class VERT) yet took the + class-0 CDF. `eob_pt_class1: None` on `Luma16InterSet1` was the line. + +## Gate — GREEN, both arms + +``` +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-txselect EC_AV1_REQUIRE_AOMENC=1 \ + cargo test -p ec-av1 --lib a_real_aomenc_inter_sequence_with_tx_select -- --nocapture +``` + +EVIDENCE: cargo test stderr | 4-frame 64x64 mandelbrot inter sequence, aomenc +default tx-mode (`--enable-tx-size-search` deliberately absent), decode_stream +vs ffmpeg per frame, 8-bit and 10-bit arms | `txselect gate 8-bit seed=42: +txfm_split reads=22 splits taken=3`, `txselect gate 10-bit seed=42: +txfm_split reads=25 splits taken=6`, `test result: ok. 2 passed; 0 failed`. + +EVIDENCE: /tmp/…/scratchpad/{ref,ours}.f0..f3 | `EC_AV1_PREFILT_DUMP` on +instrumented aomdec and on `decode_probe s43.obu` (r1's own failing seed-43 +stream) | `cmp -l` 0 differing bytes on all four frames' Y+U+V pre-filter +planes (was 0 / 0 / 1721 / 3647 before the fix). + +10-bit note: the 10-bit arm passes, so this lane owes lane-hbdinter nothing. + +## Suite + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (full, this branch): +**269 passed / 0 failed / 23 ignored**, 877.86s. The earlier run of the same +command before the 10-bit arm was added was +**268 passed / 0 failed / 23 ignored** (r1: 267/1/23, the one failure being +this lane's gate). + +## Film probe (0.4 s, `-c:v copy -f obu`) + +- ReelC: `REFUSED: unsupported: AV1 tile (a 32x32 partition type this decoder + does not code (value=4))` +- ReelB: `REFUSED: unsupported: AV1 tile (a partition below 8x8 (this + decoder codes no leaf smaller than 8x8))` + +Both are other lanes' refusals, reached in the first tile's partition tree — +strictly upstream of anything this round touched, so the "before" value is +identical by construction (not separately rebuilt: `deferred(nothing)` — +measuring it would mean a second full build of `fb6b74f` for a string that +cannot move). + +## Residue + +- accepted (documented corner-cut, unchanged from r1, `decode.rs:11447`): a + var-tx block's **chroma** deblock edges follow `tx_h_grid / 2`, i.e. the + luma leaves, though the block's uv transform is not split. Ceiling: a + chroma deblock edge at a luma-only transform seam. Not observable in this + gate (`--enable-cdef=0`, and both arms are chroma-exact through 4 frames); + upgrade path = a per-plane tx grid, not a scalar. +- accepted: the two narrow refusals r1 added stay (a var-tx leaf >32x32; an + intra block in an inter frame whose `tx_depth` splits).