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] =
722 pub const EOB_PT_1024_CHROMA: [u16; 12] = [722 pub const EOB_PT_1024_CHROMA: [u16; 12] = [
723 9577, 12466, 17739, 20750, 22061, 23215, 24601, 25483, 25843, 32056, 32768, 0,723 9577, 12466, 17739, 20750, 22061, 23215, 24601, 25483, 25843, 32056, 32768, 0,
724 ];724 ];
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 {
20 Luma32,20 Luma32,
21 /// The 64x64 luma transform of a whole superblock, scanned as a 32x32.21 /// The 64x64 luma transform of a whole superblock, scanned as a 32x32.
22 Luma64,22 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,
23 /// The 16x16 transform of a chroma plane of a 32x32 block.27 /// The 16x16 transform of a chroma plane of a 32x32 block.
24 Chroma16,28 Chroma16,
25 /// The 32x32 transform of a chroma plane of a whole superblock.29 /// The 32x32 transform of a chroma plane of a whole superblock.
@@ -45,6 +49,8 @@ pub(crate) struct TxbTables<'a> {
45 pub br: &'a mut [[u16; 5]; 21],49 pub br: &'a mut [[u16; 5]; 21],
46 /// The sign of the DC.50 /// The sign of the DC.
47 pub dc_sign: &'a mut [[u16; 3]; 3],51 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]>,
48 }54 }
49 55
50 /// Every table a key frame's tile writer adapts.56 /// Every table a key frame's tile writer adapts.
@@ -63,6 +69,32 @@ pub(crate) struct Cdfs {
63 pub uv_mode_cfl: [[u16; 15]; 13],69 pub uv_mode_cfl: [[u16; 15]; 13],
64 /// The angle a directional mode is nudged by.70 /// The angle a directional mode is nudged by.
65 pub angle_delta: [[u16; 8]; 8],71 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],
66 /// The one-context all-zero flag of a 32x32 luma transform.98 /// The one-context all-zero flag of a 32x32 luma transform.
67 pub txb_skip_luma_32: [[u16; 3]; 1],99 pub txb_skip_luma_32: [[u16; 3]; 1],
68 /// The same, for a 64x64 luma transform.100 /// The same, for a 64x64 luma transform.
@@ -110,6 +142,8 @@ pub(crate) struct Cdfs {
110 pub br_chroma_32: [[u16; 5]; 21],142 pub br_chroma_32: [[u16; 5]; 21],
111 /// The DC sign of a luma coefficient, shared by both luma sets.143 /// The DC sign of a luma coefficient, shared by both luma sets.
112 pub dc_sign_luma: [[u16; 3]; 3],144 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],
113 /// The DC sign of a chroma coefficient, shared by both chroma sets.147 /// The DC sign of a chroma coefficient, shared by both chroma sets.
114 pub dc_sign_chroma: [[u16; 3]; 3],148 pub dc_sign_chroma: [[u16; 3]; 3],
115 }149 }
@@ -127,6 +161,19 @@ impl Cdfs {
127 uv_mode_no_cfl: cdf::UV_MODE_NO_CFL,161 uv_mode_no_cfl: cdf::UV_MODE_NO_CFL,
128 uv_mode_cfl: cdf::UV_MODE_CFL,162 uv_mode_cfl: cdf::UV_MODE_CFL,
129 angle_delta: cdf::ANGLE_DELTA,163 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,
130 txb_skip_luma_32: [cdf::TXB_SKIP_LUMA_32],177 txb_skip_luma_32: [cdf::TXB_SKIP_LUMA_32],
131 txb_skip_luma_64: [cdf::TXB_SKIP_LUMA_64],178 txb_skip_luma_64: [cdf::TXB_SKIP_LUMA_64],
132 txb_skip_chroma_16: cdf::TXB_SKIP_CHROMA_16,179 txb_skip_chroma_16: cdf::TXB_SKIP_CHROMA_16,
@@ -150,12 +197,13 @@ impl Cdfs {
150 br_chroma_16: cdf::COEFF_BR_CHROMA_16,197 br_chroma_16: cdf::COEFF_BR_CHROMA_16,
151 br_chroma_32: cdf::COEFF_BR_CHROMA_32,198 br_chroma_32: cdf::COEFF_BR_CHROMA_32,
152 dc_sign_luma: cdf::DC_SIGN_LUMA,199 dc_sign_luma: cdf::DC_SIGN_LUMA,
200+ intra_tx_type_16: cdf::INTRA_TX_TYPE_SET2_16,
153 dc_sign_chroma: cdf::DC_SIGN_CHROMA,201 dc_sign_chroma: cdf::DC_SIGN_CHROMA,
154 }202 }
155 }203 }
156 204
157 /// The tables one table set is coded with, borrowed out of the state.205 /// 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<'_> {
159 match set {207 match set {
160 TxbSet::Luma32 => TxbTables {208 TxbSet::Luma32 => TxbTables {
161 side: 32,209 side: 32,
@@ -166,6 +214,7 @@ impl Cdfs {
166 base_eob: &mut self.base_eob_luma_32,214 base_eob: &mut self.base_eob_luma_32,
167 br: &mut self.br_luma_32,215 br: &mut self.br_luma_32,
168 dc_sign: &mut self.dc_sign_luma,216 dc_sign: &mut self.dc_sign_luma,
217+ tx_type: None,
169 },218 },
170 TxbSet::Luma64 => TxbTables {219 TxbSet::Luma64 => TxbTables {
171 side: 32,220 side: 32,
@@ -176,6 +225,29 @@ impl Cdfs {
176 base_eob: &mut self.base_eob_luma_64,225 base_eob: &mut self.base_eob_luma_64,
177 br: &mut self.br_luma_32,226 br: &mut self.br_luma_32,
178 dc_sign: &mut self.dc_sign_luma,227 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,
179 },251 },
180 TxbSet::Chroma16 => TxbTables {252 TxbSet::Chroma16 => TxbTables {
181 side: 16,253 side: 16,
@@ -186,6 +258,7 @@ impl Cdfs {
186 base_eob: &mut self.base_eob_chroma_16,258 base_eob: &mut self.base_eob_chroma_16,
187 br: &mut self.br_chroma_16,259 br: &mut self.br_chroma_16,
188 dc_sign: &mut self.dc_sign_chroma,260 dc_sign: &mut self.dc_sign_chroma,
261+ tx_type: None,
189 },262 },
190 TxbSet::Chroma32 => TxbTables {263 TxbSet::Chroma32 => TxbTables {
191 side: 32,264 side: 32,
@@ -196,6 +269,7 @@ impl Cdfs {
196 base_eob: &mut self.base_eob_chroma_32,269 base_eob: &mut self.base_eob_chroma_32,
197 br: &mut self.br_chroma_32,270 br: &mut self.br_chroma_32,
198 dc_sign: &mut self.dc_sign_chroma,271 dc_sign: &mut self.dc_sign_chroma,
272+ tx_type: None,
199 },273 },
200 }274 }
201 }275 }
@@ -212,8 +286,8 @@ mod tests {
212 #[test]286 #[test]
213 fn the_two_luma_sets_share_the_base_range_table() {287 fn the_two_luma_sets_share_the_base_range_table() {
214 let mut cdfs = Cdfs::new();288 let mut cdfs = Cdfs::new();
215- cdfs.txb(TxbSet::Luma64).br[0][0] = 1;289+ cdfs.txb(TxbSet::Luma64, 0).br[0][0] = 1;
216- assert_eq!(cdfs.txb(TxbSet::Luma32).br[0][0], 1);290+ assert_eq!(cdfs.txb(TxbSet::Luma32, 0).br[0][0], 1);
217 }291 }
218 292
219 /// Both luma sets read one DC sign table, and both chroma sets another;293 /// Both luma sets read one DC sign table, and both chroma sets another;
@@ -221,12 +295,12 @@ mod tests {
221 #[test]295 #[test]
222 fn the_sign_tables_are_shared_within_a_plane_type_and_not_across() {296 fn the_sign_tables_are_shared_within_a_plane_type_and_not_across() {
223 let mut cdfs = Cdfs::new();297 let mut cdfs = Cdfs::new();
224- cdfs.txb(TxbSet::Luma32).dc_sign[1][0] = 1;298+ cdfs.txb(TxbSet::Luma32, 0).dc_sign[1][0] = 1;
225- cdfs.txb(TxbSet::Chroma16).dc_sign[2][0] = 2;299+ cdfs.txb(TxbSet::Chroma16, 0).dc_sign[2][0] = 2;
226- assert_eq!(cdfs.txb(TxbSet::Luma64).dc_sign[1][0], 1);300+ assert_eq!(cdfs.txb(TxbSet::Luma64, 0).dc_sign[1][0], 1);
227- assert_eq!(cdfs.txb(TxbSet::Chroma32).dc_sign[2][0], 2);301+ assert_eq!(cdfs.txb(TxbSet::Chroma32, 0).dc_sign[2][0], 2);
228- assert_ne!(cdfs.txb(TxbSet::Chroma32).dc_sign[1][0], 1);302+ assert_ne!(cdfs.txb(TxbSet::Chroma32, 0).dc_sign[1][0], 1);
229- assert_ne!(cdfs.txb(TxbSet::Luma64).dc_sign[2][0], 2);303+ assert_ne!(cdfs.txb(TxbSet::Luma64, 0).dc_sign[2][0], 2);
230 }304 }
231 305
232 /// The end-of-block table a 1024-position transform reads is shared by both306 /// The end-of-block table a 1024-position transform reads is shared by both
@@ -235,9 +309,9 @@ mod tests {
235 #[test]309 #[test]
236 fn the_luma_end_of_block_table_is_shared_and_chromas_is_not() {310 fn the_luma_end_of_block_table_is_shared_and_chromas_is_not() {
237 let mut cdfs = Cdfs::new();311 let mut cdfs = Cdfs::new();
238- cdfs.txb(TxbSet::Luma32).eob_pt[0] = 7;312+ cdfs.txb(TxbSet::Luma32, 0).eob_pt[0] = 7;
239- assert_eq!(cdfs.txb(TxbSet::Luma64).eob_pt[0], 7);313+ assert_eq!(cdfs.txb(TxbSet::Luma64, 0).eob_pt[0], 7);
240- assert_ne!(cdfs.txb(TxbSet::Chroma32).eob_pt[0], 7);314+ assert_ne!(cdfs.txb(TxbSet::Chroma32, 0).eob_pt[0], 7);
241 }315 }
242 316
243 /// Every set starts from the spec's defaults, so a tile that adapts nothing317 /// Every set starts from the spec's defaults, so a tile that adapts nothing
@@ -245,9 +319,12 @@ mod tests {
245 #[test]319 #[test]
246 fn the_state_starts_at_the_defaults() {320 fn the_state_starts_at_the_defaults() {
247 let mut cdfs = Cdfs::new();321 let mut cdfs = Cdfs::new();
248- assert_eq!(cdfs.txb(TxbSet::Luma32).base[3], cdf::COEFF_BASE_LUMA_32[3]);
249 assert_eq!(322 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],
251 cdf::EOB_EXTRA_CHROMA_16[2]328 cdf::EOB_EXTRA_CHROMA_16[2]
252 );329 );
253 assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]);330 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::{
22 use ec_core::{Error, Result};22 use ec_core::{Error, Result};
23 23
24 use crate::cdf;24 use crate::cdf;
25+use crate::cdf_state::TxbSet;
25 use crate::frame::frame_obu;26 use crate::frame::frame_obu;
26 use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};27 use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};
27 use crate::obu::temporal_delimiter;28 use crate::obu::temporal_delimiter;
28 use crate::quant::ac_q;29 use crate::quant::ac_q;
29 use crate::sequence::sequence_header_obu;30 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+};
31 use crate::transform::{dequant_and_inverse, forward_and_quantize};35 use crate::transform::{dequant_and_inverse, forward_and_quantize};
32 36
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.
34 const BLOCK: usize = 32;39 const BLOCK: usize = 32;
35 40
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+
36 /// How heavily the mode search weighs rate against squared error, in units of47 /// How heavily the mode search weighs rate against squared error, in units of
37 /// the quantizer's reconstruction step squared per bit.48 /// the quantizer's reconstruction step squared per bit.
38 ///49 ///
@@ -57,6 +68,16 @@ fn lambda_scale() -> f64 {
57 }68 }
58 }69 }
59 70
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+
60 /// One 8-bit planar 4:2:0 picture.81 /// One 8-bit planar 4:2:0 picture.
61 #[derive(Clone, Debug, PartialEq, Eq)]82 #[derive(Clone, Debug, PartialEq, Eq)]
62 pub struct Picture {83 pub struct Picture {
@@ -117,7 +138,8 @@ pub struct Encoded {
117 /// reconstruction, which its prediction was built on.138 /// reconstruction, which its prediction was built on.
118 pub reconstruction: Picture,139 pub reconstruction: Picture,
119 /// The luma intra mode each block was coded under, in the order the blocks140 /// 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.
121 pub modes: Vec<u8>,143 pub modes: Vec<u8>,
122 }144 }
123 145
@@ -284,7 +306,9 @@ impl Plane<'_> {
284 /// levels, the block the decoder would reconstruct, the squared error306 /// levels, the block the decoder would reconstruct, the squared error
285 /// against the source and an estimate of what the levels cost in bits.307 /// against the source and an estimate of what the levels cost in bits.
286 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial {308 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;
288 let (above, left, corner) = self.edges(x, y, side, reach);312 let (above, left, corner) = self.edges(x, y, side, reach);
289 let mut prediction = vec![0u8; side * side];313 let mut prediction = vec![0u8; side * side];
290 crate::intra::predict(314 crate::intra::predict(
@@ -321,12 +345,9 @@ impl Plane<'_> {
321 }345 }
322 }346 }
323 // What the levels cost is priced through the same CDFs the tile writer347 // 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 they348+ // will code them with, so the search ranks modes -- and the partition
325- // actually spend. Chroma blocks are not searched, so only the 32x32349+ // trial ranks trees -- by the bits they actually spend.
326- // luma table is asked for.350+ let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
327- let bits = if side != BLOCK {
328- 0.0
329- } else if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
330 // What the search used before it could price a block exactly: a351 // What the search used before it could price a block exactly: a
331 // level costs its magnitude's width plus a sign and a run. Kept352 // level costs its magnitude's width plus a sign and a run. Kept
332 // reachable from the sweep so the two rate terms can be compared353 // reachable from the sweep so the two rate terms can be compared
@@ -337,7 +358,7 @@ impl Plane<'_> {
337 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())358 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
338 .sum()359 .sum()
339 } else {360 } else {
340- crate::tile::luma_32_coeff_bits(&levels)361+ crate::tile::coeff_bits(&levels, at.set)
341 };362 };
342 Trial {363 Trial {
343 levels,364 levels,
@@ -355,16 +376,44 @@ impl Plane<'_> {
355 }376 }
356 }377 }
357 378
358- /// Codes one block under a fixed mode, committing it.379+ /// Codes one block under a fixed mode, committing it, and hands back what
359- fn code_block(&mut self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Vec<Coeff> {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) {
360 let trial = self.trial(at, mode, base_q_idx, deadzone);388 let trial = self.trial(at, mode, base_q_idx, deadzone);
361 self.commit(at.x, at.y, at.side, &trial);389 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+ }
363 }407 }
364 408
365 /// Codes one block under every mode the search offers and commits the one409 /// Codes one block under every mode the search offers and commits the one
366 /// whose squared error and estimated rate come out cheapest.410 /// 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) {
368 let mut best: Option<(f64, u8, Trial)> = None;417 let mut best: Option<(f64, u8, Trial)> = None;
369 for &mode in search.modes {418 for &mode in search.modes {
370 let trial = self.trial(at, mode, search.base_q_idx, search.deadzone);419 let trial = self.trial(at, mode, search.base_q_idx, search.deadzone);
@@ -376,9 +425,9 @@ impl Plane<'_> {
376 best = Some((cost, mode, trial));425 best = Some((cost, mode, trial));
377 }426 }
378 }427 }
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");
380 self.commit(at.x, at.y, at.side, &trial);429 self.commit(at.x, at.y, at.side, &trial);
381- (coeffs(&trial.levels, at.side), mode)430+ (coeffs(&trial.levels, at.side), mode, cost)
382 }431 }
383 }432 }
384 433
@@ -390,34 +439,44 @@ struct At {
390 y: usize,439 y: usize,
391 side: usize,440 side: usize,
392 reach: Reach,441 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,
393 }445 }
394 446
395 /// Which of the samples past a block's own edges the decoder has decoded by447 /// Which of the samples past a block's own edges the decoder has decoded by
396 /// the time it predicts the block, and so which a directional mode may read.448 /// the time it predicts the block, and so which a directional mode may read.
397 ///449 ///
398 /// The decoder derives these from its `BlockDecoded` flags, which are cleared450 /// The decoder derives these from its `BlockDecoded` flags, which are cleared
399-/// per superblock (`clear_block_decoded_flags`, spec 7.4): the row above the451+/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
400-/// superblock counts as decoded out to the end of the *tile*, while the column452+/// that map, this reads the answer the same way libaom and rav1e do: for a
401-/// to its left counts only as far as the superblock's own height, and every453+/// block whose transform covers it whole, whether the samples above its right
402-/// position inside the superblock starts undecoded. For the four 32x32454+/// (or below its left) are decoded depends only on where the block sits inside
403-/// quadrants of a 64x64 superblock that comes to: the samples above-right are455+/// its 64x64 superblock, which is a pinned table per block size.
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.
408 #[derive(Clone, Copy)]456 #[derive(Clone, Copy)]
409 struct Reach {457 struct Reach {
410 above_right: bool,458 above_right: bool,
411 below_left: bool,459 below_left: bool,
412 }460 }
413 461
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+
414 impl Reach {473 impl Reach {
415- /// The reach of the quadrant coded `quadrant`-th in a superblock, counting474+ /// What a block of `side` samples at `(x, y)` may read past its own edges,
416- /// in raster order among the four.475+ /// in a frame of `width` by `height`.
417- fn quadrant(quadrant: usize) -> Self {476+ fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {
418 Self {477 Self {
419- above_right: quadrant != 3,478+ above_right: y > 0 && x + side < width && Self::top_right(side, x, y),
420- below_left: quadrant == 0,479+ below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),
421 }480 }
422 }481 }
423 482
@@ -429,10 +488,60 @@ impl Reach {
429 below_left: false,488 below_left: false,
430 }489 }
431 }490 }
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+ }
432 }541 }
433 542
434 /// What one symbol costs against a CDF, in bits.543 /// 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 {
436 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };545 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
437 let probability = f64::from(cdf[symbol] - low) / 32768.0;546 let probability = f64::from(cdf[symbol] - low) / 32768.0;
438 -probability.log2()547 -probability.log2()
@@ -447,6 +556,86 @@ fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
447 /// Without this the search is blind to what a mode costs to name, which is not556 /// Without this the search is blind to what a mode costs to name, which is not
448 /// a rounding error: a directional mode on a picture that does not run that way557 /// a rounding error: a directional mode on a picture that does not run that way
449 /// is a rate loss the squared error never sees.558 /// 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+
450 fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {639 fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
451 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]640 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
452 [INTRA_MODE_CTX[usize::from(left_mode)]];641 [INTRA_MODE_CTX[usize::from(left_mode)]];
@@ -521,6 +710,18 @@ pub fn encode_key_frame_with_modes(
521 base_q_idx: u8,710 base_q_idx: u8,
522 deadzone: f64,711 deadzone: f64,
523 modes: &[u8],712 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,
524 ) -> Result<Encoded> {725 ) -> Result<Encoded> {
525 picture.check()?;726 picture.check()?;
526 if modes.is_empty() {727 if modes.is_empty() {
@@ -573,8 +774,10 @@ pub fn encode_key_frame_with_modes(
573 // what picks the CDF the next block's mode is coded against -- the same774 // what picks the CDF the next block's mode is coded against -- the same
574 // bookkeeping the tile writer keeps, so that the search is costing the775 // bookkeeping the tile writer keeps, so that the search is costing the
575 // symbol the writer will actually write.776 // symbol the writer will actually write.
576- let mut above_mode = vec![DC_PRED; cols];777+ // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
577- let mut left_mode = vec![DC_PRED; rows];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];
578 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));781 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
579 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);782 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
580 let mut modes = Vec::with_capacity(cols * rows);783 let mut modes = Vec::with_capacity(cols * rows);
@@ -590,47 +793,58 @@ pub fn encode_key_frame_with_modes(
590 continue;793 continue;
591 }794 }
592 let (x, y) = (col * BLOCK, row * BLOCK);795 let (x, y) = (col * BLOCK, row * BLOCK);
593- let (luma_coeffs, mode) = luma.search_block(796+ let (c0, r0) = (col * 2, row * 2);
594- At {797+ let base = snapshot(&luma, &chroma, (x, y));
595- x,798+
596- y,799+ // What the whole 32x32 costs, including the partition symbol
597- side: BLOCK,800+ // that says it is not split.
598- reach: Reach::quadrant(quadrant),801+ let (whole, mut cost_whole) = code_square(
599- },802+ &mut luma,
803+ &mut chroma,
804+ (x, y),
805+ BLOCK,
600 &search,806 &search,
601- &mode_bits(above_mode[col], left_mode[row]),807+ &mode_bits(above_mode[c0], left_mode[r0]),
602 );808 );
603- above_mode[col] = mode;809+ cost_whole += search.lambda * partition_bits(BLOCK, false);
604- left_mode[row] = mode;810+ let after_whole = snapshot(&luma, &chroma, (x, y));
605- modes.push(mode);811+
606- blocks.push(BlockCoeffs {812+ // What four 16x16 blocks cost instead, each searched against
607- // Chroma is predicted DC because that is the mode the tile813+ // the reconstruction the ones before it left.
608- // writer codes for it.814+ restore(&mut luma, &mut chroma, (x, y), &base);
609- u: chroma[0].code_block(815+ let mut split = Vec::with_capacity(4);
610- At {816+ let mut cost_split = search.lambda
611- x: x / 2,817+ * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
612- y: y / 2,818+ let mut split_modes = [DC_PRED; 4];
613- side: BLOCK / 2,819+ for (sub, sub_mode) in split_modes.iter_mut().enumerate() {
614- reach: Reach::none(),820+ let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
615- },821+ let (block, cost) = code_square(
616- DC_PRED,822+ &mut luma,
617- base_q_idx,823+ &mut chroma,
618- deadzone,824+ (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
619- ),825+ SUB,
620- v: chroma[1].code_block(826+ &search,
621- At {827+ &mode_bits(above_mode[sc], left_mode[sr]),
622- x: x / 2,828+ );
623- y: y / 2,829+ cost_split += cost;
624- side: BLOCK / 2,830+ *sub_mode = block.mode;
625- reach: Reach::none(),831+ above_mode[sc] = block.mode;
626- },832+ left_mode[sr] = block.mode;
627- DC_PRED,833+ split.push(block);
628- base_q_idx,834+ }
629- deadzone,835+
630- ),836+ if split_blocks && cost_split < cost_whole {
631- luma: luma_coeffs,837+ modes.extend_from_slice(&split_modes);
632- mode,838+ blocks.push(Quadrant::Split(split));
633- });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+ }
634 }848 }
635 superblocks.push(Superblock::Split(blocks));849 superblocks.push(Superblock::Split(blocks));
636 }850 }
@@ -854,6 +1068,42 @@ mod tests {
854 }1068 }
855 }1069 }
856 1070
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+
857 /// A striped picture, running one way or the other. The stripes are what1107 /// A striped picture, running one way or the other. The stripes are what
858 /// separates a vertical predictor from a horizontal one: a mode search1108 /// separates a vertical predictor from a horizontal one: a mode search
859 /// reading a transposed edge would pick the wrong one of the pair, which no1109 /// reading a transposed edge would pick the wrong one of the pair, which no
crates/ec-av1/src/tile.rsmodified+500 -129
@@ -64,6 +64,9 @@ const SB_MI: u32 = 16;
64 64
65 /// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.65 /// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
66 const NUM_BASE_LEVELS: i32 = 2;66 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;
67 /// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the70 /// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
68 /// Golomb tail takes over.71 /// Golomb tail takes over.
69 const COEFF_BASE_RANGE: i32 = 12;72 const COEFF_BASE_RANGE: i32 = 12;
@@ -225,7 +228,7 @@ pub fn dc_key_frame_tile_levels(
225 write_dc_coeffs(228 write_dc_coeffs(
226 &mut enc,229 &mut enc,
227 dc_level,230 dc_level,
228- dc_sign_ctx(above[c as usize], left),231+ dc_sign_ctx(dc_vote(above[c as usize]) + dc_vote(left)),
229 &cdf::TXB_SKIP_LUMA_64,232 &cdf::TXB_SKIP_LUMA_64,
230 &cdf::COEFF_BASE_EOB_LUMA_64_DC,233 &cdf::COEFF_BASE_EOB_LUMA_64_DC,
231 );234 );
@@ -301,7 +304,7 @@ pub fn split_dc_key_frame_tile(
301 write_dc_coeffs(304 write_dc_coeffs(
302 &mut enc,305 &mut enc,
303 dc_level,306 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])),
305 &cdf::TXB_SKIP_LUMA_32,308 &cdf::TXB_SKIP_LUMA_32,
306 &cdf::COEFF_BASE_EOB_LUMA_32[0],309 &cdf::COEFF_BASE_EOB_LUMA_32[0],
307 );310 );
@@ -363,8 +366,19 @@ impl From<Vec<Coeff>> for BlockCoeffs {
363 366
364 /// Side of the luma transform the coefficient writer codes.367 /// Side of the luma transform the coefficient writer codes.
365 const TX32: usize = 32;368 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.
367 const TX16: usize = 16;373 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;
368 382
369 /// What one coded block leaves behind for the blocks that read it as a383 /// What one coded block leaves behind for the blocks that read it as a
370 /// neighbour: whether it coded anything at all, and the sign of its DC.384 /// neighbour: whether it coded anything at all, and the sign of its DC.
@@ -411,11 +425,124 @@ pub enum Superblock {
411 /// top-left 32x32 carries coefficients — and whose chroma transforms are425 /// top-left 32x32 carries coefficients — and whose chroma transforms are
412 /// 32x32 each at 4:2:0.426 /// 32x32 each at 4:2:0.
413 Whole(BlockCoeffs),427 Whole(BlockCoeffs),
414- /// The 32x32 blocks the superblock is split into, each with a 32x32 luma428+ /// The 32x32 quadrants the superblock is split into, each either one
415- /// transform and a 16x16 transform per chroma plane.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.
416 Split(Vec<BlockCoeffs>),441 Split(Vec<BlockCoeffs>),
417 }442 }
418 443
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+
419 /// Writes the payload of a one-tile key frame built from `superblocks`, each546 /// Writes the payload of a one-tile key frame built from `superblocks`, each
420 /// either one 64x64 block or the 32x32 blocks it splits into.547 /// either one 64x64 block or the 32x32 blocks it splits into.
421 ///548 ///
@@ -449,14 +576,19 @@ pub fn sb_coeff_key_frame_tile(
449 "a coefficient key frame needs one entry per superblock",576 "a coefficient key frame needs one entry per superblock",
450 ));577 ));
451 }578 }
452- let bad_mode = superblocks579+ let mut coded: Vec<&BlockCoeffs> = Vec::new();
453- .iter()580+ for superblock in superblocks {
454- .flat_map(|sb| match sb {581+ match superblock {
455- Superblock::Whole(b) => std::slice::from_ref(b),582+ Superblock::Whole(block) => coded.push(block),
456- Superblock::Split(b) => b.as_slice(),583+ Superblock::Split(quadrants) => {
457- })584+ coded.extend(quadrants.iter().flat_map(Quadrant::blocks));
458- .find(|b| usize::from(b.mode) >= INTRA_MODES);585+ }
459- if let Some(bad) = bad_mode {586+ }
587+ }
588+ if let Some(bad) = coded
589+ .into_iter()
590+ .find(|b| usize::from(b.mode) >= INTRA_MODES)
591+ {
460 return Err(Error::unsupported(592 return Err(Error::unsupported(
461 "AV1 tile",593 "AV1 tile",
462 format!(594 format!(
@@ -473,28 +605,14 @@ pub fn sb_coeff_key_frame_tile(
473 ));605 ));
474 }606 }
475 607
608+ let sub_planes = [TxbSet::Luma16, TxbSet::Chroma8, TxbSet::Chroma8];
476 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];609 let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
477 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];610 let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
478- let scans = [default_scan(TX32), default_scan(TX16)];611+ let scans = [default_scan(TX32), default_scan(TX16), default_scan(TX8)];
479- // What the blocks above and to the left of the one being coded left612+ // The blocks above and to the left, on the 16x16 grid. The left edge is
480- // behind, per plane, one entry per 32x32 column and row. The left column613+ // reset at every superblock row because a tile starts each row with no
481- // is reset at every superblock row because a tile starts each row with no
482 // left neighbour.614 // left neighbour.
483- let mut above = vec![[Neighbour::default(); 3]; cols as usize];615+ let mut neighbours = Neighbours::new(cols as usize * 2, rows as usize * 2);
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];
498 616
499 // The tile adapts every non-literal CDF it writes, exactly as the decoder617 // The tile adapts every non-literal CDF it writes, exactly as the decoder
500 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`618 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
@@ -502,12 +620,10 @@ pub fn sb_coeff_key_frame_tile(
502 let mut cdfs = Cdfs::new();620 let mut cdfs = Cdfs::new();
503 let mut enc = SymbolEncoder::new();621 let mut enc = SymbolEncoder::new();
504 for sb_r in 0..sb_rows {622 for sb_r in 0..sb_rows {
505- left.iter_mut().for_each(|l| *l = Default::default());623+ neighbours.start_row();
506- left_mode.iter_mut().for_each(|m| *m = DC_PRED);
507- left_split.iter_mut().for_each(|l| *l = false);
508 for sb_c in 0..sb_cols {624 for sb_c in 0..sb_cols {
509- let (r0, c0) = (sb_r as usize * 2, sb_c as usize * 2);625+ let at = (sb_r as usize * 4, sb_c as usize * 4);
510- let ctx = 2 * usize::from(left_split[r0]) + usize::from(above_split[c0]);626+ let ctx = neighbours.partition_ctx(at, SB);
511 // A superblock whose bottom or right half is outside the frame627 // A superblock whose bottom or right half is outside the frame
512 // cannot be left unsplit, so the decoder reads a flag instead of628 // cannot be left unsplit, so the decoder reads a flag instead of
513 // the partition symbol — and reads nothing at all when both halves629 // the partition symbol — and reads nothing at all when both halves
@@ -518,7 +634,7 @@ pub fn sb_coeff_key_frame_tile(
518 );634 );
519 // The quadrants of this superblock that are inside the frame, as635 // The quadrants of this superblock that are inside the frame, as
520 // positions in the 32x32 block grid.636 // positions in the 32x32 block grid.
521- let quadrants: Vec<(usize, usize)> = (0..4)637+ let quadrant_positions: Vec<(usize, usize)> = (0..4)
522 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))638 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
523 .filter(|&(r, c)| r < rows && c < cols)639 .filter(|&(r, c)| r < rows && c < cols)
524 .map(|(r, c)| (r as usize, c as usize))640 .map(|(r, c)| (r as usize, c as usize))
@@ -533,45 +649,27 @@ pub fn sb_coeff_key_frame_tile(
533 ));649 ));
534 }650 }
535 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);651 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- );
546 let grids = [652 let grids = [
547 level_grid(&block.luma, TX32)?,653 level_grid(&block.luma, TX32)?,
548 level_grid(&block.u, TX32)?,654 level_grid(&block.u, TX32)?,
549 level_grid(&block.v, TX32)?,655 level_grid(&block.v, TX32)?,
550 ];656 ];
551- write_block_planes(657+ write_block(
552 &mut enc,658 &mut enc,
553 &mut cdfs,659 &mut cdfs,
660+ &mut neighbours,
661+ block,
662+ at,
663+ SB,
554 &whole_planes,664 &whole_planes,
555 &grids,665 &grids,
556- &[&scans[0], &scans[0], &scans[0]],666+ [&scans[0], &scans[0], &scans[0]],
557- &above[c0],667+ // A 64x64 block is too big to be offered chroma from
558- &left[r0],668+ // luma, so its chroma mode reads the table without it.
669+ false,
559 );670 );
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 }671 }
568- above_mode[c] = mode;672+ Superblock::Split(quadrants) => {
569- left_mode[r] = mode;
570- above_split[c] = false;
571- left_split[r] = false;
572- }
573- }
574- Superblock::Split(blocks) => {
575 match (has_cols, has_rows) {673 match (has_cols, has_rows) {
576 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),674 (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
577 // The gathered CDF an edge superblock reads is built675 // The gathered CDF an edge superblock reads is built
@@ -585,45 +683,68 @@ pub fn sb_coeff_key_frame_tile(
585 }683 }
586 (false, false) => {}684 (false, false) => {}
587 }685 }
588- if blocks.len() != quadrants.len() {686+ if quadrants.len() != quadrant_positions.len() {
589 return Err(Error::unsupported(687 return Err(Error::unsupported(
590 "AV1 tile",688 "AV1 tile",
591 "a split superblock needs one block per quadrant inside the frame",689 "a split superblock needs one block per quadrant inside the frame",
592 ));690 ));
593 }691 }
594- for (block, (r, c)) in blocks.iter().zip(quadrants) {692+ for (quadrant, (r, c)) in quadrants.iter().zip(quadrant_positions) {
595- enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);693+ let at = (r * 2, c * 2);
596- let mode = write_intra_mode(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(
597 &mut enc,704 &mut enc,
598 &mut cdfs,705 &mut cdfs,
706+ &mut neighbours,
599 block,707 block,
600- above_mode[c],708+ at,
601- left_mode[r],709+ BLOCK,
710+ &split_planes,
711+ &grids,
712+ [&scans[0], &scans[1], &scans[1]],
602 true,713 true,
603 );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]);
604 let grids = [728 let grids = [
605- level_grid(&block.luma, TX32)?,729+ level_grid(&block.luma, TX16)?,
606- level_grid(&block.u, TX16)?,730+ level_grid(&block.u, TX8)?,
607- level_grid(&block.v, TX16)?,731+ level_grid(&block.v, TX8)?,
608 ];732 ];
609- write_block_planes(733+ write_block(
610 &mut enc,734 &mut enc,
611 &mut cdfs,735 &mut cdfs,
612- &split_planes,736+ &mut neighbours,
737+ block,
738+ at,
739+ SUB,
740+ &sub_planes,
613 &grids,741 &grids,
614- &[&scans[0], &scans[1], &scans[1]],742+ [&scans[1], &scans[2], &scans[2]],
615- &above[c],743+ true,
616- &left[r],
617 );744 );
618- for plane in 0..3 {
619- let state = neighbour_state(&grids[plane]);
620- above[c][plane] = state;
621- left[r][plane] = state;
622 }745 }
623- above_mode[c] = mode;746+ }
624- left_mode[r] = mode;747+ }
625- above_split[c] = true;
626- left_split[r] = true;
627 }748 }
628 }749 }
629 }750 }
@@ -663,18 +784,56 @@ fn write_intra_mode(
663 mode784 mode
664 }785 }
665 786
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+
666 /// Writes the three transform blocks of one coded block, in the order a824 /// Writes the three transform blocks of one coded block, in the order a
667 /// decoder reads them.825 /// decoder reads them.
826+#[allow(clippy::too_many_arguments)]
668 fn write_block_planes(827 fn write_block_planes(
669 enc: &mut SymbolEncoder,828 enc: &mut SymbolEncoder,
670 cdfs: &mut Cdfs,829 cdfs: &mut Cdfs,
671 planes: &[TxbSet; 3],830 planes: &[TxbSet; 3],
672 grids: &[Vec<i32>; 3],831 grids: &[Vec<i32>; 3],
673 scans: &[&Vec<u16>; 3],832 scans: &[&Vec<u16>; 3],
674- above: &[Neighbour; 3],833+ around: &[Around; 3],
675- left: &[Neighbour; 3],834+ mode: usize,
676 ) {835 ) {
677- for (plane, grid) in grids.iter().enumerate() {836+ for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
678 // Luma's transform covers its whole block, which fixes the all-zero837 // Luma's transform covers its whole block, which fixes the all-zero
679 // flag's context at zero; a chroma transform reads whether its838 // flag's context at zero; a chroma transform reads whether its
680 // neighbours coded anything, on top of the offset the chroma tables839 // neighbours coded anything, on top of the offset the chroma tables
@@ -682,15 +841,15 @@ fn write_block_planes(
682 let skip_ctx = if plane == 0 {841 let skip_ctx = if plane == 0 {
683 0842 0
684 } else {843 } 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)
686 };845 };
687 write_coeffs(846 write_coeffs(
688 enc,847 enc,
689- &mut cdfs.txb(planes[plane]),848+ &mut cdfs.txb(planes[plane], mode),
690 grid,849 grid,
691- scans[plane],850+ scan,
692 skip_ctx,851 skip_ctx,
693- dc_sign_ctx(above[plane].dc, left[plane].dc),852+ dc_sign_ctx(around[plane].dc_vote),
694 );853 );
695 }854 }
696 }855 }
@@ -734,7 +893,7 @@ pub fn split_coeff_key_frame_tile(
734 (0..4)893 (0..4)
735 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))894 .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2))
736 .filter(|&(r, c)| r < rows && c < cols)895 .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()))
738 .collect(),897 .collect(),
739 )898 )
740 })899 })
@@ -808,31 +967,62 @@ fn default_scan(side: usize) -> Vec<u16> {
808 /// so one table is all the search needs; a second block size would need its967 /// so one table is all the search needs; a second block size would need its
809 /// own entry point rather than a size argument, because the table and the scan968 /// own entry point rather than a size argument, because the table and the scan
810 /// have to agree.969 /// have to agree.
970+#[cfg(test)]
811 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {971 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
812- /// Built once: the search prices thirteen modes for every block, and the972+ coeff_bits(grid, TxbSet::Luma32)
813- /// scan is the same table every time.973+}
814- static SCAN: LazyLock<Vec<u16>> = LazyLock::new(|| default_scan(TX32));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+ };
815 let mut enc = SymbolEncoder::new();993 let mut enc = SymbolEncoder::new();
816 enc.reset_bits();994 enc.reset_bits();
817- // The search runs before the tile is written, so the adapted state the995+ write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0);
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- );
828 enc.bits()996 enc.bits()
829 }997 }
830 998
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+
831 /// coeffs() for one plane's transform block of any coefficients the base and1020 /// coeffs() for one plane's transform block of any coefficients the base and
832 /// base-range syntax reach (spec 5.11.39).1021 /// base-range syntax reach (spec 5.11.39).
833 ///1022 ///
834-/// A 32x32 or 16x16 transform is DCT-only here, so no transform type is coded;1023+/// A 16x16 luma transform codes which transform type it is, because its set
835-/// and the levels the contexts below are read from are the levels of1024+/// 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
836 /// coefficients later in the scan, which a decoder walking the scan backwards1026 /// coefficients later in the scan, which a decoder walking the scan backwards
837 /// already has.1027 /// already has.
838 fn write_coeffs(1028 fn write_coeffs(
@@ -852,6 +1042,12 @@ fn write_coeffs(
852 if eob == 0 {1042 if eob == 0 {
853 return;1043 return;
854 }1044 }
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+ }
855 1051
856 write_eob(enc, coding, eob);1052 write_eob(enc, coding, eob);
857 1053
@@ -1066,19 +1262,21 @@ fn write_dc_coeffs(
1066 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);1262 enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
1067 }1263 }
1068 1264
1069-/// `Dc_Sign_Contexts` (spec 8.3.2): every 4x4 unit above and left of the block1265+/// One neighbour cell's vote in `Dc_Sign_Contexts` (spec 8.3.2): plus one for
1070-/// votes the sign of the DC its own block carries — plus one for a positive1266+/// a positive DC, minus one for a negative one, nothing for a cell whose block
1071-/// one, minus one for a negative one, nothing for a unit with no coded1267+/// carried no DC. Every 4x4 unit of a cell votes the same way, so counting
1072-/// coefficient — and the sum picks one of three contexts. Every block here is a1268+/// cells and counting units differ only by a factor the sign is blind to.
1073-/// whole superblock carrying one DC, so all sixteen units of a neighbour vote1269+fn dc_vote(dc: Option<bool>) -> i32 {
1074-/// together and the sum can only lean up, lean down, or cancel.1270+ match dc {
1075-fn dc_sign_ctx(above: Option<bool>, left: Option<bool>) -> usize {1271+ None => 0,
1076- let vote = |n: Option<bool>| match n {
1077- None => 0i32,
1078 Some(true) => -1,1272 Some(true) => -1,
1079 Some(false) => 1,1273 Some(false) => 1,
1080- };1274+ }
1081- match (vote(above) + vote(left)).signum() {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() {
1082 0 => 0,1280 0 => 0,
1083 -1 => 1,1281 -1 => 1,
1084 _ => 2,1282 _ => 2,
@@ -1795,7 +1993,7 @@ mod tests {
1795 for grid in &grids {1993 for grid in &grids {
1796 write_coeffs(1994 write_coeffs(
1797 &mut enc,1995 &mut enc,
1798- &mut Cdfs::new().txb(TxbSet::Luma32),1996+ &mut Cdfs::new().txb(TxbSet::Luma32, 0),
1799 grid,1997 grid,
1800 &scan,1998 &scan,
1801 0,1999 0,
@@ -2090,6 +2288,41 @@ mod tests {
2090 2288
2091 /// Encodes a key frame of the given size, whose 32x32 blocks carry2289 /// Encodes a key frame of the given size, whose 32x32 blocks carry
2092 /// `blocks` in raster order, and hands back its luma plane as rows of2290 /// `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+
2093 /// samples.2326 /// samples.
2094 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {2327 fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
2095 let (seq, header) = frame_of(width as u32, height as u32);2328 let (seq, header) = frame_of(width as u32, height as u32);
@@ -2294,7 +2527,12 @@ mod tests {
2294 }]);2527 }]);
2295 let sbs = [2528 let sbs = [
2296 Superblock::Whole(across),2529 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+ ]),
2298 ];2536 ];
2299 let rows = decode_luma_sb(128, 64, &sbs);2537 let rows = decode_luma_sb(128, 64, &sbs);
2300 2538
@@ -2325,6 +2563,71 @@ mod tests {
2325 }2563 }
2326 }2564 }
2327 2565
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+
2328 /// A superblock half outside the frame has no partition that keeps a block2631 /// A superblock half outside the frame has no partition that keeps a block
2329 /// outside it, so it cannot be left whole.2632 /// outside it, so it cannot be left whole.
2330 #[test]2633 #[test]
@@ -2336,10 +2639,10 @@ mod tests {
2336 }]);2639 }]);
2337 let sbs = [2640 let sbs = [
2338 Superblock::Split(vec![2641 Superblock::Split(vec![
2339- block.clone(),2642+ Quadrant::Whole(block.clone()),
2340- block.clone(),2643+ Quadrant::Whole(block.clone()),
2341- block.clone(),2644+ Quadrant::Whole(block.clone()),
2342- block.clone(),2645+ Quadrant::Whole(block.clone()),
2343 ]),2646 ]),
2344 Superblock::Whole(block.clone()),2647 Superblock::Whole(block.clone()),
2345 ];2648 ];
@@ -2781,6 +3084,74 @@ mod tests {
2781 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");3084 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
2782 }3085 }
2783 3086
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+
2784 /// The same against the other transform size, the 64x64 one a whole3155 /// The same against the other transform size, the 64x64 one a whole
2785 /// superblock carries. Only its top-left 32x32 can hold coefficients, and3156 /// superblock carries. Only its top-left 32x32 can hold coefficients, and
2786 /// the spec zeroes the rest before the row transform — a 64-point network3157 /// 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.