diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 4c9d5c58..e9a66bad 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -722,3 +722,238 @@ pub const TXB_SKIP_CHROMA_32: [[u16; 3]; 3] = pub const EOB_PT_1024_CHROMA: [u16; 12] = [ 9577, 12466, 17739, 20750, 22061, 23215, 24601, 25483, 25843, 32056, 32768, 0, ]; +/// `Default_Txb_Skip_Cdf[2][2][0]`: the all-zero flag of a 16x16 luma transform, whose only context is zero because the transform covers its whole block. +pub const TXB_SKIP_LUMA_16: [u16; 3] = [32363, 32768, 0]; + +/// `Default_Txb_Skip_Cdf[2][1][7..10]`: the all-zero flag of an 8x8 chroma transform. +pub const TXB_SKIP_CHROMA_8: [[u16; 3]; 3] = + [[3050, 32768, 0], [14603, 32768, 0], [25155, 32768, 0]]; + +/// `Default_Eob_Pt_256_Cdf[2][0][0]`: the end-of-block group of a 16x16 luma transform. +pub const EOB_PT_256_LUMA: [u16; 10] = + [3089, 3920, 6038, 9460, 14266, 19881, 25766, 29176, 32768, 0]; + +/// `Default_Eob_Pt_64_Cdf[2][1][0]`: the end-of-block group of an 8x8 chroma transform. +pub const EOB_PT_64_CHROMA: [u16; 8] = [15050, 17126, 21410, 24886, 28156, 30726, 32768, 0]; + +/// `Default_Eob_Extra_Cdf[2][2][0]`: the top offset bit inside a 16x16 luma transform's end-of-block group. +pub const EOB_EXTRA_LUMA_16: [[u16; 3]; 9] = [ + [19833, 32768, 0], + [21502, 32768, 0], + [17485, 32768, 0], + [20267, 32768, 0], + [18353, 32768, 0], + [23329, 32768, 0], + [21478, 32768, 0], + [16384, 32768, 0], + [16384, 32768, 0], +]; + +/// `Default_Eob_Extra_Cdf[2][1][1]`: the same, for an 8x8 chroma transform. +pub const EOB_EXTRA_CHROMA_8: [[u16; 3]; 9] = [ + [20536, 32768, 0], + [20664, 32768, 0], + [20625, 32768, 0], + [19123, 32768, 0], + [14862, 32768, 0], + [16384, 32768, 0], + [16384, 32768, 0], + [16384, 32768, 0], + [16384, 32768, 0], +]; + +/// `Default_Coeff_Base_Cdf[2][2][0]`: a 16x16 luma coefficient's base level. +pub const COEFF_BASE_LUMA_16: [[u16; 5]; 42] = [ + [9800, 17635, 21073, 32768, 0], + [26153, 31885, 32527, 32768, 0], + [15038, 27852, 31006, 32768, 0], + [8718, 20564, 26486, 32768, 0], + [5128, 14076, 20514, 32768, 0], + [2636, 7566, 11925, 32768, 0], + [27551, 32504, 32701, 32768, 0], + [18310, 30054, 32100, 32768, 0], + [10211, 23420, 29082, 32768, 0], + [6222, 16876, 23916, 32768, 0], + [3462, 9954, 15498, 32768, 0], + [29991, 32633, 32721, 32768, 0], + [19883, 30751, 32201, 32768, 0], + [11141, 24184, 29285, 32768, 0], + [6420, 16940, 23774, 32768, 0], + [3392, 9753, 15118, 32768, 0], + [28465, 32616, 32712, 32768, 0], + [19850, 30702, 32244, 32768, 0], + [10983, 24024, 29223, 32768, 0], + [6294, 16770, 23582, 32768, 0], + [3244, 9283, 14509, 32768, 0], + [30023, 32717, 32748, 32768, 0], + [22940, 32032, 32626, 32768, 0], + [14282, 27928, 31473, 32768, 0], + [8562, 21327, 27914, 32768, 0], + [4846, 13393, 19919, 32768, 0], + [29981, 32590, 32695, 32768, 0], + [20465, 30963, 32166, 32768, 0], + [11479, 23579, 28195, 32768, 0], + [5916, 15648, 22073, 32768, 0], + [3031, 8605, 13398, 32768, 0], + [31146, 32691, 32739, 32768, 0], + [23106, 31724, 32444, 32768, 0], + [13783, 26738, 30439, 32768, 0], + [7852, 19468, 25807, 32768, 0], + [3860, 11124, 16853, 32768, 0], + [31014, 32724, 32748, 32768, 0], + [23629, 32109, 32628, 32768, 0], + [14747, 28115, 31403, 32768, 0], + [8545, 21242, 27478, 32768, 0], + [4574, 12781, 19067, 32768, 0], + [8192, 16384, 24576, 32768, 0], +]; + +/// `Default_Coeff_Base_Cdf[2][1][1]`: an 8x8 chroma coefficient's base level. +pub const COEFF_BASE_CHROMA_8: [[u16; 5]; 42] = [ + [11016, 22111, 26794, 32768, 0], + [25946, 32357, 32677, 32768, 0], + [17890, 30452, 32252, 32768, 0], + [11678, 25142, 29816, 32768, 0], + [6720, 17534, 24584, 32768, 0], + [4230, 11665, 17820, 32768, 0], + [28400, 32623, 32747, 32768, 0], + [21164, 31668, 32575, 32768, 0], + [13572, 27388, 31182, 32768, 0], + [8234, 20750, 27358, 32768, 0], + [5065, 14055, 20897, 32768, 0], + [28981, 32547, 32705, 32768, 0], + [18681, 30543, 32239, 32768, 0], + [10919, 24075, 29286, 32768, 0], + [6431, 17199, 24077, 32768, 0], + [3819, 10464, 16618, 32768, 0], + [26870, 32467, 32693, 32768, 0], + [19041, 30831, 32347, 32768, 0], + [11794, 25211, 30016, 32768, 0], + [6888, 18019, 24970, 32768, 0], + [4370, 12363, 18992, 32768, 0], + [29578, 32670, 32744, 32768, 0], + [23159, 32007, 32613, 32768, 0], + [15315, 28669, 31676, 32768, 0], + [9298, 22607, 28782, 32768, 0], + [6144, 15913, 22968, 32768, 0], + [28110, 32499, 32669, 32768, 0], + [21574, 30937, 32015, 32768, 0], + [12759, 24818, 28727, 32768, 0], + [6545, 16761, 23042, 32768, 0], + [3649, 10597, 16833, 32768, 0], + [28163, 32552, 32728, 32768, 0], + [22101, 31469, 32464, 32768, 0], + [13160, 25472, 30143, 32768, 0], + [7303, 18684, 25468, 32768, 0], + [5241, 13975, 20955, 32768, 0], + [28400, 32631, 32744, 32768, 0], + [22104, 31793, 32603, 32768, 0], + [13557, 26571, 30846, 32768, 0], + [7749, 19861, 26675, 32768, 0], + [4873, 14030, 21234, 32768, 0], + [8192, 16384, 24576, 32768, 0], +]; + +/// `Default_Coeff_Base_Eob_Cdf[2][2][0]`: the base level of the last coefficient of a 16x16 luma transform. +pub const COEFF_BASE_EOB_LUMA_16: [[u16; 4]; 4] = [ + [12854, 29093, 32768, 0], + [32272, 32558, 32768, 0], + [32667, 32729, 32768, 0], + [32306, 32585, 32768, 0], +]; + +/// `Default_Coeff_Base_Eob_Cdf[2][1][1]`: the same, for an 8x8 chroma transform. +pub const COEFF_BASE_EOB_CHROMA_8: [[u16; 4]; 4] = [ + [27116, 30842, 32768, 0], + [31971, 32598, 32768, 0], + [32088, 32576, 32768, 0], + [32067, 32664, 32768, 0], +]; + +/// `Default_Coeff_Br_Cdf[2][2][0]`: the base-range tail of a 16x16 luma coefficient. +pub const COEFF_BR_LUMA_16: [[u16; 5]; 21] = [ + [14438, 20798, 24089, 32768, 0], + [12621, 19203, 23097, 32768, 0], + [8177, 14125, 18402, 32768, 0], + [5674, 10501, 14456, 32768, 0], + [4236, 8239, 11733, 32768, 0], + [3447, 6750, 9806, 32768, 0], + [1986, 3950, 5864, 32768, 0], + [16208, 22099, 24930, 32768, 0], + [16537, 24025, 27585, 32768, 0], + [12780, 20381, 24867, 32768, 0], + [9767, 16612, 21416, 32768, 0], + [7686, 13738, 18398, 32768, 0], + [6333, 11614, 15964, 32768, 0], + [3941, 7571, 10836, 32768, 0], + [22819, 27422, 29202, 32768, 0], + [22224, 28514, 30721, 32768, 0], + [17660, 25433, 28913, 32768, 0], + [13574, 21482, 26002, 32768, 0], + [10629, 17977, 22938, 32768, 0], + [8612, 15298, 20265, 32768, 0], + [5607, 10491, 14596, 32768, 0], +]; + +/// `Default_Coeff_Br_Cdf[2][1][1]`: the base-range tail of an 8x8 chroma coefficient. +pub const COEFF_BR_CHROMA_8: [[u16; 5]; 21] = [ + [14433, 21155, 24938, 32768, 0], + [14658, 21716, 25545, 32768, 0], + [9923, 16824, 21557, 32768, 0], + [6982, 13052, 17721, 32768, 0], + [5419, 10503, 15050, 32768, 0], + [4852, 9162, 13014, 32768, 0], + [3271, 6395, 9630, 32768, 0], + [22210, 27833, 30109, 32768, 0], + [20750, 27368, 29821, 32768, 0], + [16894, 24828, 28573, 32768, 0], + [13247, 21276, 25757, 32768, 0], + [10038, 17265, 22563, 32768, 0], + [8587, 14947, 20327, 32768, 0], + [5645, 11371, 15252, 32768, 0], + [22027, 27526, 29714, 32768, 0], + [23098, 29146, 31221, 32768, 0], + [19886, 27341, 30272, 32768, 0], + [15609, 23747, 28046, 32768, 0], + [11993, 20065, 24939, 32768, 0], + [9637, 18267, 23671, 32768, 0], + [7625, 13801, 19144, 32768, 0], +]; + +/// `Default_Partition_Cdf[0..4]`: the partition symbol of a 16x16 block. +pub const PARTITION_W16: [[u16; 11]; 4] = [ + [ + 15597, 20929, 24571, 26706, 27664, 28821, 29601, 30571, 31902, 32768, 0, + ], + [ + 7925, 11043, 16785, 22470, 23971, 25043, 26651, 28701, 29834, 32768, 0, + ], + [ + 5414, 13269, 15111, 20488, 22360, 24500, 25537, 26336, 32117, 32768, 0, + ], + [ + 2662, 6362, 8614, 20860, 23053, 24778, 26436, 27829, 31171, 32768, 0, + ], +]; + +/// The transform type of a 16x16 intra luma transform, as an index into the +/// spec's `Tx_Type_Intra_Inv_Set2`, indexed by the block's luma mode. +/// +/// A 16x16 transform is the only size this writer codes whose transform-type +/// set holds more than one type, so it is the only one that codes the symbol: +/// 32x32 and 64x64 are DCT-only by spec 5.11.40's `get_tx_set`. +pub const INTRA_TX_TYPE_SET2_16: [[u16; 6]; 13] = [ + [1127, 12814, 22772, 27483, 32768, 0], + [145, 6761, 11980, 26667, 32768, 0], + [362, 5887, 11678, 16725, 32768, 0], + [385, 15213, 18587, 30693, 32768, 0], + [25, 2914, 23134, 27903, 32768, 0], + [60, 4470, 11749, 23991, 32768, 0], + [37, 3332, 14511, 21448, 32768, 0], + [157, 6320, 13036, 17439, 32768, 0], + [119, 6719, 12906, 29396, 32768, 0], + [47, 5537, 12576, 21499, 32768, 0], + [269, 6076, 11258, 23115, 32768, 0], + [83, 5615, 12001, 17228, 32768, 0], + [1968, 5556, 12023, 18547, 32768, 0], +]; diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 20c15643..bc78a083 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -20,6 +20,10 @@ pub(crate) enum TxbSet { Luma32, /// The 64x64 luma transform of a whole superblock, scanned as a 32x32. Luma64, + /// The 16x16 luma transform of a 16x16 block. + Luma16, + /// The 8x8 transform of a chroma plane of a 16x16 block. + Chroma8, /// The 16x16 transform of a chroma plane of a 32x32 block. Chroma16, /// The 32x32 transform of a chroma plane of a whole superblock. @@ -45,6 +49,8 @@ pub(crate) struct TxbTables<'a> { pub br: &'a mut [[u16; 5]; 21], /// The sign of the DC. pub dc_sign: &'a mut [[u16; 3]; 3], + /// The transform type, for the one size whose set holds more than one. + pub tx_type: Option<&'a mut [u16; 6]>, } /// Every table a key frame's tile writer adapts. @@ -63,6 +69,32 @@ pub(crate) struct Cdfs { pub uv_mode_cfl: [[u16; 15]; 13], /// 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 all-zero flag of an 8x8 chroma transform. + pub txb_skip_chroma_8: [[u16; 3]; 3], + /// The end-of-block group of a 16x16 luma transform. + pub eob_pt_256_luma: [u16; 10], + /// The end-of-block group of an 8x8 chroma transform. + pub eob_pt_64_chroma: [u16; 8], + /// The end-of-block offset bit of a 16x16 luma transform. + pub eob_extra_luma_16: [[u16; 3]; 9], + /// The same, for an 8x8 chroma transform. + pub eob_extra_chroma_8: [[u16; 3]; 9], + /// The base level of a 16x16 luma coefficient. + pub base_luma_16: [[u16; 5]; 42], + /// The base level of an 8x8 chroma coefficient. + pub base_chroma_8: [[u16; 5]; 42], + /// The last coefficient's base level, for a 16x16 luma transform. + pub base_eob_luma_16: [[u16; 4]; 4], + /// The same, for an 8x8 chroma transform. + pub base_eob_chroma_8: [[u16; 4]; 4], + /// The base-range tail of a 16x16 luma coefficient. + pub br_luma_16: [[u16; 5]; 21], + /// The base-range tail of an 8x8 chroma coefficient. + pub br_chroma_8: [[u16; 5]; 21], + /// The partition symbol of a 16x16 block. + pub partition_w16: [[u16; 11]; 4], /// The one-context all-zero flag of a 32x32 luma transform. pub txb_skip_luma_32: [[u16; 3]; 1], /// The same, for a 64x64 luma transform. @@ -110,6 +142,8 @@ pub(crate) struct Cdfs { pub br_chroma_32: [[u16; 5]; 21], /// The DC sign of a luma coefficient, shared by both luma sets. pub dc_sign_luma: [[u16; 3]; 3], + /// The transform type of a 16x16 intra luma transform, by luma mode. + pub intra_tx_type_16: [[u16; 6]; 13], /// The DC sign of a chroma coefficient, shared by both chroma sets. pub dc_sign_chroma: [[u16; 3]; 3], } @@ -127,6 +161,19 @@ impl Cdfs { uv_mode_no_cfl: cdf::UV_MODE_NO_CFL, uv_mode_cfl: cdf::UV_MODE_CFL, angle_delta: cdf::ANGLE_DELTA, + txb_skip_luma_16: [cdf::TXB_SKIP_LUMA_16], + txb_skip_chroma_8: cdf::TXB_SKIP_CHROMA_8, + eob_pt_256_luma: cdf::EOB_PT_256_LUMA, + eob_pt_64_chroma: cdf::EOB_PT_64_CHROMA, + eob_extra_luma_16: cdf::EOB_EXTRA_LUMA_16, + eob_extra_chroma_8: cdf::EOB_EXTRA_CHROMA_8, + base_luma_16: cdf::COEFF_BASE_LUMA_16, + base_chroma_8: cdf::COEFF_BASE_CHROMA_8, + base_eob_luma_16: cdf::COEFF_BASE_EOB_LUMA_16, + base_eob_chroma_8: cdf::COEFF_BASE_EOB_CHROMA_8, + br_luma_16: cdf::COEFF_BR_LUMA_16, + br_chroma_8: cdf::COEFF_BR_CHROMA_8, + partition_w16: cdf::PARTITION_W16, txb_skip_luma_32: [cdf::TXB_SKIP_LUMA_32], txb_skip_luma_64: [cdf::TXB_SKIP_LUMA_64], txb_skip_chroma_16: cdf::TXB_SKIP_CHROMA_16, @@ -150,12 +197,13 @@ impl Cdfs { br_chroma_16: cdf::COEFF_BR_CHROMA_16, br_chroma_32: cdf::COEFF_BR_CHROMA_32, dc_sign_luma: cdf::DC_SIGN_LUMA, + intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16, dc_sign_chroma: cdf::DC_SIGN_CHROMA, } } /// The tables one table set is coded with, borrowed out of the state. - pub fn txb(&mut self, set: TxbSet) -> TxbTables<'_> { + pub fn txb(&mut self, set: TxbSet, mode: usize) -> TxbTables<'_> { match set { TxbSet::Luma32 => TxbTables { side: 32, @@ -166,6 +214,7 @@ impl Cdfs { base_eob: &mut self.base_eob_luma_32, br: &mut self.br_luma_32, dc_sign: &mut self.dc_sign_luma, + tx_type: None, }, TxbSet::Luma64 => TxbTables { side: 32, @@ -176,6 +225,29 @@ impl Cdfs { base_eob: &mut self.base_eob_luma_64, br: &mut self.br_luma_32, dc_sign: &mut self.dc_sign_luma, + tx_type: None, + }, + TxbSet::Luma16 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_256_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(&mut self.intra_tx_type_16[mode]), + }, + TxbSet::Chroma8 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_chroma_8, + eob_pt: &mut self.eob_pt_64_chroma, + eob_extra: &mut self.eob_extra_chroma_8, + base: &mut self.base_chroma_8, + base_eob: &mut self.base_eob_chroma_8, + br: &mut self.br_chroma_8, + dc_sign: &mut self.dc_sign_chroma, + tx_type: None, }, TxbSet::Chroma16 => TxbTables { side: 16, @@ -186,6 +258,7 @@ impl Cdfs { base_eob: &mut self.base_eob_chroma_16, br: &mut self.br_chroma_16, dc_sign: &mut self.dc_sign_chroma, + tx_type: None, }, TxbSet::Chroma32 => TxbTables { side: 32, @@ -196,6 +269,7 @@ impl Cdfs { base_eob: &mut self.base_eob_chroma_32, br: &mut self.br_chroma_32, dc_sign: &mut self.dc_sign_chroma, + tx_type: None, }, } } @@ -212,8 +286,8 @@ mod tests { #[test] fn the_two_luma_sets_share_the_base_range_table() { let mut cdfs = Cdfs::new(); - cdfs.txb(TxbSet::Luma64).br[0][0] = 1; - assert_eq!(cdfs.txb(TxbSet::Luma32).br[0][0], 1); + cdfs.txb(TxbSet::Luma64, 0).br[0][0] = 1; + assert_eq!(cdfs.txb(TxbSet::Luma32, 0).br[0][0], 1); } /// Both luma sets read one DC sign table, and both chroma sets another; @@ -221,12 +295,12 @@ mod tests { #[test] fn the_sign_tables_are_shared_within_a_plane_type_and_not_across() { let mut cdfs = Cdfs::new(); - cdfs.txb(TxbSet::Luma32).dc_sign[1][0] = 1; - cdfs.txb(TxbSet::Chroma16).dc_sign[2][0] = 2; - assert_eq!(cdfs.txb(TxbSet::Luma64).dc_sign[1][0], 1); - assert_eq!(cdfs.txb(TxbSet::Chroma32).dc_sign[2][0], 2); - assert_ne!(cdfs.txb(TxbSet::Chroma32).dc_sign[1][0], 1); - assert_ne!(cdfs.txb(TxbSet::Luma64).dc_sign[2][0], 2); + cdfs.txb(TxbSet::Luma32, 0).dc_sign[1][0] = 1; + cdfs.txb(TxbSet::Chroma16, 0).dc_sign[2][0] = 2; + assert_eq!(cdfs.txb(TxbSet::Luma64, 0).dc_sign[1][0], 1); + assert_eq!(cdfs.txb(TxbSet::Chroma32, 0).dc_sign[2][0], 2); + assert_ne!(cdfs.txb(TxbSet::Chroma32, 0).dc_sign[1][0], 1); + assert_ne!(cdfs.txb(TxbSet::Luma64, 0).dc_sign[2][0], 2); } /// The end-of-block table a 1024-position transform reads is shared by both @@ -235,9 +309,9 @@ mod tests { #[test] fn the_luma_end_of_block_table_is_shared_and_chromas_is_not() { let mut cdfs = Cdfs::new(); - cdfs.txb(TxbSet::Luma32).eob_pt[0] = 7; - assert_eq!(cdfs.txb(TxbSet::Luma64).eob_pt[0], 7); - assert_ne!(cdfs.txb(TxbSet::Chroma32).eob_pt[0], 7); + cdfs.txb(TxbSet::Luma32, 0).eob_pt[0] = 7; + assert_eq!(cdfs.txb(TxbSet::Luma64, 0).eob_pt[0], 7); + assert_ne!(cdfs.txb(TxbSet::Chroma32, 0).eob_pt[0], 7); } /// Every set starts from the spec's defaults, so a tile that adapts nothing @@ -245,9 +319,12 @@ mod tests { #[test] fn the_state_starts_at_the_defaults() { let mut cdfs = Cdfs::new(); - assert_eq!(cdfs.txb(TxbSet::Luma32).base[3], cdf::COEFF_BASE_LUMA_32[3]); assert_eq!( - cdfs.txb(TxbSet::Chroma16).eob_extra[2], + cdfs.txb(TxbSet::Luma32, 0).base[3], + cdf::COEFF_BASE_LUMA_32[3] + ); + assert_eq!( + cdfs.txb(TxbSet::Chroma16, 0).eob_extra[2], cdf::EOB_EXTRA_CHROMA_16[2] ); assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 4230d895..7361177a 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -22,17 +22,28 @@ use ec_av1_syntax::{ use ec_core::{Error, Result}; use crate::cdf; +use crate::cdf_state::TxbSet; use crate::frame::frame_obu; use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED}; use crate::obu::temporal_delimiter; use crate::quant::ac_q; use crate::sequence::sequence_header_obu; -use crate::tile::{BlockCoeffs, Coeff, INTRA_MODE_CTX, Superblock, sb_coeff_key_frame_tile}; +use crate::tile::{ + BlockCoeffs, Coeff, INTRA_MODE_CTX, Quadrant, Superblock, partition_bits, + sb_coeff_key_frame_tile, +}; use crate::transform::{dequant_and_inverse, forward_and_quantize}; -/// The side of the luma blocks this encoder codes, in samples. +/// The side of the larger of the two luma blocks this encoder codes, in +/// samples. const BLOCK: usize = 32; +/// The side of the smaller one, which a 32x32 block may be split into four of. +const SUB: usize = 16; + +/// The side of a superblock, which is what the partition tree starts from. +const SUPERBLOCK: usize = 64; + /// How heavily the mode search weighs rate against squared error, in units of /// the quantizer's reconstruction step squared per bit. /// @@ -57,6 +68,16 @@ fn lambda_scale() -> f64 { } } +/// Whether a 32x32 block may be split into four 16x16 ones when the trial says +/// four cost less. Set from the measurement in the lane report. +const SPLIT_BLOCKS: bool = true; + +/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides +/// by calling [`encode_key_frame_inner`] both ways. +fn split_blocks() -> bool { + SPLIT_BLOCKS +} + /// One 8-bit planar 4:2:0 picture. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Picture { @@ -117,7 +138,8 @@ pub struct Encoded { /// reconstruction, which its prediction was built on. pub reconstruction: Picture, /// The luma intra mode each block was coded under, in the order the blocks - /// are coded — raster order among the quadrants of each superblock. + /// are coded — raster order among the quadrants of each superblock, and + /// among the four 16x16 blocks of a quadrant that was split. pub modes: Vec, } @@ -284,7 +306,9 @@ impl Plane<'_> { /// levels, the block the decoder would reconstruct, the squared error /// against the source and an estimate of what the levels cost in bits. fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial { - let At { x, y, side, reach } = at; + let At { + x, y, side, reach, .. + } = at; let (above, left, corner) = self.edges(x, y, side, reach); let mut prediction = vec![0u8; side * side]; crate::intra::predict( @@ -321,12 +345,9 @@ impl Plane<'_> { } } // What the levels cost is priced through the same CDFs the tile writer - // will code them with, so the search ranks modes by the bits they - // actually spend. Chroma blocks are not searched, so only the 32x32 - // luma table is asked for. - let bits = if side != BLOCK { - 0.0 - } else if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { + // will code them with, so the search ranks modes -- and the partition + // trial ranks trees -- by the bits they actually spend. + let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { // What the search used before it could price a block exactly: a // level costs its magnitude's width plus a sign and a run. Kept // reachable from the sweep so the two rate terms can be compared @@ -337,7 +358,7 @@ impl Plane<'_> { .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() } else { - crate::tile::luma_32_coeff_bits(&levels) + crate::tile::coeff_bits(&levels, at.set) }; Trial { levels, @@ -355,16 +376,44 @@ impl Plane<'_> { } } - /// Codes one block under a fixed mode, committing it. - fn code_block(&mut self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Vec { + /// Codes one block under a fixed mode, committing it, and hands back what + /// it cost: its squared error and the bits its levels spend. + fn code_block( + &mut self, + at: At, + mode: u8, + base_q_idx: u8, + deadzone: f64, + ) -> (Vec, f64, f64) { let trial = self.trial(at, mode, base_q_idx, deadzone); self.commit(at.x, at.y, at.side, &trial); - coeffs(&trial.levels, at.side) + (coeffs(&trial.levels, at.side), trial.sse, trial.bits) + } + + /// The reconstructed samples of one square, so that a partition trial can + /// be undone. + fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec { + (y..y + side) + .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec()) + .collect() + } + + /// Puts a snapshot back. + fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) { + for row in 0..side { + self.reconstruction[(y + row) * self.width + x..][..side] + .copy_from_slice(&samples[row * side..][..side]); + } } /// Codes one block under every mode the search offers and commits the one /// whose squared error and estimated rate come out cheapest. - fn search_block(&mut self, at: At, search: &Search, mode_bits: &[f64; 13]) -> (Vec, u8) { + fn search_block( + &mut self, + at: At, + search: &Search, + mode_bits: &[f64; 13], + ) -> (Vec, u8, f64) { let mut best: Option<(f64, u8, Trial)> = None; for &mode in search.modes { let trial = self.trial(at, mode, search.base_q_idx, search.deadzone); @@ -376,9 +425,9 @@ impl Plane<'_> { best = Some((cost, mode, trial)); } } - let (_, mode, trial) = best.expect("the search offers at least one mode"); + let (cost, mode, trial) = best.expect("the search offers at least one mode"); self.commit(at.x, at.y, at.side, &trial); - (coeffs(&trial.levels, at.side), mode) + (coeffs(&trial.levels, at.side), mode, cost) } } @@ -390,34 +439,44 @@ struct At { y: usize, side: usize, reach: Reach, + /// Which of the tile writer's coefficient tables this block's levels are + /// coded with, and so which the search prices them through. + set: TxbSet, } /// Which of the samples past a block's own edges the decoder has decoded by /// the time it predicts the block, and so which a directional mode may read. /// /// The decoder derives these from its `BlockDecoded` flags, which are cleared -/// per superblock (`clear_block_decoded_flags`, spec 7.4): the row above the -/// superblock counts as decoded out to the end of the *tile*, while the column -/// to its left counts only as far as the superblock's own height, and every -/// position inside the superblock starts undecoded. For the four 32x32 -/// quadrants of a 64x64 superblock that comes to: the samples above-right are -/// decoded for all but the last quadrant -- the one whose above-right lies -/// inside the superblock to the right, which raster order has not reached -- -/// and the samples below-left only for the first, the only one whose left -/// column continues into the superblock beside it. +/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry +/// that map, this reads the answer the same way libaom and rav1e do: for a +/// block whose transform covers it whole, whether the samples above its right +/// (or below its left) are decoded depends only on where the block sits inside +/// its 64x64 superblock, which is a pinned table per block size. #[derive(Clone, Copy)] struct Reach { above_right: bool, below_left: bool, } +/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in +/// libaom): for a block that is neither in the superblock's top row nor its +/// rightmost column, whether the block above and to its right is coded before +/// it. Indexed by the block's position in the superblock, in blocks of its own +/// size, as `row * (16 >> log2 mi width) + col`, bit by bit from the low end. +const HAS_TOP_RIGHT: [&[u8]; 2] = [&[255, 85, 119, 85, 127, 85, 119, 85], &[95, 87]]; + +/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the +/// left. +const HAS_BOTTOM_LEFT: [&[u8]; 2] = [&[84, 16, 84, 0, 84, 16, 84, 0], &[4, 4]]; + impl Reach { - /// The reach of the quadrant coded `quadrant`-th in a superblock, counting - /// in raster order among the four. - fn quadrant(quadrant: usize) -> Self { + /// What a block of `side` samples at `(x, y)` may read past its own edges, + /// in a frame of `width` by `height`. + fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self { Self { - above_right: quadrant != 3, - below_left: quadrant == 0, + above_right: y > 0 && x + side < width && Self::top_right(side, x, y), + below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y), } } @@ -429,10 +488,60 @@ impl Reach { below_left: false, } } + + /// `has_top_right` for a block whose transform covers it whole: the top + /// row of a superblock reads into the superblock above, which is decoded; + /// the rightmost column would read into the superblock to the right, which + /// is not; and everything between is the table's to answer. + fn top_right(side: usize, x: usize, y: usize) -> bool { + let (row, col, per_side) = Self::position(side, x, y); + if row == 0 { + return true; + } + if col + 1 == per_side { + return false; + } + Self::bit(HAS_TOP_RIGHT[Self::table(side)], row * per_side + col) + } + + /// `has_bottom_left` for such a block: the leftmost column of a superblock + /// reads into the superblock to its left, which is decoded only as far + /// down as its own bottom; the bottom row would read into the superblock + /// below, which is not decoded at all; and the table answers the rest. + fn bottom_left(side: usize, x: usize, y: usize) -> bool { + let (row, col, per_side) = Self::position(side, x, y); + if col == 0 { + return row * side + side < SUPERBLOCK; + } + if row + 1 == per_side { + return false; + } + Self::bit(HAS_BOTTOM_LEFT[Self::table(side)], row * per_side + col) + } + + /// Where a block sits inside its superblock, in blocks of its own size, + /// and how many of them a superblock is across. + fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) { + ( + (y % SUPERBLOCK) / side, + (x % SUPERBLOCK) / side, + SUPERBLOCK / side, + ) + } + + /// Which of the two block sizes the encoder codes a table row is for. + fn table(side: usize) -> usize { + usize::from(side == BLOCK) + } + + /// One bit of a table, counting from the low end of its first byte. + fn bit(table: &[u8], index: usize) -> bool { + (table[index / 8] >> (index % 8)) & 1 != 0 + } } /// What one symbol costs against a CDF, in bits. -fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { +pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; let probability = f64::from(cdf[symbol] - low) / 32768.0; -probability.log2() @@ -447,6 +556,86 @@ fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { /// Without this the search is blind to what a mode costs to name, which is not /// a rounding error: a directional mode on a picture that does not run that way /// is a rate loss the squared error never sees. +/// Codes one square of the picture as a single block: searches the luma mode, +/// codes both chroma planes DC, and hands back the block and what it cost -- +/// squared error plus lambda times the bits its symbols spend. +fn code_square( + luma: &mut Plane, + chroma: &mut [Plane; 2], + (x, y): (usize, usize), + side: usize, + search: &Search, + mode_bits: &[f64; 13], +) -> (BlockCoeffs, f64) { + let (luma_set, chroma_set) = if side == BLOCK { + (TxbSet::Luma32, TxbSet::Chroma16) + } else { + (TxbSet::Luma16, TxbSet::Chroma8) + }; + let (luma_coeffs, mode, mut cost) = luma.search_block( + At { + x, + y, + side, + reach: Reach::of(side, x, y, luma.width, luma.height), + set: luma_set, + }, + search, + mode_bits, + ); + // Chroma is predicted DC because that is the mode the tile writer codes + // for it; what it costs still counts towards the partition decision. + let mut planes = [Vec::new(), Vec::new()]; + for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) { + let (levels, sse, bits) = plane.code_block( + At { + x: x / 2, + y: y / 2, + side: side / 2, + reach: Reach::none(), + set: chroma_set, + }, + DC_PRED, + search.base_q_idx, + search.deadzone, + ); + *coeffs = levels; + cost += sse + search.lambda * bits; + } + let [u, v] = planes; + ( + BlockCoeffs { + u, + v, + luma: luma_coeffs, + mode, + }, + cost, + ) +} + +/// The reconstructed samples one 32x32 square covers in all three planes, so +/// that a partition trial can be undone. +fn snapshot(luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize)) -> [Vec; 3] { + [ + luma.snapshot(x, y, BLOCK), + chroma[0].snapshot(x / 2, y / 2, BLOCK / 2), + chroma[1].snapshot(x / 2, y / 2, BLOCK / 2), + ] +} + +/// Puts such a snapshot back. +fn restore( + luma: &mut Plane, + chroma: &mut [Plane; 2], + (x, y): (usize, usize), + saved: &[Vec; 3], +) { + luma.restore(x, y, BLOCK, &saved[0]); + chroma[0].restore(x / 2, y / 2, BLOCK / 2, &saved[1]); + chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]); +} + fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] [INTRA_MODE_CTX[usize::from(left_mode)]]; @@ -521,6 +710,18 @@ pub fn encode_key_frame_with_modes( base_q_idx: u8, deadzone: f64, modes: &[u8], +) -> Result { + encode_key_frame_inner(picture, base_q_idx, deadzone, modes, split_blocks()) +} + +/// [`encode_key_frame_with_modes`] with the partition decision forced, which is +/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. +fn encode_key_frame_inner( + picture: &Picture, + base_q_idx: u8, + deadzone: f64, + modes: &[u8], + split_blocks: bool, ) -> Result { picture.check()?; if modes.is_empty() { @@ -573,8 +774,10 @@ pub fn encode_key_frame_with_modes( // what picks the CDF the next block's mode is coded against -- the same // bookkeeping the tile writer keeps, so that the search is costing the // symbol the writer will actually write. - let mut above_mode = vec![DC_PRED; cols]; - let mut left_mode = vec![DC_PRED; rows]; + // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on, + // because a 32x32 block may be split into four 16x16 ones. + let mut above_mode = vec![DC_PRED; cols * 2]; + let mut left_mode = vec![DC_PRED; rows * 2]; let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); let mut modes = Vec::with_capacity(cols * rows); @@ -590,47 +793,58 @@ pub fn encode_key_frame_with_modes( continue; } let (x, y) = (col * BLOCK, row * BLOCK); - let (luma_coeffs, mode) = luma.search_block( - At { - x, - y, - side: BLOCK, - reach: Reach::quadrant(quadrant), - }, + let (c0, r0) = (col * 2, row * 2); + let base = snapshot(&luma, &chroma, (x, y)); + + // What the whole 32x32 costs, including the partition symbol + // that says it is not split. + let (whole, mut cost_whole) = code_square( + &mut luma, + &mut chroma, + (x, y), + BLOCK, &search, - &mode_bits(above_mode[col], left_mode[row]), + &mode_bits(above_mode[c0], left_mode[r0]), ); - above_mode[col] = mode; - left_mode[row] = mode; - modes.push(mode); - blocks.push(BlockCoeffs { - // Chroma is predicted DC because that is the mode the tile - // writer codes for it. - u: chroma[0].code_block( - At { - x: x / 2, - y: y / 2, - side: BLOCK / 2, - reach: Reach::none(), - }, - DC_PRED, - base_q_idx, - deadzone, - ), - v: chroma[1].code_block( - At { - x: x / 2, - y: y / 2, - side: BLOCK / 2, - reach: Reach::none(), - }, - DC_PRED, - base_q_idx, - deadzone, - ), - luma: luma_coeffs, - mode, - }); + cost_whole += search.lambda * partition_bits(BLOCK, false); + let after_whole = snapshot(&luma, &chroma, (x, y)); + + // What four 16x16 blocks cost instead, each searched against + // the reconstruction the ones before it left. + restore(&mut luma, &mut chroma, (x, y), &base); + let mut split = Vec::with_capacity(4); + let mut cost_split = search.lambda + * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); + let mut split_modes = [DC_PRED; 4]; + for (sub, sub_mode) in split_modes.iter_mut().enumerate() { + let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); + let (block, cost) = code_square( + &mut luma, + &mut chroma, + (x + (sub % 2) * SUB, y + (sub / 2) * SUB), + SUB, + &search, + &mode_bits(above_mode[sc], left_mode[sr]), + ); + cost_split += cost; + *sub_mode = block.mode; + above_mode[sc] = block.mode; + left_mode[sr] = block.mode; + split.push(block); + } + + if split_blocks && cost_split < cost_whole { + modes.extend_from_slice(&split_modes); + blocks.push(Quadrant::Split(split)); + } else { + restore(&mut luma, &mut chroma, (x, y), &after_whole); + for cell in 0..2 { + above_mode[c0 + cell] = whole.mode; + left_mode[r0 + cell] = whole.mode; + } + modes.push(whole.mode); + blocks.push(Quadrant::Whole(whole)); + } } superblocks.push(Superblock::Split(blocks)); } @@ -854,6 +1068,42 @@ mod tests { } } + /// Splitting a 32x32 block into four 16x16 ones, measured both ways over + /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what + /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report. + #[test] + #[ignore = "a sweep, not a gate"] + fn probe_split() { + for (name, picture) in sweep_pictures() { + let ladder = |split: bool| { + let mut points: Vec<(f64, f64)> = [110u8, 90, 70] + .iter() + .map(|&q| { + let encoded = + encode_key_frame_inner(&picture, q, 0.5, &KEY_FRAME_MODES, split) + .unwrap(); + ( + psnr(&encoded.reconstruction.y, picture.y.as_slice()), + (encoded.stream.len() as f64).log10(), + ) + }) + .collect(); + points.sort_by(|a, b| a.0.total_cmp(&b.0)); + points + }; + let (whole, split) = (ladder(false), ladder(true)); + let blocks = encode_key_frame_inner(&picture, 90, 0.5, &KEY_FRAME_MODES, true) + .unwrap() + .modes + .len(); + let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); + println!( + "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", + bd_rate(&whole, &split) * 100.0 + ); + } + } + /// A striped picture, running one way or the other. The stripes are what /// separates a vertical predictor from a horizontal one: a mode search /// reading a transposed edge would pick the wrong one of the pair, which no diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 4635ccb8..6d6a5d5d 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -64,6 +64,9 @@ const SB_MI: u32 = 16; /// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail. const NUM_BASE_LEVELS: i32 = 2; +/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16 +/// intra luma transform picks its type from. +const TX_TYPE_DCT_DCT_SET2: usize = 1; /// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the /// Golomb tail takes over. const COEFF_BASE_RANGE: i32 = 12; @@ -225,7 +228,7 @@ pub fn dc_key_frame_tile_levels( write_dc_coeffs( &mut enc, dc_level, - dc_sign_ctx(above[c as usize], left), + dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)), &cdf::TXB_SKIP_LUMA_64, &cdf::COEFF_BASE_EOB_LUMA_64_DC, ); @@ -301,7 +304,7 @@ pub fn split_dc_key_frame_tile( write_dc_coeffs( &mut enc, dc_level, - dc_sign_ctx(above[c as usize], left[r as usize]), + dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])), &cdf::TXB_SKIP_LUMA_32, &cdf::COEFF_BASE_EOB_LUMA_32[0], ); @@ -363,8 +366,19 @@ impl From> for BlockCoeffs { /// Side of the luma transform the coefficient writer codes. const TX32: usize = 32; -/// Side of the chroma transform beside it at 4:2:0. +/// Side of the larger of the two blocks a superblock splits into, in samples. +const BLOCK: usize = 32; +/// Side of the chroma transform beside it at 4:2:0, and of the luma transform +/// of a 16x16 block. const TX16: usize = 16; +/// Side of the chroma transform of a 16x16 block at 4:2:0. +const TX8: usize = 8; +/// Side of a superblock, in samples, which is the size a block outside the +/// tile reads as. +const SB: usize = 64; +/// Side of the smallest block the writer codes, in samples, which is the grid +/// the neighbour bookkeeping is kept on. +const SUB: usize = 16; /// What one coded block leaves behind for the blocks that read it as a /// neighbour: whether it coded anything at all, and the sign of its DC. @@ -411,11 +425,124 @@ pub enum Superblock { /// top-left 32x32 carries coefficients — and whose chroma transforms are /// 32x32 each at 4:2:0. Whole(BlockCoeffs), - /// The 32x32 blocks the superblock is split into, each with a 32x32 luma - /// transform and a 16x16 transform per chroma plane. + /// The 32x32 quadrants the superblock is split into, each either one + /// block or four 16x16 blocks of its own. + Split(Vec), +} + +/// One 32x32 quadrant of a split superblock. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Quadrant { + /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per + /// chroma plane. + Whole(BlockCoeffs), + /// The four 16x16 blocks it is split into, in raster order, each with a + /// 16x16 luma transform and an 8x8 transform per chroma plane. Split(Vec), } +impl Quadrant { + /// The blocks it carries, in the order they are coded. + fn blocks(&self) -> &[BlockCoeffs] { + match self { + Quadrant::Whole(block) => std::slice::from_ref(block), + Quadrant::Split(blocks) => blocks.as_slice(), + } + } +} + +/// What the blocks above and to the left of the one being coded left behind, +/// kept on the 16x16 grid the smallest block sits on. +struct Neighbours { + /// Per plane, whether the neighbour coded anything and the sign of its DC. + above: Vec<[Neighbour; 3]>, + /// The same, down the left edge. + left: Vec<[Neighbour; 3]>, + /// The neighbour's luma intra mode, which picks the CDF the next block's + /// mode is coded with. + above_mode: Vec, + /// The same, down the left edge. + left_mode: Vec, + /// The side of the neighbour block, in samples, which is what the + /// partition symbol's context reads. + above_side: Vec, + /// The same, down the left edge. + left_side: Vec, +} + +/// What one plane's neighbours leave for a block, gathered across every cell +/// the block spans -- which is what the decoder's own derivation reads +/// (spec 5.11.39), and what a single cell only stands in for while every block +/// is the same size. +#[derive(Clone, Copy, Default)] +struct Around { + /// Whether any transform block above this one carried a coefficient. + above_coded: bool, + /// The same, to the left. + left_coded: bool, + /// The running vote of the neighbours' DC signs: negative DCs count down, + /// positive ones up, and a neighbour with no DC does not count. + dc_vote: i32, +} + +impl Neighbours { + /// The state a tile starts from: a block outside it reads as `DC_PRED`, + /// as having coded nothing, and as unsplit. + fn new(cols: usize, rows: usize) -> Self { + Self { + above: vec![[Neighbour::default(); 3]; cols], + left: vec![[Neighbour::default(); 3]; rows], + above_mode: vec![DC_PRED; cols], + left_mode: vec![DC_PRED; rows], + above_side: vec![SB; cols], + left_side: vec![SB; rows], + } + } + + /// Clears the left edge, which a tile starts every superblock row with. + fn start_row(&mut self) { + self.left.iter_mut().for_each(|l| *l = Default::default()); + self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); + self.left_side.iter_mut().for_each(|s| *s = SB); + } + + /// Writes one coded block into every 16x16 column and row it covers. + fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec; 3]) { + let (r, c) = at; + let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); + for cell in 0..side / SUB { + self.above[c + cell] = states; + self.left[r + cell] = states; + self.above_mode[c + cell] = mode; + self.left_mode[r + cell] = mode; + self.above_side[c + cell] = side; + self.left_side[r + cell] = side; + } + } + + /// The context of a block's partition symbol (spec 9.3): whether the + /// blocks above it and to its left were split finer than it is. + /// The gathered state of the blocks above and to the left of one block, + /// per plane. + fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] { + std::array::from_fn(|plane| { + let mut around = Around::default(); + for cell in 0..side / SUB { + let (above, left) = (&self.above[c + cell][plane], &self.left[r + cell][plane]); + around.above_coded |= above.coded; + around.left_coded |= left.coded; + around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc); + } + around + }) + } + + fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize { + let (r, c) = at; + 2 * usize::from(self.left_side[r] * 2 <= side) + usize::from(self.above_side[c] * 2 <= side) + } +} + /// Writes the payload of a one-tile key frame built from `superblocks`, each /// either one 64x64 block or the 32x32 blocks it splits into. /// @@ -449,14 +576,19 @@ pub fn sb_coeff_key_frame_tile( "a coefficient key frame needs one entry per superblock", )); } - let bad_mode = superblocks - .iter() - .flat_map(|sb| match sb { - Superblock::Whole(b) => std::slice::from_ref(b), - Superblock::Split(b) => b.as_slice(), - }) - .find(|b| usize::from(b.mode) >= INTRA_MODES); - if let Some(bad) = bad_mode { + let mut coded: Vec<&BlockCoeffs> = Vec::new(); + for superblock in superblocks { + match superblock { + Superblock::Whole(block) => coded.push(block), + Superblock::Split(quadrants) => { + coded.extend(quadrants.iter().flat_map(Quadrant::blocks)); + } + } + } + if let Some(bad) = coded + .into_iter() + .find(|b| usize::from(b.mode) >= INTRA_MODES) + { return Err(Error::unsupported( "AV1 tile", format!( @@ -473,28 +605,14 @@ pub fn sb_coeff_key_frame_tile( )); } + let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8]; let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16]; let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; - let scans = [default_scan(TX32), default_scan(TX16)]; - // What the blocks above and to the left of the one being coded left - // behind, per plane, one entry per 32x32 column and row. The left column - // is reset at every superblock row because a tile starts each row with no + let scans = [default_scan(TX32), default_scan(TX16), default_scan(TX8)]; + // The blocks above and to the left, on the 16x16 grid. The left edge is + // reset at every superblock row because a tile starts each row with no // left neighbour. - let mut above = vec![[Neighbour::default(); 3]; cols as usize]; - let mut left = vec![[Neighbour::default(); 3]; rows as usize]; - // The luma intra mode of those same neighbours, which picks the CDF the - // next block's mode is coded with. A block outside the tile reads as - // `DC_PRED`, which is what these start and are reset to. - let mut above_mode = vec![DC_PRED; cols as usize]; - let mut left_mode = vec![DC_PRED; rows as usize]; - // Whether those neighbours were split, which is what the superblock's - // partition symbol reads: the context is bit three of the neighbour's - // entry in the spec's partition-context table, and of the sizes a - // superblock can leave behind only a 32x32 block sets it. A neighbour - // outside the tile reads as an unsplit one, which is what these start and - // are reset to. - let mut above_split = vec![false; cols as usize]; - let mut left_split = vec![false; rows as usize]; + let mut neighbours = Neighbours::new(cols as usize * 2, rows as usize * 2); // The tile adapts every non-literal CDF it writes, exactly as the decoder // adapts the ones it reads, so the frame header leaves `disable_cdf_update` @@ -502,12 +620,10 @@ pub fn sb_coeff_key_frame_tile( let mut cdfs = Cdfs::new(); let mut enc = SymbolEncoder::new(); for sb_r in 0..sb_rows { - left.iter_mut().for_each(|l| *l = Default::default()); - left_mode.iter_mut().for_each(|m| *m = DC_PRED); - left_split.iter_mut().for_each(|l| *l = false); + neighbours.start_row(); for sb_c in 0..sb_cols { - let (r0, c0) = (sb_r as usize * 2, sb_c as usize * 2); - let ctx = 2 * usize::from(left_split[r0]) + usize::from(above_split[c0]); + let at = (sb_r as usize * 4, sb_c as usize * 4); + let ctx = neighbours.partition_ctx(at, SB); // A superblock whose bottom or right half is outside the frame // cannot be left unsplit, so the decoder reads a flag instead of // the partition symbol — and reads nothing at all when both halves @@ -518,7 +634,7 @@ pub fn sb_coeff_key_frame_tile( ); // The quadrants of this superblock that are inside the frame, as // positions in the 32x32 block grid. - let quadrants: Vec<(usize, usize)> = (0..4) + let quadrant_positions: Vec<(usize, usize)> = (0..4) .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2)) .filter(|&(r, c)| r < rows && c < cols) .map(|(r, c)| (r as usize, c as usize)) @@ -533,45 +649,27 @@ pub fn sb_coeff_key_frame_tile( )); } enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]); - let mode = write_intra_mode( - &mut enc, - &mut cdfs, - block, - above_mode[c0], - left_mode[r0], - // A 64x64 block is too big to be offered chroma from - // luma, so its chroma mode reads the table without it. - false, - ); let grids = [ level_grid(&block.luma, TX32)?, level_grid(&block.u, TX32)?, level_grid(&block.v, TX32)?, ]; - write_block_planes( + write_block( &mut enc, &mut cdfs, + &mut neighbours, + block, + at, + SB, &whole_planes, &grids, - &[&scans[0], &scans[0], &scans[0]], - &above[c0], - &left[r0], + [&scans[0], &scans[0], &scans[0]], + // A 64x64 block is too big to be offered chroma from + // luma, so its chroma mode reads the table without it. + false, ); - // The block covers two columns and two rows of the 32x32 - // grid, so both of each read it as their neighbour. - for (r, c) in quadrants { - for plane in 0..3 { - let state = neighbour_state(&grids[plane]); - above[c][plane] = state; - left[r][plane] = state; - } - above_mode[c] = mode; - left_mode[r] = mode; - above_split[c] = false; - left_split[r] = false; - } } - Superblock::Split(blocks) => { + Superblock::Split(quadrants) => { match (has_cols, has_rows) { (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]), // The gathered CDF an edge superblock reads is built @@ -585,45 +683,68 @@ pub fn sb_coeff_key_frame_tile( } (false, false) => {} } - if blocks.len() != quadrants.len() { + if quadrants.len() != quadrant_positions.len() { return Err(Error::unsupported( "AV1 tile", "a split superblock needs one block per quadrant inside the frame", )); } - for (block, (r, c)) in blocks.iter().zip(quadrants) { - enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]); - let mode = write_intra_mode( - &mut enc, - &mut cdfs, - block, - above_mode[c], - left_mode[r], - true, - ); - let grids = [ - level_grid(&block.luma, TX32)?, - level_grid(&block.u, TX16)?, - level_grid(&block.v, TX16)?, - ]; - write_block_planes( - &mut enc, - &mut cdfs, - &split_planes, - &grids, - &[&scans[0], &scans[1], &scans[1]], - &above[c], - &left[r], - ); - for plane in 0..3 { - let state = neighbour_state(&grids[plane]); - above[c][plane] = state; - left[r][plane] = state; + for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) { + let at = (r * 2, c * 2); + let ctx = neighbours.partition_ctx(at, BLOCK); + match quadrant { + Quadrant::Whole(block) => { + enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]); + let grids = [ + level_grid(&block.luma, TX32)?, + level_grid(&block.u, TX16)?, + level_grid(&block.v, TX16)?, + ]; + write_block( + &mut enc, + &mut cdfs, + &mut neighbours, + block, + at, + BLOCK, + &split_planes, + &grids, + [&scans[0], &scans[1], &scans[1]], + true, + ); + } + Quadrant::Split(blocks) => { + enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]); + if blocks.len() != 4 { + return Err(Error::unsupported( + "AV1 tile", + "a 32x32 block that is split carries four 16x16 blocks", + )); + } + for (i, block) in blocks.iter().enumerate() { + let at = (at.0 + i / 2, at.1 + i % 2); + let ctx = neighbours.partition_ctx(at, SUB); + enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]); + let grids = [ + level_grid(&block.luma, TX16)?, + level_grid(&block.u, TX8)?, + level_grid(&block.v, TX8)?, + ]; + write_block( + &mut enc, + &mut cdfs, + &mut neighbours, + block, + at, + SUB, + &sub_planes, + &grids, + [&scans[1], &scans[2], &scans[2]], + true, + ); + } + } } - above_mode[c] = mode; - left_mode[r] = mode; - above_split[c] = true; - left_split[r] = true; } } } @@ -663,18 +784,56 @@ fn write_intra_mode( mode } +/// Writes one coded block: its mode, its three transform blocks, and what it +/// leaves behind for the blocks beside it. Its partition symbol is already +/// written, because only the caller knows what tree led here. +#[allow(clippy::too_many_arguments)] +fn write_block( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + block: &BlockCoeffs, + at: (usize, usize), + side: usize, + planes: &[TxbSet; 3], + grids: &[Vec; 3], + scans: [&Vec; 3], + cfl: bool, +) { + let (r, c) = at; + let mode = write_intra_mode( + enc, + cdfs, + block, + neighbours.above_mode[c], + neighbours.left_mode[r], + cfl, + ); + write_block_planes( + enc, + cdfs, + planes, + grids, + &scans, + &neighbours.around(at, side), + mode, + ); + neighbours.record(at, side, mode, grids); +} + /// Writes the three transform blocks of one coded block, in the order a /// decoder reads them. +#[allow(clippy::too_many_arguments)] fn write_block_planes( enc: &mut SymbolEncoder, cdfs: &mut Cdfs, planes: &[TxbSet; 3], grids: &[Vec; 3], scans: &[&Vec; 3], - above: &[Neighbour; 3], - left: &[Neighbour; 3], + around: &[Around; 3], + mode: usize, ) { - for (plane, grid) in grids.iter().enumerate() { + for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() { // Luma's transform covers its whole block, which fixes the all-zero // flag's context at zero; a chroma transform reads whether its // neighbours coded anything, on top of the offset the chroma tables @@ -682,15 +841,15 @@ fn write_block_planes( let skip_ctx = if plane == 0 { 0 } else { - usize::from(above[plane].coded) + usize::from(left[plane].coded) + usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded) }; write_coeffs( enc, - &mut cdfs.txb(planes[plane]), + &mut cdfs.txb(planes[plane], mode), grid, - scans[plane], + scan, skip_ctx, - dc_sign_ctx(above[plane].dc, left[plane].dc), + dc_sign_ctx(around[plane].dc_vote), ); } } @@ -734,7 +893,7 @@ pub fn split_coeff_key_frame_tile( (0..4) .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2)) .filter(|&(r, c)| r < rows && c < cols) - .map(|(r, c)| blocks[(r * cols + c) as usize].clone()) + .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone())) .collect(), ) }) @@ -808,31 +967,62 @@ fn default_scan(side: usize) -> Vec { /// so one table is all the search needs; a second block size would need its /// own entry point rather than a size argument, because the table and the scan /// have to agree. +#[cfg(test)] pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { - /// Built once: the search prices thirteen modes for every block, and the - /// scan is the same table every time. - static SCAN: LazyLock> = LazyLock::new(|| default_scan(TX32)); + coeff_bits(grid, TxbSet::Luma32) +} + +/// What one transform block's levels cost through the CDFs of `set`, in bits. +/// +/// The search runs before the tile is written, so the adapted state the block +/// will really be coded against does not exist yet: the price is taken against +/// the defaults every tile starts from, and against the contexts a block whose +/// neighbours coded nothing reads. +pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 { + /// Built once per size: the search prices thirteen modes for every block, + /// and the scan is the same table every time. + static SCANS: LazyLock<[Vec; 3]> = + LazyLock::new(|| [default_scan(TX8), default_scan(TX16), default_scan(TX32)]); + let mut cdfs = Cdfs::new(); + let mut coding = cdfs.txb(set, DC_PRED); + let scan = match coding.side { + TX8 => &SCANS[0], + TX16 => &SCANS[1], + _ => &SCANS[2], + }; let mut enc = SymbolEncoder::new(); enc.reset_bits(); - // The search runs before the tile is written, so the adapted state the - // block will really be coded against does not exist yet: the price is - // taken against the defaults every tile starts from. - write_coeffs( - &mut enc, - &mut Cdfs::new().txb(TxbSet::Luma32), - grid, - &SCAN, - 0, - 0, - ); + write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0); enc.bits() } +/// What the partition symbol of a block of `side` samples costs, in bits, when +/// it says the block is split (or that it is not). +/// +/// The price is taken at context zero — a block whose neighbours are no finer +/// than it is — because the search that reads it runs before the tile knows +/// what its neighbours will be. +pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { + let cdfs = Cdfs::new(); + let cdf: &[u16] = match side { + SB => &cdfs.partition_w64[0], + BLOCK => &cdfs.partition_w32[0], + _ => &cdfs.partition_w16[0], + }; + let symbol = if split { + PARTITION_SPLIT + } else { + PARTITION_NONE + }; + crate::encode::symbol_bits(cdf, symbol) +} + /// coeffs() for one plane's transform block of any coefficients the base and /// base-range syntax reach (spec 5.11.39). /// -/// A 32x32 or 16x16 transform is DCT-only here, so no transform type is coded; -/// and the levels the contexts below are read from are the levels of +/// A 16x16 luma transform codes which transform type it is, because its set +/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The +/// levels the contexts below are read from are the levels of /// coefficients later in the scan, which a decoder walking the scan backwards /// already has. fn write_coeffs( @@ -852,6 +1042,12 @@ fn write_coeffs( if eob == 0 { return; } + // A luma transform whose type set holds more than one type codes which it + // is, right after the all-zero flag (spec 5.11.39). The writer only ever + // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`. + if let Some(tx_type) = coding.tx_type.as_deref_mut() { + enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type); + } write_eob(enc, coding, eob); @@ -1066,19 +1262,21 @@ fn write_dc_coeffs( enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]); } -/// `Dc_Sign_Contexts` (spec 8.3.2): every 4x4 unit above and left of the block -/// votes the sign of the DC its own block carries — plus one for a positive -/// one, minus one for a negative one, nothing for a unit with no coded -/// coefficient — and the sum picks one of three contexts. Every block here is a -/// whole superblock carrying one DC, so all sixteen units of a neighbour vote -/// together and the sum can only lean up, lean down, or cancel. -fn dc_sign_ctx(above: Option, left: Option) -> usize { - let vote = |n: Option| match n { - None => 0i32, +/// One neighbour cell's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for +/// a positive DC, minus one for a negative one, nothing for a cell whose block +/// carried no DC. Every 4x4 unit of a cell votes the same way, so counting +/// cells and counting units differ only by a factor the sign is blind to. +fn dc_vote(dc: Option) -> i32 { + match dc { + None => 0, Some(true) => -1, Some(false) => 1, - }; - match (vote(above) + vote(left)).signum() { + } +} + +/// Which of the three DC sign contexts a gathered vote picks. +fn dc_sign_ctx(vote: i32) -> usize { + match vote.signum() { 0 => 0, -1 => 1, _ => 2, @@ -1795,7 +1993,7 @@ mod tests { for grid in &grids { write_coeffs( &mut enc, - &mut Cdfs::new().txb(TxbSet::Luma32), + &mut Cdfs::new().txb(TxbSet::Luma32, 0), grid, &scan, 0, @@ -2090,6 +2288,41 @@ mod tests { /// Encodes a key frame of the given size, whose 32x32 blocks carry /// `blocks` in raster order, and hands back its luma plane as rows of + /// The neighbour context a block reads is gathered across every cell it + /// spans, not taken from the first one: a 32x32 block whose left-hand + /// neighbour cells disagree still sees the coded one. Reading a single + /// cell agreed with the decoder only while every block was the same size, + /// and desynchronised the arithmetic decoder the moment a 16x16 one + /// appeared beside a 32x32 one. + #[test] + fn a_block_gathers_the_cells_its_neighbours_cover() { + let mut neighbours = Neighbours::new(4, 4); + let quiet = [ + vec![0i32; TX16 * TX16], + vec![0; TX8 * TX8], + vec![0; TX8 * TX8], + ]; + let mut loud = quiet.clone(); + loud[1][0] = -3; + // Two 16x16 blocks above the right-hand 32x32 block of the row, of + // which only the second codes anything. + neighbours.record((0, 2), SUB, DC_PRED, &quiet); + neighbours.record((0, 3), SUB, DC_PRED, &loud); + let around = neighbours.around((2, 2), BLOCK); + assert!( + around[1].above_coded, + "the coded cell has to reach the block below it" + ); + assert_eq!( + dc_sign_ctx(around[1].dc_vote), + 1, + "the one negative DC above the block is what it votes" + ); + // The same read one cell at a time misses it, which is the bug this + // gate is here for. + assert!(!neighbours.above[2][1].coded); + } + /// samples. fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec> { let (seq, header) = frame_of(width as u32, height as u32); @@ -2294,7 +2527,12 @@ mod tests { }]); let sbs = [ Superblock::Whole(across), - Superblock::Split(vec![down.clone(), down.clone(), down.clone(), down]), + Superblock::Split(vec![ + Quadrant::Whole(down.clone()), + Quadrant::Whole(down.clone()), + Quadrant::Whole(down.clone()), + Quadrant::Whole(down), + ]), ]; let rows = decode_luma_sb(128, 64, &sbs); @@ -2325,6 +2563,71 @@ mod tests { } } + /// A quadrant may be split again into four 16x16 blocks, each carrying its + /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block + /// makes each of the four a flat grey of its own, so the quadrant reads as + /// four squares rather than one — which is what tells the extra split from + /// a 32x32 block that merely carries the same coefficients. + #[test] + fn a_quadrant_splits_into_four_sixteens() { + if !have_ffmpeg() { + eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg"); + return; + } + let dc = |level: i32| { + BlockCoeffs::from(vec![Coeff { + row: 0, + col: 0, + level, + }]) + }; + let levels = [14, 8, -8, -14]; + let flat = BlockCoeffs::from(Vec::new()); + let sbs = [Superblock::Split(vec![ + Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()), + Quadrant::Whole(flat.clone()), + Quadrant::Whole(flat.clone()), + Quadrant::Whole(flat), + ])]; + let rows = decode_luma_sb(64, 64, &sbs); + + let mut greys = Vec::new(); + for i in 0..levels.len() { + let (y0, x0) = ((i / 2) * 16, (i % 2) * 16); + let grey = rows[y0][x0]; + for (y, row) in rows.iter().enumerate().skip(y0).take(16) { + for (x, &sample) in row.iter().enumerate().skip(x0).take(16) { + assert_eq!( + sample, grey, + "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not" + ); + } + } + greys.push(grey); + } + + // Each block is predicted DC from the blocks the decoder has already + // rebuilt, so what its own level does is move it off that prediction, + // in the level's own direction. + let g = |i: usize| i32::from(greys[i]); + let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2]; + for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() { + assert_eq!( + (g(i) - prediction).signum(), + level.signum(), + "the 16x16 block {i} carries level {level}, so it sits on the \ + {} side of the {prediction} its neighbours predict, not at {}", + if level > 0 { "bright" } else { "dark" }, + g(i) + ); + } + assert_eq!( + greys.iter().collect::>().len(), + 4, + "the four blocks are four different greys, not one: {greys:?}" + ); + } + /// A superblock half outside the frame has no partition that keeps a block /// outside it, so it cannot be left whole. #[test] @@ -2336,10 +2639,10 @@ mod tests { }]); let sbs = [ Superblock::Split(vec![ - block.clone(), - block.clone(), - block.clone(), - block.clone(), + Quadrant::Whole(block.clone()), + Quadrant::Whole(block.clone()), + Quadrant::Whole(block.clone()), + Quadrant::Whole(block.clone()), ]), Superblock::Whole(block.clone()), ]; @@ -2781,6 +3084,74 @@ mod tests { assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}"); } + /// The same against the smallest transform the writer codes, the 16x16 one + /// a split quadrant carries. Its rounding is the one the split path rests + /// on, and nothing else in the crate exercises it against a decoder. + #[test] + fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() { + if !have_ffmpeg() { + eprintln!( + "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg" + ); + return; + } + let coeffs = [ + (0u8, 0u8, 9i32), + (0, 1, -14), + (1, 0, 7), + (0, 3, 5), + (3, 0, -3), + (2, 2, 11), + (7, 5, -6), + (15, 15, 4), + ]; + let block: BlockCoeffs = coeffs + .iter() + .map(|&(row, col, level)| Coeff { row, col, level }) + .collect::>() + .into(); + let (seq, header) = frame_of(64, 64); + let quadrants = vec![ + Quadrant::Split(vec![ + block, + BlockCoeffs::default(), + BlockCoeffs::default(), + BlockCoeffs::default(), + ]), + Quadrant::Whole(BlockCoeffs::default()), + Quadrant::Whole(BlockCoeffs::default()), + Quadrant::Whole(BlockCoeffs::default()), + ]; + let tile = sb_coeff_key_frame_tile( + header.mi_cols, + header.mi_rows, + Q_IDX, + &[Superblock::Split(quadrants)], + ) + .unwrap(); + let mut stream = temporal_delimiter(); + stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); + stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); + let planes = ffmpeg_decode(&stream, 64, 64); + + let mut levels = vec![0i32; TX16 * TX16]; + for &(row, col, level) in &coeffs { + levels[usize::from(row) * TX16 + usize::from(col)] = level; + } + let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX)); + for row in 0..TX16 { + for col in 0..TX16 { + let want = (128 + residual[row * TX16 + col]).clamp(0, 255); + assert_eq!( + i32::from(planes[row * 64 + col]), + want, + "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}", + planes[row * 64 + col] + ); + } + } + } + /// The same against the other transform size, the 64x64 one a whole /// superblock carries. Only its top-left 32x32 can hold coefficients, and /// the spec zeroes the rest before the row transform — a 64-point network diff --git a/lanes/av1-sub32-r1.report.md b/lanes/av1-sub32-r1.report.md new file mode 100644 index 00000000..3f6f3de0 --- /dev/null +++ b/lanes/av1-sub32-r1.report.md @@ -0,0 +1,75 @@ +# lane-av1-sub32 r1 — 32x32 quadrants may split into four 16x16 blocks + +## What landed + +`encode_key_frame` now trials each 32x32 quadrant twice and keeps the cheaper +coding: + +- `cost_whole = luma_cost + sum_chroma(sse + lambda * bits) + lambda * partition_bits(BLOCK, false)` +- `cost_split = sum_i(sub costs) + lambda * (partition_bits(BLOCK, true) + 4 * partition_bits(SUB, false))` + +The reconstruction is snapshotted before the whole trial, restored before the +split trial, and the winner's reconstruction is put back, so prediction below and +to the right reads exactly what the decoder will. Mode bookkeeping moved to the +16x16 grid (`above_mode[cols * 2]`, `left_mode[rows * 2]`), which is the +granularity the spec's mode context reads at. + +The ablation is a parameter, not an env knob: `encode_key_frame_inner(..., split_blocks: bool)`, +with `SPLIT_BLOCKS` as the shipped default and `probe_split` calling both ways. + +## Measurement — `probe_split`, three-point ladder (q 110/90/70), BD-rate split vs whole + +| picture | BD-rate | coded blocks / quadrants @ q90 | +| --- | --- | --- | +| test card (synthetic) | -0.72% | 15 / 15 | +| stripes (synthetic) | +0.00% | 15 / 15 | +| diagonal (synthetic) | -22.45% | 33 / 15 | +| ReelC 1080p film @20:00 | **-9.15%** | 415 / 220 | +| OBS screen capture @10:00 | **-27.20%** | 604 / 220 | +| reela.mp4 @5s | **-9.05%** | 316 / 220 | + +Negative is better. `stripes` never splits (every quadrant is one texture), which +is the shape a correct RD decision should have. Default set to `SPLIT_BLOCKS = true`. + +## Defect found, fixed and gated — class: context read from one cell + +Turning splits on broke `ffmpeg_decodes_exactly_what_the_encoder_reconstructed` at +96x64: 979/6144 samples off by ~1, starting at the first split quadrant. Bisected +by forcing DC on sub-blocks (drift stayed, so not the mode context) and by adding a +permanent 16x16 inverse-transform-vs-ffmpeg gate (passed, so not the transform or +dequant). + +Cause: `write_block` read the chroma `txb_skip` context and the DC-sign context +from a single neighbour cell. The decoder gathers over every 4x4 unit the block +spans (`get_txb_skip_ctx`, spec 5.11.39; `Dc_Sign_Contexts`, spec 8.3.2). While +every block is 32x32 the one cell *is* the span, so the bug is invisible; the +moment a 16x16 sits beside a 32x32 the arithmetic decoder desynchronises — as +sample drift, never a crash. + +Fix: `Neighbours::around((r, c), side) -> [Around; 3]`, OR-ing `coded` and summing +the DC vote across `side / SUB` cells on both edges. + +Sibling single-cell reads swept, each correct by spec and left alone: +`above_mode`/`left_mode` (the spec reads exactly the mi above/left of the top-left), +`partition_ctx` (one neighbour's size), luma `txb_skip` ctx = 0 (the transform +covers the whole block at every size the writer codes). + +## Gates added + +- `the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block` — a split + quadrant carrying eight coefficients including `(15, 15, 4)`, every sample + compared to `dequant_and_inverse(&levels, TX16, 8, Q_IDX)`. +- `a_block_gathers_the_cells_its_neighbours_cover` — two 16x16 neighbours with + different chroma state; asserts the gathered read sees both and that the + single-cell read misses it. + +## State + +`cargo clippy --release -p ec-av1 --all-targets` zero warnings; suite 85 passed, +0 failed, 4 ignored. + +## Next in this layer + +Transform types beyond DCT_DCT and tx-size selection; splits below 16x16; pictures +that are not a multiple of 32; interleaving the search with the writer so rates +price against adapted tables.