forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-sub32': 16x16 partition RD

Browse files at this commit

d5332d25a2bd9c6e264e1777e9b1e96b06e4bbeeAhmet Kaan GümüşParent: 0c1d7877d10ec2
crates/ec-av1/src/cdf.rsmodified+235 -0
@@ -722,3 +722,238 @@ pub const TXB_SKIP_CHROMA_32: [[u16; 3]; 3] =
722722 pub const EOB_PT_1024_CHROMA: [u16; 12] = [
723723 9577, 12466, 17739, 20750, 22061, 23215, 24601, 25483, 25843, 32056, 32768, 0,
724724 ];
725+/// `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.
726+pub const TXB_SKIP_LUMA_16: [u16; 3] = [32363, 32768, 0];
727+
728+/// `Default_Txb_Skip_Cdf[2][1][7..10]`: the all-zero flag of an 8x8 chroma transform.
729+pub const TXB_SKIP_CHROMA_8: [[u16; 3]; 3] =
730+ [[3050, 32768, 0], [14603, 32768, 0], [25155, 32768, 0]];
731+
732+/// `Default_Eob_Pt_256_Cdf[2][0][0]`: the end-of-block group of a 16x16 luma transform.
733+pub const EOB_PT_256_LUMA: [u16; 10] =
734+ [3089, 3920, 6038, 9460, 14266, 19881, 25766, 29176, 32768, 0];
735+
736+/// `Default_Eob_Pt_64_Cdf[2][1][0]`: the end-of-block group of an 8x8 chroma transform.
737+pub const EOB_PT_64_CHROMA: [u16; 8] = [15050, 17126, 21410, 24886, 28156, 30726, 32768, 0];
738+
739+/// `Default_Eob_Extra_Cdf[2][2][0]`: the top offset bit inside a 16x16 luma transform's end-of-block group.
740+pub const EOB_EXTRA_LUMA_16: [[u16; 3]; 9] = [
741+ [19833, 32768, 0],
742+ [21502, 32768, 0],
743+ [17485, 32768, 0],
744+ [20267, 32768, 0],
745+ [18353, 32768, 0],
746+ [23329, 32768, 0],
747+ [21478, 32768, 0],
748+ [16384, 32768, 0],
749+ [16384, 32768, 0],
750+];
751+
752+/// `Default_Eob_Extra_Cdf[2][1][1]`: the same, for an 8x8 chroma transform.
753+pub const EOB_EXTRA_CHROMA_8: [[u16; 3]; 9] = [
754+ [20536, 32768, 0],
755+ [20664, 32768, 0],
756+ [20625, 32768, 0],
757+ [19123, 32768, 0],
758+ [14862, 32768, 0],
759+ [16384, 32768, 0],
760+ [16384, 32768, 0],
761+ [16384, 32768, 0],
762+ [16384, 32768, 0],
763+];
764+
765+/// `Default_Coeff_Base_Cdf[2][2][0]`: a 16x16 luma coefficient's base level.
766+pub const COEFF_BASE_LUMA_16: [[u16; 5]; 42] = [
767+ [9800, 17635, 21073, 32768, 0],
768+ [26153, 31885, 32527, 32768, 0],
769+ [15038, 27852, 31006, 32768, 0],
770+ [8718, 20564, 26486, 32768, 0],
771+ [5128, 14076, 20514, 32768, 0],
772+ [2636, 7566, 11925, 32768, 0],
773+ [27551, 32504, 32701, 32768, 0],
774+ [18310, 30054, 32100, 32768, 0],
775+ [10211, 23420, 29082, 32768, 0],
776+ [6222, 16876, 23916, 32768, 0],
777+ [3462, 9954, 15498, 32768, 0],
778+ [29991, 32633, 32721, 32768, 0],
779+ [19883, 30751, 32201, 32768, 0],
780+ [11141, 24184, 29285, 32768, 0],
781+ [6420, 16940, 23774, 32768, 0],
782+ [3392, 9753, 15118, 32768, 0],
783+ [28465, 32616, 32712, 32768, 0],
784+ [19850, 30702, 32244, 32768, 0],
785+ [10983, 24024, 29223, 32768, 0],
786+ [6294, 16770, 23582, 32768, 0],
787+ [3244, 9283, 14509, 32768, 0],
788+ [30023, 32717, 32748, 32768, 0],
789+ [22940, 32032, 32626, 32768, 0],
790+ [14282, 27928, 31473, 32768, 0],
791+ [8562, 21327, 27914, 32768, 0],
792+ [4846, 13393, 19919, 32768, 0],
793+ [29981, 32590, 32695, 32768, 0],
794+ [20465, 30963, 32166, 32768, 0],
795+ [11479, 23579, 28195, 32768, 0],
796+ [5916, 15648, 22073, 32768, 0],
797+ [3031, 8605, 13398, 32768, 0],
798+ [31146, 32691, 32739, 32768, 0],
799+ [23106, 31724, 32444, 32768, 0],
800+ [13783, 26738, 30439, 32768, 0],
801+ [7852, 19468, 25807, 32768, 0],
802+ [3860, 11124, 16853, 32768, 0],
803+ [31014, 32724, 32748, 32768, 0],
804+ [23629, 32109, 32628, 32768, 0],
805+ [14747, 28115, 31403, 32768, 0],
806+ [8545, 21242, 27478, 32768, 0],
807+ [4574, 12781, 19067, 32768, 0],
808+ [8192, 16384, 24576, 32768, 0],
809+];
810+
811+/// `Default_Coeff_Base_Cdf[2][1][1]`: an 8x8 chroma coefficient's base level.
812+pub const COEFF_BASE_CHROMA_8: [[u16; 5]; 42] = [
813+ [11016, 22111, 26794, 32768, 0],
814+ [25946, 32357, 32677, 32768, 0],
815+ [17890, 30452, 32252, 32768, 0],
816+ [11678, 25142, 29816, 32768, 0],
817+ [6720, 17534, 24584, 32768, 0],
818+ [4230, 11665, 17820, 32768, 0],
819+ [28400, 32623, 32747, 32768, 0],
820+ [21164, 31668, 32575, 32768, 0],
821+ [13572, 27388, 31182, 32768, 0],
822+ [8234, 20750, 27358, 32768, 0],
823+ [5065, 14055, 20897, 32768, 0],
824+ [28981, 32547, 32705, 32768, 0],
825+ [18681, 30543, 32239, 32768, 0],
826+ [10919, 24075, 29286, 32768, 0],
827+ [6431, 17199, 24077, 32768, 0],
828+ [3819, 10464, 16618, 32768, 0],
829+ [26870, 32467, 32693, 32768, 0],
830+ [19041, 30831, 32347, 32768, 0],
831+ [11794, 25211, 30016, 32768, 0],
832+ [6888, 18019, 24970, 32768, 0],
833+ [4370, 12363, 18992, 32768, 0],
834+ [29578, 32670, 32744, 32768, 0],
835+ [23159, 32007, 32613, 32768, 0],
836+ [15315, 28669, 31676, 32768, 0],
837+ [9298, 22607, 28782, 32768, 0],
838+ [6144, 15913, 22968, 32768, 0],
839+ [28110, 32499, 32669, 32768, 0],
840+ [21574, 30937, 32015, 32768, 0],
841+ [12759, 24818, 28727, 32768, 0],
842+ [6545, 16761, 23042, 32768, 0],
843+ [3649, 10597, 16833, 32768, 0],
844+ [28163, 32552, 32728, 32768, 0],
845+ [22101, 31469, 32464, 32768, 0],
846+ [13160, 25472, 30143, 32768, 0],
847+ [7303, 18684, 25468, 32768, 0],
848+ [5241, 13975, 20955, 32768, 0],
849+ [28400, 32631, 32744, 32768, 0],
850+ [22104, 31793, 32603, 32768, 0],
851+ [13557, 26571, 30846, 32768, 0],
852+ [7749, 19861, 26675, 32768, 0],
853+ [4873, 14030, 21234, 32768, 0],
854+ [8192, 16384, 24576, 32768, 0],
855+];
856+
857+/// `Default_Coeff_Base_Eob_Cdf[2][2][0]`: the base level of the last coefficient of a 16x16 luma transform.
858+pub const COEFF_BASE_EOB_LUMA_16: [[u16; 4]; 4] = [
859+ [12854, 29093, 32768, 0],
860+ [32272, 32558, 32768, 0],
861+ [32667, 32729, 32768, 0],
862+ [32306, 32585, 32768, 0],
863+];
864+
865+/// `Default_Coeff_Base_Eob_Cdf[2][1][1]`: the same, for an 8x8 chroma transform.
866+pub const COEFF_BASE_EOB_CHROMA_8: [[u16; 4]; 4] = [
867+ [27116, 30842, 32768, 0],
868+ [31971, 32598, 32768, 0],
869+ [32088, 32576, 32768, 0],
870+ [32067, 32664, 32768, 0],
871+];
872+
873+/// `Default_Coeff_Br_Cdf[2][2][0]`: the base-range tail of a 16x16 luma coefficient.
874+pub const COEFF_BR_LUMA_16: [[u16; 5]; 21] = [
875+ [14438, 20798, 24089, 32768, 0],
876+ [12621, 19203, 23097, 32768, 0],
877+ [8177, 14125, 18402, 32768, 0],
878+ [5674, 10501, 14456, 32768, 0],
879+ [4236, 8239, 11733, 32768, 0],
880+ [3447, 6750, 9806, 32768, 0],
881+ [1986, 3950, 5864, 32768, 0],
882+ [16208, 22099, 24930, 32768, 0],
883+ [16537, 24025, 27585, 32768, 0],
884+ [12780, 20381, 24867, 32768, 0],
885+ [9767, 16612, 21416, 32768, 0],
886+ [7686, 13738, 18398, 32768, 0],
887+ [6333, 11614, 15964, 32768, 0],
888+ [3941, 7571, 10836, 32768, 0],
889+ [22819, 27422, 29202, 32768, 0],
890+ [22224, 28514, 30721, 32768, 0],
891+ [17660, 25433, 28913, 32768, 0],
892+ [13574, 21482, 26002, 32768, 0],
893+ [10629, 17977, 22938, 32768, 0],
894+ [8612, 15298, 20265, 32768, 0],
895+ [5607, 10491, 14596, 32768, 0],
896+];
897+
898+/// `Default_Coeff_Br_Cdf[2][1][1]`: the base-range tail of an 8x8 chroma coefficient.
899+pub const COEFF_BR_CHROMA_8: [[u16; 5]; 21] = [
900+ [14433, 21155, 24938, 32768, 0],
901+ [14658, 21716, 25545, 32768, 0],
902+ [9923, 16824, 21557, 32768, 0],
903+ [6982, 13052, 17721, 32768, 0],
904+ [5419, 10503, 15050, 32768, 0],
905+ [4852, 9162, 13014, 32768, 0],
906+ [3271, 6395, 9630, 32768, 0],
907+ [22210, 27833, 30109, 32768, 0],
908+ [20750, 27368, 29821, 32768, 0],
909+ [16894, 24828, 28573, 32768, 0],
910+ [13247, 21276, 25757, 32768, 0],
911+ [10038, 17265, 22563, 32768, 0],
912+ [8587, 14947, 20327, 32768, 0],
913+ [5645, 11371, 15252, 32768, 0],
914+ [22027, 27526, 29714, 32768, 0],
915+ [23098, 29146, 31221, 32768, 0],
916+ [19886, 27341, 30272, 32768, 0],
917+ [15609, 23747, 28046, 32768, 0],
918+ [11993, 20065, 24939, 32768, 0],
919+ [9637, 18267, 23671, 32768, 0],
920+ [7625, 13801, 19144, 32768, 0],
921+];
922+
923+/// `Default_Partition_Cdf[0..4]`: the partition symbol of a 16x16 block.
924+pub const PARTITION_W16: [[u16; 11]; 4] = [
925+ [
926+ 15597, 20929, 24571, 26706, 27664, 28821, 29601, 30571, 31902, 32768, 0,
927+ ],
928+ [
929+ 7925, 11043, 16785, 22470, 23971, 25043, 26651, 28701, 29834, 32768, 0,
930+ ],
931+ [
932+ 5414, 13269, 15111, 20488, 22360, 24500, 25537, 26336, 32117, 32768, 0,
933+ ],
934+ [
935+ 2662, 6362, 8614, 20860, 23053, 24778, 26436, 27829, 31171, 32768, 0,
936+ ],
937+];
938+
939+/// The transform type of a 16x16 intra luma transform, as an index into the
940+/// spec's `Tx_Type_Intra_Inv_Set2`, indexed by the block's luma mode.
941+///
942+/// A 16x16 transform is the only size this writer codes whose transform-type
943+/// set holds more than one type, so it is the only one that codes the symbol:
944+/// 32x32 and 64x64 are DCT-only by spec 5.11.40's `get_tx_set`.
945+pub const INTRA_TX_TYPE_SET2_16: [[u16; 6]; 13] = [
946+ [1127, 12814, 22772, 27483, 32768, 0],
947+ [145, 6761, 11980, 26667, 32768, 0],
948+ [362, 5887, 11678, 16725, 32768, 0],
949+ [385, 15213, 18587, 30693, 32768, 0],
950+ [25, 2914, 23134, 27903, 32768, 0],
951+ [60, 4470, 11749, 23991, 32768, 0],
952+ [37, 3332, 14511, 21448, 32768, 0],
953+ [157, 6320, 13036, 17439, 32768, 0],
954+ [119, 6719, 12906, 29396, 32768, 0],
955+ [47, 5537, 12576, 21499, 32768, 0],
956+ [269, 6076, 11258, 23115, 32768, 0],
957+ [83, 5615, 12001, 17228, 32768, 0],
958+ [1968, 5556, 12023, 18547, 32768, 0],
959+];
crates/ec-av1/src/cdf_state.rsmodified+91 -14
@@ -20,6 +20,10 @@ pub(crate) enum TxbSet {
2020 Luma32,
2121 /// The 64x64 luma transform of a whole superblock, scanned as a 32x32.
2222 Luma64,
23+ /// The 16x16 luma transform of a 16x16 block.
24+ Luma16,
25+ /// The 8x8 transform of a chroma plane of a 16x16 block.
26+ Chroma8,
2327 /// The 16x16 transform of a chroma plane of a 32x32 block.
2428 Chroma16,
2529 /// The 32x32 transform of a chroma plane of a whole superblock.
@@ -45,6 +49,8 @@ pub(crate) struct TxbTables<'a> {
4549 pub br: &'a mut [[u16; 5]; 21],
4650 /// The sign of the DC.
4751 pub dc_sign: &'a mut [[u16; 3]; 3],
52+ /// The transform type, for the one size whose set holds more than one.
53+ pub tx_type: Option<&'a mut [u16; 6]>,
4854 }
4955
5056 /// Every table a key frame's tile writer adapts.
@@ -63,6 +69,32 @@ pub(crate) struct Cdfs {
6369 pub uv_mode_cfl: [[u16; 15]; 13],
6470 /// The angle a directional mode is nudged by.
6571 pub angle_delta: [[u16; 8]; 8],
72+ /// The one-context all-zero flag of a 16x16 luma transform.
73+ pub txb_skip_luma_16: [[u16; 3]; 1],
74+ /// The all-zero flag of an 8x8 chroma transform.
75+ pub txb_skip_chroma_8: [[u16; 3]; 3],
76+ /// The end-of-block group of a 16x16 luma transform.
77+ pub eob_pt_256_luma: [u16; 10],
78+ /// The end-of-block group of an 8x8 chroma transform.
79+ pub eob_pt_64_chroma: [u16; 8],
80+ /// The end-of-block offset bit of a 16x16 luma transform.
81+ pub eob_extra_luma_16: [[u16; 3]; 9],
82+ /// The same, for an 8x8 chroma transform.
83+ pub eob_extra_chroma_8: [[u16; 3]; 9],
84+ /// The base level of a 16x16 luma coefficient.
85+ pub base_luma_16: [[u16; 5]; 42],
86+ /// The base level of an 8x8 chroma coefficient.
87+ pub base_chroma_8: [[u16; 5]; 42],
88+ /// The last coefficient's base level, for a 16x16 luma transform.
89+ pub base_eob_luma_16: [[u16; 4]; 4],
90+ /// The same, for an 8x8 chroma transform.
91+ pub base_eob_chroma_8: [[u16; 4]; 4],
92+ /// The base-range tail of a 16x16 luma coefficient.
93+ pub br_luma_16: [[u16; 5]; 21],
94+ /// The base-range tail of an 8x8 chroma coefficient.
95+ pub br_chroma_8: [[u16; 5]; 21],
96+ /// The partition symbol of a 16x16 block.
97+ pub partition_w16: [[u16; 11]; 4],
6698 /// The one-context all-zero flag of a 32x32 luma transform.
6799 pub txb_skip_luma_32: [[u16; 3]; 1],
68100 /// The same, for a 64x64 luma transform.
@@ -110,6 +142,8 @@ pub(crate) struct Cdfs {
110142 pub br_chroma_32: [[u16; 5]; 21],
111143 /// The DC sign of a luma coefficient, shared by both luma sets.
112144 pub dc_sign_luma: [[u16; 3]; 3],
145+ /// The transform type of a 16x16 intra luma transform, by luma mode.
146+ pub intra_tx_type_16: [[u16; 6]; 13],
113147 /// The DC sign of a chroma coefficient, shared by both chroma sets.
114148 pub dc_sign_chroma: [[u16; 3]; 3],
115149 }
@@ -127,6 +161,19 @@ impl Cdfs {
127161 uv_mode_no_cfl: cdf::UV_MODE_NO_CFL,
128162 uv_mode_cfl: cdf::UV_MODE_CFL,
129163 angle_delta: cdf::ANGLE_DELTA,
164+ txb_skip_luma_16: [cdf::TXB_SKIP_LUMA_16],
165+ txb_skip_chroma_8: cdf::TXB_SKIP_CHROMA_8,
166+ eob_pt_256_luma: cdf::EOB_PT_256_LUMA,
167+ eob_pt_64_chroma: cdf::EOB_PT_64_CHROMA,
168+ eob_extra_luma_16: cdf::EOB_EXTRA_LUMA_16,
169+ eob_extra_chroma_8: cdf::EOB_EXTRA_CHROMA_8,
170+ base_luma_16: cdf::COEFF_BASE_LUMA_16,
171+ base_chroma_8: cdf::COEFF_BASE_CHROMA_8,
172+ base_eob_luma_16: cdf::COEFF_BASE_EOB_LUMA_16,
173+ base_eob_chroma_8: cdf::COEFF_BASE_EOB_CHROMA_8,
174+ br_luma_16: cdf::COEFF_BR_LUMA_16,
175+ br_chroma_8: cdf::COEFF_BR_CHROMA_8,
176+ partition_w16: cdf::PARTITION_W16,
130177 txb_skip_luma_32: [cdf::TXB_SKIP_LUMA_32],
131178 txb_skip_luma_64: [cdf::TXB_SKIP_LUMA_64],
132179 txb_skip_chroma_16: cdf::TXB_SKIP_CHROMA_16,
@@ -150,12 +197,13 @@ impl Cdfs {
150197 br_chroma_16: cdf::COEFF_BR_CHROMA_16,
151198 br_chroma_32: cdf::COEFF_BR_CHROMA_32,
152199 dc_sign_luma: cdf::DC_SIGN_LUMA,
200+ intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16,
153201 dc_sign_chroma: cdf::DC_SIGN_CHROMA,
154202 }
155203 }
156204
157205 /// The tables one table set is coded with, borrowed out of the state.
158- pub fn txb(&mut self, set: TxbSet) -> TxbTables<'_> {
206+ pub fn txb(&mut self, set: TxbSet, mode: usize) -> TxbTables<'_> {
159207 match set {
160208 TxbSet::Luma32 => TxbTables {
161209 side: 32,
@@ -166,6 +214,7 @@ impl Cdfs {
166214 base_eob: &mut self.base_eob_luma_32,
167215 br: &mut self.br_luma_32,
168216 dc_sign: &mut self.dc_sign_luma,
217+ tx_type: None,
169218 },
170219 TxbSet::Luma64 => TxbTables {
171220 side: 32,
@@ -176,6 +225,29 @@ impl Cdfs {
176225 base_eob: &mut self.base_eob_luma_64,
177226 br: &mut self.br_luma_32,
178227 dc_sign: &mut self.dc_sign_luma,
228+ tx_type: None,
229+ },
230+ TxbSet::Luma16 => TxbTables {
231+ side: 16,
232+ txb_skip: &mut self.txb_skip_luma_16,
233+ eob_pt: &mut self.eob_pt_256_luma,
234+ eob_extra: &mut self.eob_extra_luma_16,
235+ base: &mut self.base_luma_16,
236+ base_eob: &mut self.base_eob_luma_16,
237+ br: &mut self.br_luma_16,
238+ dc_sign: &mut self.dc_sign_luma,
239+ tx_type: Some(&mut self.intra_tx_type_16[mode]),
240+ },
241+ TxbSet::Chroma8 => TxbTables {
242+ side: 8,
243+ txb_skip: &mut self.txb_skip_chroma_8,
244+ eob_pt: &mut self.eob_pt_64_chroma,
245+ eob_extra: &mut self.eob_extra_chroma_8,
246+ base: &mut self.base_chroma_8,
247+ base_eob: &mut self.base_eob_chroma_8,
248+ br: &mut self.br_chroma_8,
249+ dc_sign: &mut self.dc_sign_chroma,
250+ tx_type: None,
179251 },
180252 TxbSet::Chroma16 => TxbTables {
181253 side: 16,
@@ -186,6 +258,7 @@ impl Cdfs {
186258 base_eob: &mut self.base_eob_chroma_16,
187259 br: &mut self.br_chroma_16,
188260 dc_sign: &mut self.dc_sign_chroma,
261+ tx_type: None,
189262 },
190263 TxbSet::Chroma32 => TxbTables {
191264 side: 32,
@@ -196,6 +269,7 @@ impl Cdfs {
196269 base_eob: &mut self.base_eob_chroma_32,
197270 br: &mut self.br_chroma_32,
198271 dc_sign: &mut self.dc_sign_chroma,
272+ tx_type: None,
199273 },
200274 }
201275 }
@@ -212,8 +286,8 @@ mod tests {
212286 #[test]
213287 fn the_two_luma_sets_share_the_base_range_table() {
214288 let mut cdfs = Cdfs::new();
215- cdfs.txb(TxbSet::Luma64).br[0][0] = 1;
216- assert_eq!(cdfs.txb(TxbSet::Luma32).br[0][0], 1);
289+ cdfs.txb(TxbSet::Luma64, 0).br[0][0] = 1;
290+ assert_eq!(cdfs.txb(TxbSet::Luma32, 0).br[0][0], 1);
217291 }
218292
219293 /// Both luma sets read one DC sign table, and both chroma sets another;
@@ -221,12 +295,12 @@ mod tests {
221295 #[test]
222296 fn the_sign_tables_are_shared_within_a_plane_type_and_not_across() {
223297 let mut cdfs = Cdfs::new();
224- cdfs.txb(TxbSet::Luma32).dc_sign[1][0] = 1;
225- cdfs.txb(TxbSet::Chroma16).dc_sign[2][0] = 2;
226- assert_eq!(cdfs.txb(TxbSet::Luma64).dc_sign[1][0], 1);
227- assert_eq!(cdfs.txb(TxbSet::Chroma32).dc_sign[2][0], 2);
228- assert_ne!(cdfs.txb(TxbSet::Chroma32).dc_sign[1][0], 1);
229- assert_ne!(cdfs.txb(TxbSet::Luma64).dc_sign[2][0], 2);
298+ cdfs.txb(TxbSet::Luma32, 0).dc_sign[1][0] = 1;
299+ cdfs.txb(TxbSet::Chroma16, 0).dc_sign[2][0] = 2;
300+ assert_eq!(cdfs.txb(TxbSet::Luma64, 0).dc_sign[1][0], 1);
301+ assert_eq!(cdfs.txb(TxbSet::Chroma32, 0).dc_sign[2][0], 2);
302+ assert_ne!(cdfs.txb(TxbSet::Chroma32, 0).dc_sign[1][0], 1);
303+ assert_ne!(cdfs.txb(TxbSet::Luma64, 0).dc_sign[2][0], 2);
230304 }
231305
232306 /// The end-of-block table a 1024-position transform reads is shared by both
@@ -235,9 +309,9 @@ mod tests {
235309 #[test]
236310 fn the_luma_end_of_block_table_is_shared_and_chromas_is_not() {
237311 let mut cdfs = Cdfs::new();
238- cdfs.txb(TxbSet::Luma32).eob_pt[0] = 7;
239- assert_eq!(cdfs.txb(TxbSet::Luma64).eob_pt[0], 7);
240- assert_ne!(cdfs.txb(TxbSet::Chroma32).eob_pt[0], 7);
312+ cdfs.txb(TxbSet::Luma32, 0).eob_pt[0] = 7;
313+ assert_eq!(cdfs.txb(TxbSet::Luma64, 0).eob_pt[0], 7);
314+ assert_ne!(cdfs.txb(TxbSet::Chroma32, 0).eob_pt[0], 7);
241315 }
242316
243317 /// Every set starts from the spec's defaults, so a tile that adapts nothing
@@ -245,9 +319,12 @@ mod tests {
245319 #[test]
246320 fn the_state_starts_at_the_defaults() {
247321 let mut cdfs = Cdfs::new();
248- assert_eq!(cdfs.txb(TxbSet::Luma32).base[3], cdf::COEFF_BASE_LUMA_32[3]);
249322 assert_eq!(
250- cdfs.txb(TxbSet::Chroma16).eob_extra[2],
323+ cdfs.txb(TxbSet::Luma32, 0).base[3],
324+ cdf::COEFF_BASE_LUMA_32[3]
325+ );
326+ assert_eq!(
327+ cdfs.txb(TxbSet::Chroma16, 0).eob_extra[2],
251328 cdf::EOB_EXTRA_CHROMA_16[2]
252329 );
253330 assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]);
crates/ec-av1/src/encode.rsmodified+323 -73
@@ -22,17 +22,28 @@ use ec_av1_syntax::{
2222 use ec_core::{Error, Result};
2323
2424 use crate::cdf;
25+use crate::cdf_state::TxbSet;
2526 use crate::frame::frame_obu;
2627 use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};
2728 use crate::obu::temporal_delimiter;
2829 use crate::quant::ac_q;
2930 use crate::sequence::sequence_header_obu;
30-use crate::tile::{BlockCoeffs, Coeff, INTRA_MODE_CTX, Superblock, sb_coeff_key_frame_tile};
31+use crate::tile::{
32+ BlockCoeffs, Coeff, INTRA_MODE_CTX, Quadrant, Superblock, partition_bits,
33+ sb_coeff_key_frame_tile,
34+};
3135 use crate::transform::{dequant_and_inverse, forward_and_quantize};
3236
33-/// The side of the luma blocks this encoder codes, in samples.
37+/// The side of the larger of the two luma blocks this encoder codes, in
38+/// samples.
3439 const BLOCK: usize = 32;
3540
41+/// The side of the smaller one, which a 32x32 block may be split into four of.
42+const SUB: usize = 16;
43+
44+/// The side of a superblock, which is what the partition tree starts from.
45+const SUPERBLOCK: usize = 64;
46+
3647 /// How heavily the mode search weighs rate against squared error, in units of
3748 /// the quantizer's reconstruction step squared per bit.
3849 ///
@@ -57,6 +68,16 @@ fn lambda_scale() -> f64 {
5768 }
5869 }
5970
71+/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
72+/// four cost less. Set from the measurement in the lane report.
73+const SPLIT_BLOCKS: bool = true;
74+
75+/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
76+/// by calling [`encode_key_frame_inner`] both ways.
77+fn split_blocks() -> bool {
78+ SPLIT_BLOCKS
79+}
80+
6081 /// One 8-bit planar 4:2:0 picture.
6182 #[derive(Clone, Debug, PartialEq, Eq)]
6283 pub struct Picture {
@@ -117,7 +138,8 @@ pub struct Encoded {
117138 /// reconstruction, which its prediction was built on.
118139 pub reconstruction: Picture,
119140 /// The luma intra mode each block was coded under, in the order the blocks
120- /// are coded — raster order among the quadrants of each superblock.
141+ /// are coded — raster order among the quadrants of each superblock, and
142+ /// among the four 16x16 blocks of a quadrant that was split.
121143 pub modes: Vec<u8>,
122144 }
123145
@@ -284,7 +306,9 @@ impl Plane<'_> {
284306 /// levels, the block the decoder would reconstruct, the squared error
285307 /// against the source and an estimate of what the levels cost in bits.
286308 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial {
287- let At { x, y, side, reach } = at;
309+ let At {
310+ x, y, side, reach, ..
311+ } = at;
288312 let (above, left, corner) = self.edges(x, y, side, reach);
289313 let mut prediction = vec![0u8; side * side];
290314 crate::intra::predict(
@@ -321,12 +345,9 @@ impl Plane<'_> {
321345 }
322346 }
323347 // What the levels cost is priced through the same CDFs the tile writer
324- // will code them with, so the search ranks modes by the bits they
325- // actually spend. Chroma blocks are not searched, so only the 32x32
326- // luma table is asked for.
327- let bits = if side != BLOCK {
328- 0.0
329- } else if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
348+ // will code them with, so the search ranks modes -- and the partition
349+ // trial ranks trees -- by the bits they actually spend.
350+ let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
330351 // What the search used before it could price a block exactly: a
331352 // level costs its magnitude's width plus a sign and a run. Kept
332353 // reachable from the sweep so the two rate terms can be compared
@@ -337,7 +358,7 @@ impl Plane<'_> {
337358 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
338359 .sum()
339360 } else {
340- crate::tile::luma_32_coeff_bits(&levels)
361+ crate::tile::coeff_bits(&levels, at.set)
341362 };
342363 Trial {
343364 levels,
@@ -355,16 +376,44 @@ impl Plane<'_> {
355376 }
356377 }
357378
358- /// Codes one block under a fixed mode, committing it.
359- fn code_block(&mut self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Vec<Coeff> {
379+ /// Codes one block under a fixed mode, committing it, and hands back what
380+ /// it cost: its squared error and the bits its levels spend.
381+ fn code_block(
382+ &mut self,
383+ at: At,
384+ mode: u8,
385+ base_q_idx: u8,
386+ deadzone: f64,
387+ ) -> (Vec<Coeff>, f64, f64) {
360388 let trial = self.trial(at, mode, base_q_idx, deadzone);
361389 self.commit(at.x, at.y, at.side, &trial);
362- coeffs(&trial.levels, at.side)
390+ (coeffs(&trial.levels, at.side), trial.sse, trial.bits)
391+ }
392+
393+ /// The reconstructed samples of one square, so that a partition trial can
394+ /// be undone.
395+ fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
396+ (y..y + side)
397+ .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec())
398+ .collect()
399+ }
400+
401+ /// Puts a snapshot back.
402+ fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) {
403+ for row in 0..side {
404+ self.reconstruction[(y + row) * self.width + x..][..side]
405+ .copy_from_slice(&samples[row * side..][..side]);
406+ }
363407 }
364408
365409 /// Codes one block under every mode the search offers and commits the one
366410 /// whose squared error and estimated rate come out cheapest.
367- fn search_block(&mut self, at: At, search: &Search, mode_bits: &[f64; 13]) -> (Vec<Coeff>, u8) {
411+ fn search_block(
412+ &mut self,
413+ at: At,
414+ search: &Search,
415+ mode_bits: &[f64; 13],
416+ ) -> (Vec<Coeff>, u8, f64) {
368417 let mut best: Option<(f64, u8, Trial)> = None;
369418 for &mode in search.modes {
370419 let trial = self.trial(at, mode, search.base_q_idx, search.deadzone);
@@ -376,9 +425,9 @@ impl Plane<'_> {
376425 best = Some((cost, mode, trial));
377426 }
378427 }
379- let (_, mode, trial) = best.expect("the search offers at least one mode");
428+ let (cost, mode, trial) = best.expect("the search offers at least one mode");
380429 self.commit(at.x, at.y, at.side, &trial);
381- (coeffs(&trial.levels, at.side), mode)
430+ (coeffs(&trial.levels, at.side), mode, cost)
382431 }
383432 }
384433
@@ -390,34 +439,44 @@ struct At {
390439 y: usize,
391440 side: usize,
392441 reach: Reach,
442+ /// Which of the tile writer's coefficient tables this block's levels are
443+ /// coded with, and so which the search prices them through.
444+ set: TxbSet,
393445 }
394446
395447 /// Which of the samples past a block's own edges the decoder has decoded by
396448 /// the time it predicts the block, and so which a directional mode may read.
397449 ///
398450 /// The decoder derives these from its `BlockDecoded` flags, which are cleared
399-/// per superblock (`clear_block_decoded_flags`, spec 7.4): the row above the
400-/// superblock counts as decoded out to the end of the *tile*, while the column
401-/// to its left counts only as far as the superblock's own height, and every
402-/// position inside the superblock starts undecoded. For the four 32x32
403-/// quadrants of a 64x64 superblock that comes to: the samples above-right are
404-/// decoded for all but the last quadrant -- the one whose above-right lies
405-/// inside the superblock to the right, which raster order has not reached --
406-/// and the samples below-left only for the first, the only one whose left
407-/// column continues into the superblock beside it.
451+/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
452+/// that map, this reads the answer the same way libaom and rav1e do: for a
453+/// block whose transform covers it whole, whether the samples above its right
454+/// (or below its left) are decoded depends only on where the block sits inside
455+/// its 64x64 superblock, which is a pinned table per block size.
408456 #[derive(Clone, Copy)]
409457 struct Reach {
410458 above_right: bool,
411459 below_left: bool,
412460 }
413461
462+/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
463+/// libaom): for a block that is neither in the superblock's top row nor its
464+/// rightmost column, whether the block above and to its right is coded before
465+/// it. Indexed by the block's position in the superblock, in blocks of its own
466+/// size, as `row * (16 >> log2 mi width) + col`, bit by bit from the low end.
467+const HAS_TOP_RIGHT: [&[u8]; 2] = [&[255, 85, 119, 85, 127, 85, 119, 85], &[95, 87]];
468+
469+/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
470+/// left.
471+const HAS_BOTTOM_LEFT: [&[u8]; 2] = [&[84, 16, 84, 0, 84, 16, 84, 0], &[4, 4]];
472+
414473 impl Reach {
415- /// The reach of the quadrant coded `quadrant`-th in a superblock, counting
416- /// in raster order among the four.
417- fn quadrant(quadrant: usize) -> Self {
474+ /// What a block of `side` samples at `(x, y)` may read past its own edges,
475+ /// in a frame of `width` by `height`.
476+ fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {
418477 Self {
419- above_right: quadrant != 3,
420- below_left: quadrant == 0,
478+ above_right: y > 0 && x + side < width && Self::top_right(side, x, y),
479+ below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),
421480 }
422481 }
423482
@@ -429,10 +488,60 @@ impl Reach {
429488 below_left: false,
430489 }
431490 }
491+
492+ /// `has_top_right` for a block whose transform covers it whole: the top
493+ /// row of a superblock reads into the superblock above, which is decoded;
494+ /// the rightmost column would read into the superblock to the right, which
495+ /// is not; and everything between is the table's to answer.
496+ fn top_right(side: usize, x: usize, y: usize) -> bool {
497+ let (row, col, per_side) = Self::position(side, x, y);
498+ if row == 0 {
499+ return true;
500+ }
501+ if col + 1 == per_side {
502+ return false;
503+ }
504+ Self::bit(HAS_TOP_RIGHT[Self::table(side)], row * per_side + col)
505+ }
506+
507+ /// `has_bottom_left` for such a block: the leftmost column of a superblock
508+ /// reads into the superblock to its left, which is decoded only as far
509+ /// down as its own bottom; the bottom row would read into the superblock
510+ /// below, which is not decoded at all; and the table answers the rest.
511+ fn bottom_left(side: usize, x: usize, y: usize) -> bool {
512+ let (row, col, per_side) = Self::position(side, x, y);
513+ if col == 0 {
514+ return row * side + side < SUPERBLOCK;
515+ }
516+ if row + 1 == per_side {
517+ return false;
518+ }
519+ Self::bit(HAS_BOTTOM_LEFT[Self::table(side)], row * per_side + col)
520+ }
521+
522+ /// Where a block sits inside its superblock, in blocks of its own size,
523+ /// and how many of them a superblock is across.
524+ fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) {
525+ (
526+ (y % SUPERBLOCK) / side,
527+ (x % SUPERBLOCK) / side,
528+ SUPERBLOCK / side,
529+ )
530+ }
531+
532+ /// Which of the two block sizes the encoder codes a table row is for.
533+ fn table(side: usize) -> usize {
534+ usize::from(side == BLOCK)
535+ }
536+
537+ /// One bit of a table, counting from the low end of its first byte.
538+ fn bit(table: &[u8], index: usize) -> bool {
539+ (table[index / 8] >> (index % 8)) & 1 != 0
540+ }
432541 }
433542
434543 /// What one symbol costs against a CDF, in bits.
435-fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
544+pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
436545 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
437546 let probability = f64::from(cdf[symbol] - low) / 32768.0;
438547 -probability.log2()
@@ -447,6 +556,86 @@ fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
447556 /// Without this the search is blind to what a mode costs to name, which is not
448557 /// a rounding error: a directional mode on a picture that does not run that way
449558 /// is a rate loss the squared error never sees.
559+/// Codes one square of the picture as a single block: searches the luma mode,
560+/// codes both chroma planes DC, and hands back the block and what it cost --
561+/// squared error plus lambda times the bits its symbols spend.
562+fn code_square(
563+ luma: &mut Plane,
564+ chroma: &mut [Plane; 2],
565+ (x, y): (usize, usize),
566+ side: usize,
567+ search: &Search,
568+ mode_bits: &[f64; 13],
569+) -> (BlockCoeffs, f64) {
570+ let (luma_set, chroma_set) = if side == BLOCK {
571+ (TxbSet::Luma32, TxbSet::Chroma16)
572+ } else {
573+ (TxbSet::Luma16, TxbSet::Chroma8)
574+ };
575+ let (luma_coeffs, mode, mut cost) = luma.search_block(
576+ At {
577+ x,
578+ y,
579+ side,
580+ reach: Reach::of(side, x, y, luma.width, luma.height),
581+ set: luma_set,
582+ },
583+ search,
584+ mode_bits,
585+ );
586+ // Chroma is predicted DC because that is the mode the tile writer codes
587+ // for it; what it costs still counts towards the partition decision.
588+ let mut planes = [Vec::new(), Vec::new()];
589+ for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) {
590+ let (levels, sse, bits) = plane.code_block(
591+ At {
592+ x: x / 2,
593+ y: y / 2,
594+ side: side / 2,
595+ reach: Reach::none(),
596+ set: chroma_set,
597+ },
598+ DC_PRED,
599+ search.base_q_idx,
600+ search.deadzone,
601+ );
602+ *coeffs = levels;
603+ cost += sse + search.lambda * bits;
604+ }
605+ let [u, v] = planes;
606+ (
607+ BlockCoeffs {
608+ u,
609+ v,
610+ luma: luma_coeffs,
611+ mode,
612+ },
613+ cost,
614+ )
615+}
616+
617+/// The reconstructed samples one 32x32 square covers in all three planes, so
618+/// that a partition trial can be undone.
619+fn snapshot(luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize)) -> [Vec<u8>; 3] {
620+ [
621+ luma.snapshot(x, y, BLOCK),
622+ chroma[0].snapshot(x / 2, y / 2, BLOCK / 2),
623+ chroma[1].snapshot(x / 2, y / 2, BLOCK / 2),
624+ ]
625+}
626+
627+/// Puts such a snapshot back.
628+fn restore(
629+ luma: &mut Plane,
630+ chroma: &mut [Plane; 2],
631+ (x, y): (usize, usize),
632+ saved: &[Vec<u8>; 3],
633+) {
634+ luma.restore(x, y, BLOCK, &saved[0]);
635+ chroma[0].restore(x / 2, y / 2, BLOCK / 2, &saved[1]);
636+ chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]);
637+}
638+
450639 fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
451640 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
452641 [INTRA_MODE_CTX[usize::from(left_mode)]];
@@ -521,6 +710,18 @@ pub fn encode_key_frame_with_modes(
521710 base_q_idx: u8,
522711 deadzone: f64,
523712 modes: &[u8],
713+) -> Result<Encoded> {
714+ encode_key_frame_inner(picture, base_q_idx, deadzone, modes, split_blocks())
715+}
716+
717+/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
718+/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways.
719+fn encode_key_frame_inner(
720+ picture: &Picture,
721+ base_q_idx: u8,
722+ deadzone: f64,
723+ modes: &[u8],
724+ split_blocks: bool,
524725 ) -> Result<Encoded> {
525726 picture.check()?;
526727 if modes.is_empty() {
@@ -573,8 +774,10 @@ pub fn encode_key_frame_with_modes(
573774 // what picks the CDF the next block's mode is coded against -- the same
574775 // bookkeeping the tile writer keeps, so that the search is costing the
575776 // symbol the writer will actually write.
576- let mut above_mode = vec![DC_PRED; cols];
577- let mut left_mode = vec![DC_PRED; rows];
777+ // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
778+ // because a 32x32 block may be split into four 16x16 ones.
779+ let mut above_mode = vec![DC_PRED; cols * 2];
780+ let mut left_mode = vec![DC_PRED; rows * 2];
578781 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
579782 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
580783 let mut modes = Vec::with_capacity(cols * rows);
@@ -590,47 +793,58 @@ pub fn encode_key_frame_with_modes(
590793 continue;
591794 }
592795 let (x, y) = (col * BLOCK, row * BLOCK);
593- let (luma_coeffs, mode) = luma.search_block(
594- At {
595- x,
596- y,
597- side: BLOCK,
598- reach: Reach::quadrant(quadrant),
599- },
796+ let (c0, r0) = (col * 2, row * 2);
797+ let base = snapshot(&luma, &chroma, (x, y));
798+
799+ // What the whole 32x32 costs, including the partition symbol
800+ // that says it is not split.
801+ let (whole, mut cost_whole) = code_square(
802+ &mut luma,
803+ &mut chroma,
804+ (x, y),
805+ BLOCK,
600806 &search,
601- &mode_bits(above_mode[col], left_mode[row]),
807+ &mode_bits(above_mode[c0], left_mode[r0]),
602808 );
603- above_mode[col] = mode;
604- left_mode[row] = mode;
605- modes.push(mode);
606- blocks.push(BlockCoeffs {
607- // Chroma is predicted DC because that is the mode the tile
608- // writer codes for it.
609- u: chroma[0].code_block(
610- At {
611- x: x / 2,
612- y: y / 2,
613- side: BLOCK / 2,
614- reach: Reach::none(),
615- },
616- DC_PRED,
617- base_q_idx,
618- deadzone,
619- ),
620- v: chroma[1].code_block(
621- At {
622- x: x / 2,
623- y: y / 2,
624- side: BLOCK / 2,
625- reach: Reach::none(),
626- },
627- DC_PRED,
628- base_q_idx,
629- deadzone,
630- ),
631- luma: luma_coeffs,
632- mode,
633- });
809+ cost_whole += search.lambda * partition_bits(BLOCK, false);
810+ let after_whole = snapshot(&luma, &chroma, (x, y));
811+
812+ // What four 16x16 blocks cost instead, each searched against
813+ // the reconstruction the ones before it left.
814+ restore(&mut luma, &mut chroma, (x, y), &base);
815+ let mut split = Vec::with_capacity(4);
816+ let mut cost_split = search.lambda
817+ * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
818+ let mut split_modes = [DC_PRED; 4];
819+ for (sub, sub_mode) in split_modes.iter_mut().enumerate() {
820+ let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
821+ let (block, cost) = code_square(
822+ &mut luma,
823+ &mut chroma,
824+ (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
825+ SUB,
826+ &search,
827+ &mode_bits(above_mode[sc], left_mode[sr]),
828+ );
829+ cost_split += cost;
830+ *sub_mode = block.mode;
831+ above_mode[sc] = block.mode;
832+ left_mode[sr] = block.mode;
833+ split.push(block);
834+ }
835+
836+ if split_blocks && cost_split < cost_whole {
837+ modes.extend_from_slice(&split_modes);
838+ blocks.push(Quadrant::Split(split));
839+ } else {
840+ restore(&mut luma, &mut chroma, (x, y), &after_whole);
841+ for cell in 0..2 {
842+ above_mode[c0 + cell] = whole.mode;
843+ left_mode[r0 + cell] = whole.mode;
844+ }
845+ modes.push(whole.mode);
846+ blocks.push(Quadrant::Whole(whole));
847+ }
634848 }
635849 superblocks.push(Superblock::Split(blocks));
636850 }
@@ -854,6 +1068,42 @@ mod tests {
8541068 }
8551069 }
8561070
1071+ /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
1072+ /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
1073+ /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
1074+ #[test]
1075+ #[ignore = "a sweep, not a gate"]
1076+ fn probe_split() {
1077+ for (name, picture) in sweep_pictures() {
1078+ let ladder = |split: bool| {
1079+ let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
1080+ .iter()
1081+ .map(|&q| {
1082+ let encoded =
1083+ encode_key_frame_inner(&picture, q, 0.5, &KEY_FRAME_MODES, split)
1084+ .unwrap();
1085+ (
1086+ psnr(&encoded.reconstruction.y, picture.y.as_slice()),
1087+ (encoded.stream.len() as f64).log10(),
1088+ )
1089+ })
1090+ .collect();
1091+ points.sort_by(|a, b| a.0.total_cmp(&b.0));
1092+ points
1093+ };
1094+ let (whole, split) = (ladder(false), ladder(true));
1095+ let blocks = encode_key_frame_inner(&picture, 90, 0.5, &KEY_FRAME_MODES, true)
1096+ .unwrap()
1097+ .modes
1098+ .len();
1099+ let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
1100+ println!(
1101+ "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
1102+ bd_rate(&whole, &split) * 100.0
1103+ );
1104+ }
1105+ }
1106+
8571107 /// A striped picture, running one way or the other. The stripes are what
8581108 /// separates a vertical predictor from a horizontal one: a mode search
8591109 /// reading a transposed edge would pick the wrong one of the pair, which no
crates/ec-av1/src/tile.rsmodified+511 -140
@@ -64,6 +64,9 @@ const SB_MI: u32 = 16;
6464
6565 /// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
6666 const NUM_BASE_LEVELS: i32 = 2;
67+/// Where DCT_DCT sits in the spec's `Tx_Type_Intra_Inv_Set2`, the set a 16x16
68+/// intra luma transform picks its type from.
69+const TX_TYPE_DCT_DCT_SET2: usize = 1;
6770 /// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
6871 /// Golomb tail takes over.
6972 const COEFF_BASE_RANGE: i32 = 12;
@@ -225,7 +228,7 @@ pub fn dc_key_frame_tile_levels(
225228 write_dc_coeffs(
226229 &mut enc,
227230 dc_level,
228- dc_sign_ctx(above[c as usize], left),
231+ dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
229232 &cdf::TXB_SKIP_LUMA_64,
230233 &cdf::COEFF_BASE_EOB_LUMA_64_DC,
231234 );
@@ -301,7 +304,7 @@ pub fn split_dc_key_frame_tile(
301304 write_dc_coeffs(
302305 &mut enc,
303306 dc_level,
304- dc_sign_ctx(above[c as usize], left[r as usize]),
307+ dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left[r as usize])),
305308 &cdf::TXB_SKIP_LUMA_32,
306309 &cdf::COEFF_BASE_EOB_LUMA_32[0],
307310 );
@@ -363,8 +366,19 @@ impl From<Vec<Coeff>> for BlockCoeffs {
363366
364367 /// Side of the luma transform the coefficient writer codes.
365368 const TX32: usize = 32;
366-/// Side of the chroma transform beside it at 4:2:0.
369+/// Side of the larger of the two blocks a superblock splits into, in samples.
370+const BLOCK: usize = 32;
371+/// Side of the chroma transform beside it at 4:2:0, and of the luma transform
372+/// of a 16x16 block.
367373 const TX16: usize = 16;
374+/// Side of the chroma transform of a 16x16 block at 4:2:0.
375+const TX8: usize = 8;
376+/// Side of a superblock, in samples, which is the size a block outside the
377+/// tile reads as.
378+const SB: usize = 64;
379+/// Side of the smallest block the writer codes, in samples, which is the grid
380+/// the neighbour bookkeeping is kept on.
381+const SUB: usize = 16;
368382
369383 /// What one coded block leaves behind for the blocks that read it as a
370384 /// neighbour: whether it coded anything at all, and the sign of its DC.
@@ -411,11 +425,124 @@ pub enum Superblock {
411425 /// top-left 32x32 carries coefficients — and whose chroma transforms are
412426 /// 32x32 each at 4:2:0.
413427 Whole(BlockCoeffs),
414- /// The 32x32 blocks the superblock is split into, each with a 32x32 luma
415- /// transform and a 16x16 transform per chroma plane.
428+ /// The 32x32 quadrants the superblock is split into, each either one
429+ /// block or four 16x16 blocks of its own.
430+ Split(Vec<Quadrant>),
431+}
432+
433+/// One 32x32 quadrant of a split superblock.
434+#[derive(Clone, Debug, PartialEq, Eq)]
435+pub enum Quadrant {
436+ /// One 32x32 block, with a 32x32 luma transform and a 16x16 transform per
437+ /// chroma plane.
438+ Whole(BlockCoeffs),
439+ /// The four 16x16 blocks it is split into, in raster order, each with a
440+ /// 16x16 luma transform and an 8x8 transform per chroma plane.
416441 Split(Vec<BlockCoeffs>),
417442 }
418443
444+impl Quadrant {
445+ /// The blocks it carries, in the order they are coded.
446+ fn blocks(&self) -> &[BlockCoeffs] {
447+ match self {
448+ Quadrant::Whole(block) => std::slice::from_ref(block),
449+ Quadrant::Split(blocks) => blocks.as_slice(),
450+ }
451+ }
452+}
453+
454+/// What the blocks above and to the left of the one being coded left behind,
455+/// kept on the 16x16 grid the smallest block sits on.
456+struct Neighbours {
457+ /// Per plane, whether the neighbour coded anything and the sign of its DC.
458+ above: Vec<[Neighbour; 3]>,
459+ /// The same, down the left edge.
460+ left: Vec<[Neighbour; 3]>,
461+ /// The neighbour's luma intra mode, which picks the CDF the next block's
462+ /// mode is coded with.
463+ above_mode: Vec<usize>,
464+ /// The same, down the left edge.
465+ left_mode: Vec<usize>,
466+ /// The side of the neighbour block, in samples, which is what the
467+ /// partition symbol's context reads.
468+ above_side: Vec<usize>,
469+ /// The same, down the left edge.
470+ left_side: Vec<usize>,
471+}
472+
473+/// What one plane's neighbours leave for a block, gathered across every cell
474+/// the block spans -- which is what the decoder's own derivation reads
475+/// (spec 5.11.39), and what a single cell only stands in for while every block
476+/// is the same size.
477+#[derive(Clone, Copy, Default)]
478+struct Around {
479+ /// Whether any transform block above this one carried a coefficient.
480+ above_coded: bool,
481+ /// The same, to the left.
482+ left_coded: bool,
483+ /// The running vote of the neighbours' DC signs: negative DCs count down,
484+ /// positive ones up, and a neighbour with no DC does not count.
485+ dc_vote: i32,
486+}
487+
488+impl Neighbours {
489+ /// The state a tile starts from: a block outside it reads as `DC_PRED`,
490+ /// as having coded nothing, and as unsplit.
491+ fn new(cols: usize, rows: usize) -> Self {
492+ Self {
493+ above: vec![[Neighbour::default(); 3]; cols],
494+ left: vec![[Neighbour::default(); 3]; rows],
495+ above_mode: vec![DC_PRED; cols],
496+ left_mode: vec![DC_PRED; rows],
497+ above_side: vec![SB; cols],
498+ left_side: vec![SB; rows],
499+ }
500+ }
501+
502+ /// Clears the left edge, which a tile starts every superblock row with.
503+ fn start_row(&mut self) {
504+ self.left.iter_mut().for_each(|l| *l = Default::default());
505+ self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
506+ self.left_side.iter_mut().for_each(|s| *s = SB);
507+ }
508+
509+ /// Writes one coded block into every 16x16 column and row it covers.
510+ fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
511+ let (r, c) = at;
512+ let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
513+ for cell in 0..side / SUB {
514+ self.above[c + cell] = states;
515+ self.left[r + cell] = states;
516+ self.above_mode[c + cell] = mode;
517+ self.left_mode[r + cell] = mode;
518+ self.above_side[c + cell] = side;
519+ self.left_side[r + cell] = side;
520+ }
521+ }
522+
523+ /// The context of a block's partition symbol (spec 9.3): whether the
524+ /// blocks above it and to its left were split finer than it is.
525+ /// The gathered state of the blocks above and to the left of one block,
526+ /// per plane.
527+ fn around(&self, (r, c): (usize, usize), side: usize) -> [Around; 3] {
528+ std::array::from_fn(|plane| {
529+ let mut around = Around::default();
530+ for cell in 0..side / SUB {
531+ let (above, left) = (&self.above[c + cell][plane], &self.left[r + cell][plane]);
532+ around.above_coded |= above.coded;
533+ around.left_coded |= left.coded;
534+ around.dc_vote += dc_vote(above.dc) + dc_vote(left.dc);
535+ }
536+ around
537+ })
538+ }
539+
540+ fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
541+ let (r, c) = at;
542+ 2 * usize::from(self.left_side[r] * 2 <= side) + usize::from(self.above_side[c] * 2 <= side)
543+ }
544+}
545+
419546 /// Writes the payload of a one-tile key frame built from `superblocks`, each
420547 /// either one 64x64 block or the 32x32 blocks it splits into.
421548 ///
@@ -449,14 +576,19 @@ pub fn sb_coeff_key_frame_tile(
449576 "a coefficient key frame needs one entry per superblock",
450577 ));
451578 }
452- let bad_mode = superblocks
453- .iter()
454- .flat_map(|sb| match sb {
455- Superblock::Whole(b) => std::slice::from_ref(b),
456- Superblock::Split(b) => b.as_slice(),
457- })
458- .find(|b| usize::from(b.mode) >= INTRA_MODES);
459- if let Some(bad) = bad_mode {
579+ let mut coded: Vec<&BlockCoeffs> = Vec::new();
580+ for superblock in superblocks {
581+ match superblock {
582+ Superblock::Whole(block) => coded.push(block),
583+ Superblock::Split(quadrants) => {
584+ coded.extend(quadrants.iter().flat_map(Quadrant::blocks));
585+ }
586+ }
587+ }
588+ if let Some(bad) = coded
589+ .into_iter()
590+ .find(|b| usize::from(b.mode) >= INTRA_MODES)
591+ {
460592 return Err(Error::unsupported(
461593 "AV1 tile",
462594 format!(
@@ -473,28 +605,14 @@ pub fn sb_coeff_key_frame_tile(
473605 ));
474606 }
475607
608+ let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
476609 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
477610 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
478- let scans = [default_scan(TX32), default_scan(TX16)];
479- // What the blocks above and to the left of the one being coded left
480- // behind, per plane, one entry per 32x32 column and row. The left column
481- // is reset at every superblock row because a tile starts each row with no
611+ let scans = [default_scan(TX32), default_scan(TX16), default_scan(TX8)];
612+ // The blocks above and to the left, on the 16x16 grid. The left edge is
613+ // reset at every superblock row because a tile starts each row with no
482614 // left neighbour.
483- let mut above = vec![[Neighbour::default(); 3]; cols as usize];
484- let mut left = vec![[Neighbour::default(); 3]; rows as usize];
485- // The luma intra mode of those same neighbours, which picks the CDF the
486- // next block's mode is coded with. A block outside the tile reads as
487- // `DC_PRED`, which is what these start and are reset to.
488- let mut above_mode = vec![DC_PRED; cols as usize];
489- let mut left_mode = vec![DC_PRED; rows as usize];
490- // Whether those neighbours were split, which is what the superblock's
491- // partition symbol reads: the context is bit three of the neighbour's
492- // entry in the spec's partition-context table, and of the sizes a
493- // superblock can leave behind only a 32x32 block sets it. A neighbour
494- // outside the tile reads as an unsplit one, which is what these start and
495- // are reset to.
496- let mut above_split = vec![false; cols as usize];
497- let mut left_split = vec![false; rows as usize];
615+ let mut neighbours = Neighbours::new(cols as usize * 2, rows as usize * 2);
498616
499617 // The tile adapts every non-literal CDF it writes, exactly as the decoder
500618 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
@@ -502,12 +620,10 @@ pub fn sb_coeff_key_frame_tile(
502620 let mut cdfs = Cdfs::new();
503621 let mut enc = SymbolEncoder::new();
504622 for sb_r in 0..sb_rows {
505- left.iter_mut().for_each(|l| *l = Default::default());
506- left_mode.iter_mut().for_each(|m| *m = DC_PRED);
507- left_split.iter_mut().for_each(|l| *l = false);
623+ neighbours.start_row();
508624 for sb_c in 0..sb_cols {
509- let (r0, c0) = (sb_r as usize * 2, sb_c as usize * 2);
510- let ctx = 2 * usize::from(left_split[r0]) + usize::from(above_split[c0]);
625+ let at = (sb_r as usize * 4, sb_c as usize * 4);
626+ let ctx = neighbours.partition_ctx(at, SB);
511627 // A superblock whose bottom or right half is outside the frame
512628 // cannot be left unsplit, so the decoder reads a flag instead of
513629 // the partition symbol — and reads nothing at all when both halves
@@ -518,7 +634,7 @@ pub fn sb_coeff_key_frame_tile(
518634 );
519635 // The quadrants of this superblock that are inside the frame, as
520636 // positions in the 32x32 block grid.
521- let quadrants: Vec<(usize, usize)> = (0..4)
637+ let quadrant_positions: Vec<(usize, usize)> = (0..4)
522638 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
523639 .filter(|&(r, c)| r < rows && c < cols)
524640 .map(|(r, c)| (r as usize, c as usize))
@@ -533,45 +649,27 @@ pub fn sb_coeff_key_frame_tile(
533649 ));
534650 }
535651 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
536- let mode = write_intra_mode(
537- &mut enc,
538- &mut cdfs,
539- block,
540- above_mode[c0],
541- left_mode[r0],
542- // A 64x64 block is too big to be offered chroma from
543- // luma, so its chroma mode reads the table without it.
544- false,
545- );
546652 let grids = [
547653 level_grid(&block.luma, TX32)?,
548654 level_grid(&block.u, TX32)?,
549655 level_grid(&block.v, TX32)?,
550656 ];
551- write_block_planes(
657+ write_block(
552658 &mut enc,
553659 &mut cdfs,
660+ &mut neighbours,
661+ block,
662+ at,
663+ SB,
554664 &whole_planes,
555665 &grids,
556- &[&scans[0], &scans[0], &scans[0]],
557- &above[c0],
558- &left[r0],
666+ [&scans[0], &scans[0], &scans[0]],
667+ // A 64x64 block is too big to be offered chroma from
668+ // luma, so its chroma mode reads the table without it.
669+ false,
559670 );
560- // The block covers two columns and two rows of the 32x32
561- // grid, so both of each read it as their neighbour.
562- for (r, c) in quadrants {
563- for plane in 0..3 {
564- let state = neighbour_state(&grids[plane]);
565- above[c][plane] = state;
566- left[r][plane] = state;
567- }
568- above_mode[c] = mode;
569- left_mode[r] = mode;
570- above_split[c] = false;
571- left_split[r] = false;
572- }
573671 }
574- Superblock::Split(blocks) => {
672+ Superblock::Split(quadrants) => {
575673 match (has_cols, has_rows) {
576674 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
577675 // The gathered CDF an edge superblock reads is built
@@ -585,45 +683,68 @@ pub fn sb_coeff_key_frame_tile(
585683 }
586684 (false, false) => {}
587685 }
588- if blocks.len() != quadrants.len() {
686+ if quadrants.len() != quadrant_positions.len() {
589687 return Err(Error::unsupported(
590688 "AV1 tile",
591689 "a split superblock needs one block per quadrant inside the frame",
592690 ));
593691 }
594- for (block, (r, c)) in blocks.iter().zip(quadrants) {
595- enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
596- let mode = write_intra_mode(
597- &mut enc,
598- &mut cdfs,
599- block,
600- above_mode[c],
601- left_mode[r],
602- true,
603- );
604- let grids = [
605- level_grid(&block.luma, TX32)?,
606- level_grid(&block.u, TX16)?,
607- level_grid(&block.v, TX16)?,
608- ];
609- write_block_planes(
610- &mut enc,
611- &mut cdfs,
612- &split_planes,
613- &grids,
614- &[&scans[0], &scans[1], &scans[1]],
615- &above[c],
616- &left[r],
617- );
618- for plane in 0..3 {
619- let state = neighbour_state(&grids[plane]);
620- above[c][plane] = state;
621- left[r][plane] = state;
692+ for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
693+ let at = (r * 2, c * 2);
694+ let ctx = neighbours.partition_ctx(at, BLOCK);
695+ match quadrant {
696+ Quadrant::Whole(block) => {
697+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx]);
698+ let grids = [
699+ level_grid(&block.luma, TX32)?,
700+ level_grid(&block.u, TX16)?,
701+ level_grid(&block.v, TX16)?,
702+ ];
703+ write_block(
704+ &mut enc,
705+ &mut cdfs,
706+ &mut neighbours,
707+ block,
708+ at,
709+ BLOCK,
710+ &split_planes,
711+ &grids,
712+ [&scans[0], &scans[1], &scans[1]],
713+ true,
714+ );
715+ }
716+ Quadrant::Split(blocks) => {
717+ enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w32[ctx]);
718+ if blocks.len() != 4 {
719+ return Err(Error::unsupported(
720+ "AV1 tile",
721+ "a 32x32 block that is split carries four 16x16 blocks",
722+ ));
723+ }
724+ for (i, block) in blocks.iter().enumerate() {
725+ let at = (at.0 + i / 2, at.1 + i % 2);
726+ let ctx = neighbours.partition_ctx(at, SUB);
727+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx]);
728+ let grids = [
729+ level_grid(&block.luma, TX16)?,
730+ level_grid(&block.u, TX8)?,
731+ level_grid(&block.v, TX8)?,
732+ ];
733+ write_block(
734+ &mut enc,
735+ &mut cdfs,
736+ &mut neighbours,
737+ block,
738+ at,
739+ SUB,
740+ &sub_planes,
741+ &grids,
742+ [&scans[1], &scans[2], &scans[2]],
743+ true,
744+ );
745+ }
746+ }
622747 }
623- above_mode[c] = mode;
624- left_mode[r] = mode;
625- above_split[c] = true;
626- left_split[r] = true;
627748 }
628749 }
629750 }
@@ -663,18 +784,56 @@ fn write_intra_mode(
663784 mode
664785 }
665786
787+/// Writes one coded block: its mode, its three transform blocks, and what it
788+/// leaves behind for the blocks beside it. Its partition symbol is already
789+/// written, because only the caller knows what tree led here.
790+#[allow(clippy::too_many_arguments)]
791+fn write_block(
792+ enc: &mut SymbolEncoder,
793+ cdfs: &mut Cdfs,
794+ neighbours: &mut Neighbours,
795+ block: &BlockCoeffs,
796+ at: (usize, usize),
797+ side: usize,
798+ planes: &[TxbSet; 3],
799+ grids: &[Vec<i32>; 3],
800+ scans: [&Vec<u16>; 3],
801+ cfl: bool,
802+) {
803+ let (r, c) = at;
804+ let mode = write_intra_mode(
805+ enc,
806+ cdfs,
807+ block,
808+ neighbours.above_mode[c],
809+ neighbours.left_mode[r],
810+ cfl,
811+ );
812+ write_block_planes(
813+ enc,
814+ cdfs,
815+ planes,
816+ grids,
817+ &scans,
818+ &neighbours.around(at, side),
819+ mode,
820+ );
821+ neighbours.record(at, side, mode, grids);
822+}
823+
666824 /// Writes the three transform blocks of one coded block, in the order a
667825 /// decoder reads them.
826+#[allow(clippy::too_many_arguments)]
668827 fn write_block_planes(
669828 enc: &mut SymbolEncoder,
670829 cdfs: &mut Cdfs,
671830 planes: &[TxbSet; 3],
672831 grids: &[Vec<i32>; 3],
673832 scans: &[&Vec<u16>; 3],
674- above: &[Neighbour; 3],
675- left: &[Neighbour; 3],
833+ around: &[Around; 3],
834+ mode: usize,
676835 ) {
677- for (plane, grid) in grids.iter().enumerate() {
836+ for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
678837 // Luma's transform covers its whole block, which fixes the all-zero
679838 // flag's context at zero; a chroma transform reads whether its
680839 // neighbours coded anything, on top of the offset the chroma tables
@@ -682,15 +841,15 @@ fn write_block_planes(
682841 let skip_ctx = if plane == 0 {
683842 0
684843 } else {
685- usize::from(above[plane].coded) + usize::from(left[plane].coded)
844+ usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded)
686845 };
687846 write_coeffs(
688847 enc,
689- &mut cdfs.txb(planes[plane]),
848+ &mut cdfs.txb(planes[plane], mode),
690849 grid,
691- scans[plane],
850+ scan,
692851 skip_ctx,
693- dc_sign_ctx(above[plane].dc, left[plane].dc),
852+ dc_sign_ctx(around[plane].dc_vote),
694853 );
695854 }
696855 }
@@ -734,7 +893,7 @@ pub fn split_coeff_key_frame_tile(
734893 (0..4)
735894 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
736895 .filter(|&(r, c)| r < rows && c < cols)
737- .map(|(r, c)| blocks[(r * cols + c) as usize].clone())
896+ .map(|(r, c)| Quadrant::Whole(blocks[(r * cols + c) as usize].clone()))
738897 .collect(),
739898 )
740899 })
@@ -808,31 +967,62 @@ fn default_scan(side: usize) -> Vec<u16> {
808967 /// so one table is all the search needs; a second block size would need its
809968 /// own entry point rather than a size argument, because the table and the scan
810969 /// have to agree.
970+#[cfg(test)]
811971 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
812- /// Built once: the search prices thirteen modes for every block, and the
813- /// scan is the same table every time.
814- static SCAN: LazyLock<Vec<u16>> = LazyLock::new(|| default_scan(TX32));
972+ coeff_bits(grid, TxbSet::Luma32)
973+}
974+
975+/// What one transform block's levels cost through the CDFs of `set`, in bits.
976+///
977+/// The search runs before the tile is written, so the adapted state the block
978+/// will really be coded against does not exist yet: the price is taken against
979+/// the defaults every tile starts from, and against the contexts a block whose
980+/// neighbours coded nothing reads.
981+pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 {
982+ /// Built once per size: the search prices thirteen modes for every block,
983+ /// and the scan is the same table every time.
984+ static SCANS: LazyLock<[Vec<u16>; 3]> =
985+ LazyLock::new(|| [default_scan(TX8), default_scan(TX16), default_scan(TX32)]);
986+ let mut cdfs = Cdfs::new();
987+ let mut coding = cdfs.txb(set, DC_PRED);
988+ let scan = match coding.side {
989+ TX8 => &SCANS[0],
990+ TX16 => &SCANS[1],
991+ _ => &SCANS[2],
992+ };
815993 let mut enc = SymbolEncoder::new();
816994 enc.reset_bits();
817- // The search runs before the tile is written, so the adapted state the
818- // block will really be coded against does not exist yet: the price is
819- // taken against the defaults every tile starts from.
820- write_coeffs(
821- &mut enc,
822- &mut Cdfs::new().txb(TxbSet::Luma32),
823- grid,
824- &SCAN,
825- 0,
826- 0,
827- );
995+ write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0);
828996 enc.bits()
829997 }
830998
999+/// What the partition symbol of a block of `side` samples costs, in bits, when
1000+/// it says the block is split (or that it is not).
1001+///
1002+/// The price is taken at context zero — a block whose neighbours are no finer
1003+/// than it is — because the search that reads it runs before the tile knows
1004+/// what its neighbours will be.
1005+pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
1006+ let cdfs = Cdfs::new();
1007+ let cdf: &[u16] = match side {
1008+ SB => &cdfs.partition_w64[0],
1009+ BLOCK => &cdfs.partition_w32[0],
1010+ _ => &cdfs.partition_w16[0],
1011+ };
1012+ let symbol = if split {
1013+ PARTITION_SPLIT
1014+ } else {
1015+ PARTITION_NONE
1016+ };
1017+ crate::encode::symbol_bits(cdf, symbol)
1018+}
1019+
8311020 /// coeffs() for one plane's transform block of any coefficients the base and
8321021 /// base-range syntax reach (spec 5.11.39).
8331022 ///
834-/// A 32x32 or 16x16 transform is DCT-only here, so no transform type is coded;
835-/// and the levels the contexts below are read from are the levels of
1023+/// A 16x16 luma transform codes which transform type it is, because its set
1024+/// holds more than one; 32x32 and 64x64 are DCT-only by spec 5.11.40. The
1025+/// levels the contexts below are read from are the levels of
8361026 /// coefficients later in the scan, which a decoder walking the scan backwards
8371027 /// already has.
8381028 fn write_coeffs(
@@ -852,6 +1042,12 @@ fn write_coeffs(
8521042 if eob == 0 {
8531043 return;
8541044 }
1045+ // A luma transform whose type set holds more than one type codes which it
1046+ // is, right after the all-zero flag (spec 5.11.39). The writer only ever
1047+ // uses DCT_DCT, which is index one of `Tx_Type_Intra_Inv_Set2`.
1048+ if let Some(tx_type) = coding.tx_type.as_deref_mut() {
1049+ enc.symbol(TX_TYPE_DCT_DCT_SET2, tx_type);
1050+ }
8551051
8561052 write_eob(enc, coding, eob);
8571053
@@ -1066,19 +1262,21 @@ fn write_dc_coeffs(
10661262 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
10671263 }
10681264
1069-/// `Dc_Sign_Contexts` (spec 8.3.2): every 4x4 unit above and left of the block
1070-/// votes the sign of the DC its own block carries — plus one for a positive
1071-/// one, minus one for a negative one, nothing for a unit with no coded
1072-/// coefficient — and the sum picks one of three contexts. Every block here is a
1073-/// whole superblock carrying one DC, so all sixteen units of a neighbour vote
1074-/// together and the sum can only lean up, lean down, or cancel.
1075-fn dc_sign_ctx(above: Option<bool>, left: Option<bool>) -> usize {
1076- let vote = |n: Option<bool>| match n {
1077- None => 0i32,
1265+/// One neighbour cell's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for
1266+/// a positive DC, minus one for a negative one, nothing for a cell whose block
1267+/// carried no DC. Every 4x4 unit of a cell votes the same way, so counting
1268+/// cells and counting units differ only by a factor the sign is blind to.
1269+fn dc_vote(dc: Option<bool>) -> i32 {
1270+ match dc {
1271+ None => 0,
10781272 Some(true) => -1,
10791273 Some(false) => 1,
1080- };
1081- match (vote(above) + vote(left)).signum() {
1274+ }
1275+}
1276+
1277+/// Which of the three DC sign contexts a gathered vote picks.
1278+fn dc_sign_ctx(vote: i32) -> usize {
1279+ match vote.signum() {
10821280 0 => 0,
10831281 -1 => 1,
10841282 _ => 2,
@@ -1795,7 +1993,7 @@ mod tests {
17951993 for grid in &grids {
17961994 write_coeffs(
17971995 &mut enc,
1798- &mut Cdfs::new().txb(TxbSet::Luma32),
1996+ &mut Cdfs::new().txb(TxbSet::Luma32, 0),
17991997 grid,
18001998 &scan,
18011999 0,
@@ -2090,6 +2288,41 @@ mod tests {
20902288
20912289 /// Encodes a key frame of the given size, whose 32x32 blocks carry
20922290 /// `blocks` in raster order, and hands back its luma plane as rows of
2291+ /// The neighbour context a block reads is gathered across every cell it
2292+ /// spans, not taken from the first one: a 32x32 block whose left-hand
2293+ /// neighbour cells disagree still sees the coded one. Reading a single
2294+ /// cell agreed with the decoder only while every block was the same size,
2295+ /// and desynchronised the arithmetic decoder the moment a 16x16 one
2296+ /// appeared beside a 32x32 one.
2297+ #[test]
2298+ fn a_block_gathers_the_cells_its_neighbours_cover() {
2299+ let mut neighbours = Neighbours::new(4, 4);
2300+ let quiet = [
2301+ vec![0i32; TX16 * TX16],
2302+ vec![0; TX8 * TX8],
2303+ vec![0; TX8 * TX8],
2304+ ];
2305+ let mut loud = quiet.clone();
2306+ loud[1][0] = -3;
2307+ // Two 16x16 blocks above the right-hand 32x32 block of the row, of
2308+ // which only the second codes anything.
2309+ neighbours.record((0, 2), SUB, DC_PRED, &quiet);
2310+ neighbours.record((0, 3), SUB, DC_PRED, &loud);
2311+ let around = neighbours.around((2, 2), BLOCK);
2312+ assert!(
2313+ around[1].above_coded,
2314+ "the coded cell has to reach the block below it"
2315+ );
2316+ assert_eq!(
2317+ dc_sign_ctx(around[1].dc_vote),
2318+ 1,
2319+ "the one negative DC above the block is what it votes"
2320+ );
2321+ // The same read one cell at a time misses it, which is the bug this
2322+ // gate is here for.
2323+ assert!(!neighbours.above[2][1].coded);
2324+ }
2325+
20932326 /// samples.
20942327 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
20952328 let (seq, header) = frame_of(width as u32, height as u32);
@@ -2294,7 +2527,12 @@ mod tests {
22942527 }]);
22952528 let sbs = [
22962529 Superblock::Whole(across),
2297- Superblock::Split(vec![down.clone(), down.clone(), down.clone(), down]),
2530+ Superblock::Split(vec![
2531+ Quadrant::Whole(down.clone()),
2532+ Quadrant::Whole(down.clone()),
2533+ Quadrant::Whole(down.clone()),
2534+ Quadrant::Whole(down),
2535+ ]),
22982536 ];
22992537 let rows = decode_luma_sb(128, 64, &sbs);
23002538
@@ -2325,6 +2563,71 @@ mod tests {
23252563 }
23262564 }
23272565
2566+ /// A quadrant may be split again into four 16x16 blocks, each carrying its
2567+ /// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
2568+ /// makes each of the four a flat grey of its own, so the quadrant reads as
2569+ /// four squares rather than one — which is what tells the extra split from
2570+ /// a 32x32 block that merely carries the same coefficients.
2571+ #[test]
2572+ fn a_quadrant_splits_into_four_sixteens() {
2573+ if !have_ffmpeg() {
2574+ eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
2575+ return;
2576+ }
2577+ let dc = |level: i32| {
2578+ BlockCoeffs::from(vec![Coeff {
2579+ row: 0,
2580+ col: 0,
2581+ level,
2582+ }])
2583+ };
2584+ let levels = [14, 8, -8, -14];
2585+ let flat = BlockCoeffs::from(Vec::new());
2586+ let sbs = [Superblock::Split(vec![
2587+ Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
2588+ Quadrant::Whole(flat.clone()),
2589+ Quadrant::Whole(flat.clone()),
2590+ Quadrant::Whole(flat),
2591+ ])];
2592+ let rows = decode_luma_sb(64, 64, &sbs);
2593+
2594+ let mut greys = Vec::new();
2595+ for i in 0..levels.len() {
2596+ let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
2597+ let grey = rows[y0][x0];
2598+ for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
2599+ for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
2600+ assert_eq!(
2601+ sample, grey,
2602+ "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
2603+ );
2604+ }
2605+ }
2606+ greys.push(grey);
2607+ }
2608+
2609+ // Each block is predicted DC from the blocks the decoder has already
2610+ // rebuilt, so what its own level does is move it off that prediction,
2611+ // in the level's own direction.
2612+ let g = |i: usize| i32::from(greys[i]);
2613+ let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
2614+ for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
2615+ assert_eq!(
2616+ (g(i) - prediction).signum(),
2617+ level.signum(),
2618+ "the 16x16 block {i} carries level {level}, so it sits on the \
2619+ {} side of the {prediction} its neighbours predict, not at {}",
2620+ if level > 0 { "bright" } else { "dark" },
2621+ g(i)
2622+ );
2623+ }
2624+ assert_eq!(
2625+ greys.iter().collect::<std::collections::HashSet<_>>().len(),
2626+ 4,
2627+ "the four blocks are four different greys, not one: {greys:?}"
2628+ );
2629+ }
2630+
23282631 /// A superblock half outside the frame has no partition that keeps a block
23292632 /// outside it, so it cannot be left whole.
23302633 #[test]
@@ -2336,10 +2639,10 @@ mod tests {
23362639 }]);
23372640 let sbs = [
23382641 Superblock::Split(vec![
2339- block.clone(),
2340- block.clone(),
2341- block.clone(),
2342- block.clone(),
2642+ Quadrant::Whole(block.clone()),
2643+ Quadrant::Whole(block.clone()),
2644+ Quadrant::Whole(block.clone()),
2645+ Quadrant::Whole(block.clone()),
23432646 ]),
23442647 Superblock::Whole(block.clone()),
23452648 ];
@@ -2781,6 +3084,74 @@ mod tests {
27813084 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
27823085 }
27833086
3087+ /// The same against the smallest transform the writer codes, the 16x16 one
3088+ /// a split quadrant carries. Its rounding is the one the split path rests
3089+ /// on, and nothing else in the crate exercises it against a decoder.
3090+ #[test]
3091+ fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
3092+ if !have_ffmpeg() {
3093+ eprintln!(
3094+ "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
3095+ );
3096+ return;
3097+ }
3098+ let coeffs = [
3099+ (0u8, 0u8, 9i32),
3100+ (0, 1, -14),
3101+ (1, 0, 7),
3102+ (0, 3, 5),
3103+ (3, 0, -3),
3104+ (2, 2, 11),
3105+ (7, 5, -6),
3106+ (15, 15, 4),
3107+ ];
3108+ let block: BlockCoeffs = coeffs
3109+ .iter()
3110+ .map(|&(row, col, level)| Coeff { row, col, level })
3111+ .collect::<Vec<_>>()
3112+ .into();
3113+ let (seq, header) = frame_of(64, 64);
3114+ let quadrants = vec![
3115+ Quadrant::Split(vec![
3116+ block,
3117+ BlockCoeffs::default(),
3118+ BlockCoeffs::default(),
3119+ BlockCoeffs::default(),
3120+ ]),
3121+ Quadrant::Whole(BlockCoeffs::default()),
3122+ Quadrant::Whole(BlockCoeffs::default()),
3123+ Quadrant::Whole(BlockCoeffs::default()),
3124+ ];
3125+ let tile = sb_coeff_key_frame_tile(
3126+ header.mi_cols,
3127+ header.mi_rows,
3128+ Q_IDX,
3129+ &[Superblock::Split(quadrants)],
3130+ )
3131+ .unwrap();
3132+ let mut stream = temporal_delimiter();
3133+ stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
3134+ stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
3135+ let planes = ffmpeg_decode(&stream, 64, 64);
3136+
3137+ let mut levels = vec![0i32; TX16 * TX16];
3138+ for &(row, col, level) in &coeffs {
3139+ levels[usize::from(row) * TX16 + usize::from(col)] = level;
3140+ }
3141+ let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
3142+ for row in 0..TX16 {
3143+ for col in 0..TX16 {
3144+ let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
3145+ assert_eq!(
3146+ i32::from(planes[row * 64 + col]),
3147+ want,
3148+ "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
3149+ planes[row * 64 + col]
3150+ );
3151+ }
3152+ }
3153+ }
3154+
27843155 /// The same against the other transform size, the 64x64 one a whole
27853156 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
27863157 /// the spec zeroes the rest before the row transform — a 64-point network
lanes/av1-sub32-r1.report.mdadded+75 -0
@@ -0,0 +1,75 @@
1+# lane-av1-sub32 r1 — 32x32 quadrants may split into four 16x16 blocks
2+
3+## What landed
4+
5+`encode_key_frame` now trials each 32x32 quadrant twice and keeps the cheaper
6+coding:
7+
8+- `cost_whole = luma_cost + sum_chroma(sse + lambda * bits) + lambda * partition_bits(BLOCK, false)`
9+- `cost_split = sum_i(sub costs) + lambda * (partition_bits(BLOCK, true) + 4 * partition_bits(SUB, false))`
10+
11+The reconstruction is snapshotted before the whole trial, restored before the
12+split trial, and the winner's reconstruction is put back, so prediction below and
13+to the right reads exactly what the decoder will. Mode bookkeeping moved to the
14+16x16 grid (`above_mode[cols * 2]`, `left_mode[rows * 2]`), which is the
15+granularity the spec's mode context reads at.
16+
17+The ablation is a parameter, not an env knob: `encode_key_frame_inner(..., split_blocks: bool)`,
18+with `SPLIT_BLOCKS` as the shipped default and `probe_split` calling both ways.
19+
20+## Measurement — `probe_split`, three-point ladder (q 110/90/70), BD-rate split vs whole
21+
22+| picture | BD-rate | coded blocks / quadrants @ q90 |
23+| --- | --- | --- |
24+| test card (synthetic) | -0.72% | 15 / 15 |
25+| stripes (synthetic) | +0.00% | 15 / 15 |
26+| diagonal (synthetic) | -22.45% | 33 / 15 |
27+| ReelC 1080p film @20:00 | **-9.15%** | 415 / 220 |
28+| OBS screen capture @10:00 | **-27.20%** | 604 / 220 |
29+| reela.mp4 @5s | **-9.05%** | 316 / 220 |
30+
31+Negative is better. `stripes` never splits (every quadrant is one texture), which
32+is the shape a correct RD decision should have. Default set to `SPLIT_BLOCKS = true`.
33+
34+## Defect found, fixed and gated — class: context read from one cell
35+
36+Turning splits on broke `ffmpeg_decodes_exactly_what_the_encoder_reconstructed` at
37+96x64: 979/6144 samples off by ~1, starting at the first split quadrant. Bisected
38+by forcing DC on sub-blocks (drift stayed, so not the mode context) and by adding a
39+permanent 16x16 inverse-transform-vs-ffmpeg gate (passed, so not the transform or
40+dequant).
41+
42+Cause: `write_block` read the chroma `txb_skip` context and the DC-sign context
43+from a single neighbour cell. The decoder gathers over every 4x4 unit the block
44+spans (`get_txb_skip_ctx`, spec 5.11.39; `Dc_Sign_Contexts`, spec 8.3.2). While
45+every block is 32x32 the one cell *is* the span, so the bug is invisible; the
46+moment a 16x16 sits beside a 32x32 the arithmetic decoder desynchronises — as
47+sample drift, never a crash.
48+
49+Fix: `Neighbours::around((r, c), side) -> [Around; 3]`, OR-ing `coded` and summing
50+the DC vote across `side / SUB` cells on both edges.
51+
52+Sibling single-cell reads swept, each correct by spec and left alone:
53+`above_mode`/`left_mode` (the spec reads exactly the mi above/left of the top-left),
54+`partition_ctx` (one neighbour's size), luma `txb_skip` ctx = 0 (the transform
55+covers the whole block at every size the writer codes).
56+
57+## Gates added
58+
59+- `the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block` — a split
60+ quadrant carrying eight coefficients including `(15, 15, 4)`, every sample
61+ compared to `dequant_and_inverse(&levels, TX16, 8, Q_IDX)`.
62+- `a_block_gathers_the_cells_its_neighbours_cover` — two 16x16 neighbours with
63+ different chroma state; asserts the gathered read sees both and that the
64+ single-cell read misses it.
65+
66+## State
67+
68+`cargo clippy --release -p ec-av1 --all-targets` zero warnings; suite 85 passed,
69+0 failed, 4 ignored.
70+
71+## Next in this layer
72+
73+Transform types beyond DCT_DCT and tx-size selection; splits below 16x16; pictures
74+that are not a multiple of 32; interleaving the search with the writer so rates
75+price against adapted tables.