forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265-rqt': residual quadtree, one split level, default on

Browse files at this commit

6a2f7f245a255950da2eb47d01a466f36837829bAhmet Kaan GümüşParent: a67ab4711904c0
crates/ec-h265/src/ctu.rsmodified+315 -5
@@ -172,6 +172,7 @@ pub struct CtuEncoder<'a> {
172 /// Whether the levels get a rate-distortion search after quantisation.172 /// Whether the levels get a rate-distortion search after quantisation.
173 rdoq: bool,173 rdoq: bool,
174 transform_skip: bool,174 transform_skip: bool,
175+ rqt: bool,
175 /// The counting CABAC engine that search prices its trials with.176 /// The counting CABAC engine that search prices its trials with.
176 rdoq_enc: CabacEncoder,177 rdoq_enc: CabacEncoder,
177 /// `log2` of the smallest coding unit the search will produce.178 /// `log2` of the smallest coding unit the search will produce.
@@ -208,6 +209,7 @@ impl<'a> CtuEncoder<'a> {
208 sign_hiding: bool,209 sign_hiding: bool,
209 rdoq: bool,210 rdoq: bool,
210 transform_skip: bool,211 transform_skip: bool,
212+ rqt: bool,
211 min_cb_log2: u32,213 min_cb_log2: u32,
212 ) -> CtuEncoder<'a> {214 ) -> CtuEncoder<'a> {
213 let band_rows = (height - band_y0).min(ctb_size);215 let band_rows = (height - band_y0).min(ctb_size);
@@ -231,6 +233,7 @@ impl<'a> CtuEncoder<'a> {
231 sign_hiding,233 sign_hiding,
232 rdoq,234 rdoq,
233 transform_skip,235 transform_skip,
236+ rqt,
234 rdoq_enc: CabacEncoder::counter(Contexts::new(qp)),237 rdoq_enc: CabacEncoder::counter(Contexts::new(qp)),
235 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),238 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
236 modes: vec![255; (width / 4) * (ctb_size / 4)],239 modes: vec![255; (width / 4) * (ctb_size / 4)],
@@ -662,7 +665,12 @@ impl<'a> CtuEncoder<'a> {
662 enc: &mut CabacEncoder,665 enc: &mut CabacEncoder,
663 ) -> f64 {666 ) -> f64 {
664 let n = 1usize << log2;667 let n = 1usize << log2;
665- let chroma_tskip = self.transform_skip && n == 8;668+ // Transform skip is a per-block flag the decoder reads for every 4x4
669+ // residual once the picture parameter set enables it, so the decision
670+ // has to travel by the block's own size, not the coding unit's: a
671+ // transform tree splits chroma down to 4x4 from a 16x16 unit too.
672+ // `code_chroma` and `encode_residual` each apply it only at 4x4.
673+ let chroma_tskip = self.transform_skip;
666 let before = enc.bit_count();674 let before = enc.bit_count();
667 if log2 == MIN_CB_LOG2 {675 if log2 == MIN_CB_LOG2 {
668 // part_mode: PART_2Nx2N is the single bin 1.676 // part_mode: PART_2Nx2N is the single bin 1.
@@ -683,6 +691,205 @@ impl<'a> CtuEncoder<'a> {
683 let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1, chroma_tskip).1;691 let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1, chroma_tskip).1;
684 let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2, chroma_tskip).1;692 let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2, chroma_tskip).1;
685 693
694+ if self.rqt && log2 > 2 {
695+ // A child transform tree signals its own chroma as long as its
696+ // chroma blocks are still 4x4 or larger; only the 8x8 luma tree,
697+ // whose children are 4x4, leaves chroma at the parent size and
698+ // codes it with the last child (7.3.8.8).
699+ let chroma_split = log2 > 3;
700+ let nosplit_rec = self.save_region(x, y, n);
701+ let parent_cb = self.scratch.cb_levels[..n * n / 4].to_vec();
702+ let parent_cr = self.scratch.cr_levels[..n * n / 4].to_vec();
703+ let start = enc.snapshot();
704+ enc.set_counting(true);
705+
706+ let nb = enc.bit_count();
707+ enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0);
708+ self.write_single_tu(
709+ enc,
710+ n,
711+ log2,
712+ mode,
713+ chroma_mode,
714+ chroma_tskip,
715+ luma_cbf,
716+ cb_cbf,
717+ cr_cbf,
718+ );
719+ let nosplit_bits = enc.bit_count() - nb;
720+ let nosplit_ssd = self.region_ssd(x, y, n);
721+
722+ enc.restore(&start);
723+
724+ let half = n / 2;
725+ let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)];
726+ let mut child_levels = [[0i32; 256]; 4];
727+ let mut child_cbf = [false; 4];
728+ let mut child_cb = [[0i32; 64]; 4];
729+ let mut child_cr = [[0i32; 64]; 4];
730+ let mut child_cb_cbf = [false; 4];
731+ let mut child_cr_cbf = [false; 4];
732+ for (part, &(dx, dy)) in offsets.iter().enumerate() {
733+ let (cx, cy) = (x + dx, y + dy);
734+ let refs = self.luma_refs(cx, cy, half);
735+ let mut source = std::mem::take(&mut self.scratch.source);
736+ for row in 0..half {
737+ source[row * half..row * half + half].copy_from_slice(
738+ &self.src.y
739+ [(cy + row) * self.width + cx..(cy + row) * self.width + cx + half],
740+ );
741+ }
742+ let (_, cbf) = self.transform_luma(half, mode, &source, &refs);
743+ child_levels[part][..half * half]
744+ .copy_from_slice(&self.scratch.levels[..half * half]);
745+ child_cbf[part] = cbf;
746+ for row in 0..half {
747+ for col in 0..half {
748+ self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * half + col]);
749+ }
750+ }
751+ self.scratch.source = source;
752+ // The next child predicts from this one, so its samples have
753+ // to read as available now rather than when the whole coding
754+ // unit is marked: a transform tree is walked in the same
755+ // z-order by the decoder.
756+ self.mark_coded(cx, cy, half, mode, depth);
757+ if chroma_split {
758+ let q = half * half / 4;
759+ let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip);
760+ child_cb_cbf[part] = cbf;
761+ child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]);
762+ let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 2, chroma_tskip);
763+ child_cr_cbf[part] = cbf;
764+ child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]);
765+ }
766+ }
767+ // The parent's flag is the OR of the children's: a clear one at
768+ // depth 0 tells the decoder to infer every child's as clear.
769+ let split_cb_cbf = if chroma_split {
770+ child_cb_cbf.iter().any(|&c| c)
771+ } else {
772+ cb_cbf
773+ };
774+ let split_cr_cbf = if chroma_split {
775+ child_cr_cbf.iter().any(|&c| c)
776+ } else {
777+ cr_cbf
778+ };
779+
780+ let sb = enc.bit_count();
781+ enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1);
782+ self.write_split_tu(
783+ enc,
784+ n,
785+ log2,
786+ mode,
787+ chroma_mode,
788+ chroma_tskip,
789+ chroma_split,
790+ split_cb_cbf,
791+ split_cr_cbf,
792+ &child_cbf,
793+ &child_levels,
794+ &child_cb_cbf,
795+ &child_cr_cbf,
796+ &child_cb,
797+ &child_cr,
798+ &parent_cb,
799+ &parent_cr,
800+ );
801+ let split_bits = enc.bit_count() - sb;
802+ let split_rec = self.save_region(x, y, n);
803+ let split_ssd = self.region_ssd(x, y, n);
804+
805+ enc.set_counting(false);
806+ enc.restore(&start);
807+
808+ let nosplit_cost = nosplit_ssd + self.lambda * nosplit_bits as f64;
809+ let split_cost = split_ssd + self.lambda * split_bits as f64;
810+
811+ if nosplit_cost <= split_cost {
812+ self.load_region(x, y, n, &nosplit_rec);
813+ // The children coded over the shared chroma scratch.
814+ self.scratch.cb_levels[..n * n / 4].copy_from_slice(&parent_cb);
815+ self.scratch.cr_levels[..n * n / 4].copy_from_slice(&parent_cr);
816+ enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0);
817+ self.write_single_tu(
818+ enc,
819+ n,
820+ log2,
821+ mode,
822+ chroma_mode,
823+ chroma_tskip,
824+ luma_cbf,
825+ cb_cbf,
826+ cr_cbf,
827+ );
828+ self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
829+ } else {
830+ self.load_region(x, y, n, &split_rec);
831+ enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1);
832+ self.write_split_tu(
833+ enc,
834+ n,
835+ log2,
836+ mode,
837+ chroma_mode,
838+ chroma_tskip,
839+ chroma_split,
840+ split_cb_cbf,
841+ split_cr_cbf,
842+ &child_cbf,
843+ &child_levels,
844+ &child_cb_cbf,
845+ &child_cr_cbf,
846+ &child_cb,
847+ &child_cr,
848+ &parent_cb,
849+ &parent_cr,
850+ );
851+ self.last_cu_empty =
852+ !(child_cbf.iter().any(|&c| c) || split_cb_cbf || split_cr_cbf);
853+ }
854+
855+ self.mark_coded(x, y, n, mode, depth);
856+ let bits = enc.bit_count() - before;
857+ return self.region_ssd(x, y, n) + self.lambda * bits as f64;
858+ }
859+
860+ // No-RQT: single TU, no split_transform_flag written (inferred 0).
861+ self.write_single_tu(
862+ enc,
863+ n,
864+ log2,
865+ mode,
866+ chroma_mode,
867+ chroma_tskip,
868+ luma_cbf,
869+ cb_cbf,
870+ cr_cbf,
871+ );
872+ self.mark_coded(x, y, n, mode, depth);
873+ self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
874+ let bits = enc.bit_count() - before;
875+ self.region_ssd(x, y, n) + self.lambda * bits as f64
876+ }
877+
878+ /// Write cbf flags + residual for one unsplit transform tree (no
879+ /// `split_transform_flag`).
880+ #[allow(clippy::too_many_arguments)]
881+ fn write_single_tu(
882+ &mut self,
883+ enc: &mut CabacEncoder,
884+ n: usize,
885+ log2: u32,
886+ mode: u8,
887+ chroma_mode: u8,
888+ chroma_tskip: bool,
889+ luma_cbf: bool,
890+ cb_cbf: bool,
891+ cr_cbf: bool,
892+ ) {
686 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));893 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
687 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));894 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
688 enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma_cbf));895 enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma_cbf));
@@ -727,11 +934,114 @@ impl<'a> CtuEncoder<'a> {
727 );934 );
728 self.scratch.cr_levels = levels;935 self.scratch.cr_levels = levels;
729 }936 }
937+ }
730 938
731- self.mark_coded(x, y, n, mode, depth);939+ /// Write cbf flags + residual for a split transform tree: chroma cbf first,
732- self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);940+ /// then four half-size luma children (CBF_LUMA ctx 0 for depth 1), chroma
733- let bits = enc.bit_count() - before;941+ /// residual on the last child.
734- self.region_ssd(x, y, n) + self.lambda * bits as f64942+ /// Write the syntax of a split transform tree: the parent's chroma flags,
943+ /// then four half-size children. A child carries its own chroma when the
944+ /// chroma blocks stay 4x4 or larger, and reads the depth-one contexts for
945+ /// both flags; below that the parent's chroma rides on the last child.
946+ #[allow(clippy::too_many_arguments)]
947+ fn write_split_tu(
948+ &mut self,
949+ enc: &mut CabacEncoder,
950+ n: usize,
951+ log2: u32,
952+ mode: u8,
953+ chroma_mode: u8,
954+ chroma_tskip: bool,
955+ chroma_split: bool,
956+ cb_cbf: bool,
957+ cr_cbf: bool,
958+ child_cbf: &[bool; 4],
959+ child_levels: &[[i32; 256]; 4],
960+ child_cb_cbf: &[bool; 4],
961+ child_cr_cbf: &[bool; 4],
962+ child_cb: &[[i32; 64]; 4],
963+ child_cr: &[[i32; 64]; 4],
964+ parent_cb: &[i32],
965+ parent_cr: &[i32],
966+ ) {
967+ let half = n / 2;
968+ enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
969+ enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
970+ let luma_scan = intra::scan_index(mode, log2 - 1, true);
971+ for part in 0..4usize {
972+ if chroma_split {
973+ if cb_cbf {
974+ enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cb_cbf[part]));
975+ }
976+ if cr_cbf {
977+ enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cr_cbf[part]));
978+ }
979+ }
980+ enc.encode_bin(ctx::CBF_LUMA, u32::from(child_cbf[part]));
981+ if child_cbf[part] {
982+ encode_residual(
983+ enc,
984+ &child_levels[part][..half * half],
985+ log2 - 1,
986+ 0,
987+ luma_scan,
988+ self.sign_hiding,
989+ self.transform_skip,
990+ );
991+ }
992+ if chroma_split {
993+ let (q, scan) = (
994+ half * half / 4,
995+ intra::scan_index(chroma_mode, log2 - 2, false),
996+ );
997+ if cb_cbf && child_cb_cbf[part] {
998+ encode_residual(
999+ enc,
1000+ &child_cb[part][..q],
1001+ log2 - 2,
1002+ 1,
1003+ scan,
1004+ self.sign_hiding,
1005+ chroma_tskip,
1006+ );
1007+ }
1008+ if cr_cbf && child_cr_cbf[part] {
1009+ encode_residual(
1010+ enc,
1011+ &child_cr[part][..q],
1012+ log2 - 2,
1013+ 2,
1014+ scan,
1015+ self.sign_hiding,
1016+ chroma_tskip,
1017+ );
1018+ }
1019+ } else if part == 3 {
1020+ let scan = intra::scan_index(chroma_mode, log2 - 1, false);
1021+ if cb_cbf {
1022+ encode_residual(
1023+ enc,
1024+ &parent_cb[..n * n / 4],
1025+ log2 - 1,
1026+ 1,
1027+ scan,
1028+ self.sign_hiding,
1029+ chroma_tskip,
1030+ );
1031+ }
1032+ if cr_cbf {
1033+ encode_residual(
1034+ enc,
1035+ &parent_cr[..n * n / 4],
1036+ log2 - 1,
1037+ 2,
1038+ scan,
1039+ self.sign_hiding,
1040+ chroma_tskip,
1041+ );
1042+ }
1043+ }
1044+ }
735 }1045 }
736 1046
737 fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) {1047 fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) {
crates/ec-h265/src/encoder.rsmodified+11 -1
@@ -167,6 +167,14 @@ pub struct EncoderConfig {
167 pub rdoq: bool,167 pub rdoq: bool,
168 /// Whether 4x4 TUs may skip the integer transform.168 /// Whether 4x4 TUs may skip the integer transform.
169 pub transform_skip: TransformSkip,169 pub transform_skip: TransformSkip,
170+ /// Whether the transform tree may split once (rate-quantisation transform):
171+ /// the luma TU of a 2Nx2N coding unit may be coded as four half-size
172+ /// children when that costs less in `J = SSD + lambda * bits`.
173+ ///
174+ /// On by default: measured against x265 over the four-point ladder it is
175+ /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which
176+ /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`).
177+ pub rqt: bool,
170 /// What the samples mean, written into the VUI.178 /// What the samples mean, written into the VUI.
171 pub video_signal_type: Option<VideoSignalType>,179 pub video_signal_type: Option<VideoSignalType>,
172 /// Sample aspect ratio.180 /// Sample aspect ratio.
@@ -199,6 +207,7 @@ impl EncoderConfig {
199 sign_hiding: false,207 sign_hiding: false,
200 rdoq: true,208 rdoq: true,
201 transform_skip: TransformSkip::Off,209 transform_skip: TransformSkip::Off,
210+ rqt: true,
202 video_signal_type: None,211 video_signal_type: None,
203 sample_aspect_ratio: None,212 sample_aspect_ratio: None,
204 timing: None,213 timing: None,
@@ -295,7 +304,7 @@ impl Encoder {
295 log2_min_tb_size_minus2: 0,304 log2_min_tb_size_minus2: 0,
296 log2_diff_max_min_tb_size: 3,305 log2_diff_max_min_tb_size: 3,
297 max_transform_hierarchy_depth_inter: 0,306 max_transform_hierarchy_depth_inter: 0,
298- max_transform_hierarchy_depth_intra: 0,307+ max_transform_hierarchy_depth_intra: if cfg.rqt { 1 } else { 0 },
299 scaling_list_enabled: false,308 scaling_list_enabled: false,
300 amp_enabled: false,309 amp_enabled: false,
301 // No in-loop filters: see `Encoder` docs and the PPS below.310 // No in-loop filters: see `Encoder` docs and the PPS below.
@@ -579,6 +588,7 @@ impl Encoder {
579 self.cfg.sign_hiding,588 self.cfg.sign_hiding,
580 self.cfg.rdoq,589 self.cfg.rdoq,
581 self.cfg.transform_skip != TransformSkip::Off,590 self.cfg.transform_skip != TransformSkip::Off,
591+ self.cfg.rqt,
582 self.cfg.min_cu_size.max(8).trailing_zeros(),592 self.cfg.min_cu_size.max(8).trailing_zeros(),
583 );593 );
584 for col in 0..cols {594 for col in 0..cols {
crates/ec-h265/tests/conformance.rsmodified+351 -6
@@ -163,7 +163,50 @@ fn chroma_mode_search_decodes_bit_exactly() {
163 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));163 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
164 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");164 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
165 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();165 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
166- assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");166+ if mismatches != 0 {
167+ // Which plane and where: a luma-only divergence is the transform
168+ // tree, a chroma-only one is the flags that ride on it.
169+ let luma = (w * h) as usize;
170+ let chroma = luma / 4;
171+ let first = decoded
172+ .iter()
173+ .zip(&recon)
174+ .position(|(a, b)| a != b)
175+ .unwrap();
176+ let count = |range: std::ops::Range<usize>| {
177+ decoded[range.clone()]
178+ .iter()
179+ .zip(&recon[range])
180+ .filter(|(a, b)| a != b)
181+ .count()
182+ };
183+ let mut map = String::new();
184+ for by in (0..h as usize).step_by(16) {
185+ for bx in (0..w as usize).step_by(16) {
186+ let mut c = 0;
187+ for row in by..by + 16 {
188+ for col in bx..bx + 16 {
189+ let i = row * w as usize + col;
190+ if decoded[i] != recon[i] {
191+ c += 1;
192+ }
193+ }
194+ }
195+ map.push_str(&format!("{c:4}"));
196+ }
197+ map.push('\n');
198+ }
199+ eprintln!("luma 16x16 mismatch map:\n{map}");
200+ panic!(
201+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
202+ ({}, {})",
203+ count(0..luma),
204+ count(luma..luma + chroma),
205+ count(luma + chroma..luma + 2 * chroma),
206+ first % w as usize,
207+ first / w as usize,
208+ );
209+ }
167 let quality = psnr(&planes_of(&source), &recon);210 let quality = psnr(&planes_of(&source), &recon);
168 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27");211 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27");
169 }212 }
@@ -197,7 +240,50 @@ fn intra_nxn_decodes_bit_exactly() {
197 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));240 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
198 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");241 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
199 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();242 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
200- assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");243+ if mismatches != 0 {
244+ // Which plane and where: a luma-only divergence is the transform
245+ // tree, a chroma-only one is the flags that ride on it.
246+ let luma = (w * h) as usize;
247+ let chroma = luma / 4;
248+ let first = decoded
249+ .iter()
250+ .zip(&recon)
251+ .position(|(a, b)| a != b)
252+ .unwrap();
253+ let count = |range: std::ops::Range<usize>| {
254+ decoded[range.clone()]
255+ .iter()
256+ .zip(&recon[range])
257+ .filter(|(a, b)| a != b)
258+ .count()
259+ };
260+ let mut map = String::new();
261+ for by in (0..h as usize).step_by(16) {
262+ for bx in (0..w as usize).step_by(16) {
263+ let mut c = 0;
264+ for row in by..by + 16 {
265+ for col in bx..bx + 16 {
266+ let i = row * w as usize + col;
267+ if decoded[i] != recon[i] {
268+ c += 1;
269+ }
270+ }
271+ }
272+ map.push_str(&format!("{c:4}"));
273+ }
274+ map.push('\n');
275+ }
276+ eprintln!("luma 16x16 mismatch map:\n{map}");
277+ panic!(
278+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
279+ ({}, {})",
280+ count(0..luma),
281+ count(luma..luma + chroma),
282+ count(luma + chroma..luma + 2 * chroma),
283+ first % w as usize,
284+ first / w as usize,
285+ );
286+ }
201 let quality = psnr(&planes_of(&source), &recon);287 let quality = psnr(&planes_of(&source), &recon);
202 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");288 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");
203 }289 }
@@ -235,7 +321,50 @@ fn sign_hiding_decodes_bit_exactly() {
235 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));321 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
236 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");322 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
237 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();323 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
238- assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");324+ if mismatches != 0 {
325+ // Which plane and where: a luma-only divergence is the transform
326+ // tree, a chroma-only one is the flags that ride on it.
327+ let luma = (w * h) as usize;
328+ let chroma = luma / 4;
329+ let first = decoded
330+ .iter()
331+ .zip(&recon)
332+ .position(|(a, b)| a != b)
333+ .unwrap();
334+ let count = |range: std::ops::Range<usize>| {
335+ decoded[range.clone()]
336+ .iter()
337+ .zip(&recon[range])
338+ .filter(|(a, b)| a != b)
339+ .count()
340+ };
341+ let mut map = String::new();
342+ for by in (0..h as usize).step_by(16) {
343+ for bx in (0..w as usize).step_by(16) {
344+ let mut c = 0;
345+ for row in by..by + 16 {
346+ for col in bx..bx + 16 {
347+ let i = row * w as usize + col;
348+ if decoded[i] != recon[i] {
349+ c += 1;
350+ }
351+ }
352+ }
353+ map.push_str(&format!("{c:4}"));
354+ }
355+ map.push('\n');
356+ }
357+ eprintln!("luma 16x16 mismatch map:\n{map}");
358+ panic!(
359+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
360+ ({}, {})",
361+ count(0..luma),
362+ count(luma..luma + chroma),
363+ count(luma + chroma..luma + 2 * chroma),
364+ first % w as usize,
365+ first / w as usize,
366+ );
367+ }
239 let quality = psnr(&planes_of(&source), &recon);368 let quality = psnr(&planes_of(&source), &recon);
240 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");369 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");
241 }370 }
@@ -301,7 +430,50 @@ fn transform_skip_decodes_bit_exactly() {
301 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));430 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
302 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");431 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
303 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();432 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
304- assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");433+ if mismatches != 0 {
434+ // Which plane and where: a luma-only divergence is the transform
435+ // tree, a chroma-only one is the flags that ride on it.
436+ let luma = (w * h) as usize;
437+ let chroma = luma / 4;
438+ let first = decoded
439+ .iter()
440+ .zip(&recon)
441+ .position(|(a, b)| a != b)
442+ .unwrap();
443+ let count = |range: std::ops::Range<usize>| {
444+ decoded[range.clone()]
445+ .iter()
446+ .zip(&recon[range])
447+ .filter(|(a, b)| a != b)
448+ .count()
449+ };
450+ let mut map = String::new();
451+ for by in (0..h as usize).step_by(16) {
452+ for bx in (0..w as usize).step_by(16) {
453+ let mut c = 0;
454+ for row in by..by + 16 {
455+ for col in bx..bx + 16 {
456+ let i = row * w as usize + col;
457+ if decoded[i] != recon[i] {
458+ c += 1;
459+ }
460+ }
461+ }
462+ map.push_str(&format!("{c:4}"));
463+ }
464+ map.push('\n');
465+ }
466+ eprintln!("luma 16x16 mismatch map:\n{map}");
467+ panic!(
468+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
469+ ({}, {})",
470+ count(0..luma),
471+ count(luma..luma + chroma),
472+ count(luma + chroma..luma + 2 * chroma),
473+ first % w as usize,
474+ first / w as usize,
475+ );
476+ }
305 let quality = psnr(&planes_of(&source), &recon);477 let quality = psnr(&planes_of(&source), &recon);
306 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");478 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");
307 }479 }
@@ -343,7 +515,50 @@ fn ffmpeg_decodes_bit_exactly_at_every_shape() {
343 recon.len()515 recon.len()
344 );516 );
345 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();517 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
346- assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");518+ if mismatches != 0 {
519+ // Which plane and where: a luma-only divergence is the transform
520+ // tree, a chroma-only one is the flags that ride on it.
521+ let luma = (w * h) as usize;
522+ let chroma = luma / 4;
523+ let first = decoded
524+ .iter()
525+ .zip(&recon)
526+ .position(|(a, b)| a != b)
527+ .unwrap();
528+ let count = |range: std::ops::Range<usize>| {
529+ decoded[range.clone()]
530+ .iter()
531+ .zip(&recon[range])
532+ .filter(|(a, b)| a != b)
533+ .count()
534+ };
535+ let mut map = String::new();
536+ for by in (0..h as usize).step_by(16) {
537+ for bx in (0..w as usize).step_by(16) {
538+ let mut c = 0;
539+ for row in by..by + 16 {
540+ for col in bx..bx + 16 {
541+ let i = row * w as usize + col;
542+ if decoded[i] != recon[i] {
543+ c += 1;
544+ }
545+ }
546+ }
547+ map.push_str(&format!("{c:4}"));
548+ }
549+ map.push('\n');
550+ }
551+ eprintln!("luma 16x16 mismatch map:\n{map}");
552+ panic!(
553+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
554+ ({}, {})",
555+ count(0..luma),
556+ count(luma..luma + chroma),
557+ count(luma + chroma..luma + 2 * chroma),
558+ first % w as usize,
559+ first / w as usize,
560+ );
561+ }
347 // And the encode is worth something: PSNR against the source.562 // And the encode is worth something: PSNR against the source.
348 let quality = psnr(&planes_of(&source), &recon);563 let quality = psnr(&planes_of(&source), &recon);
349 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27");564 assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27");
@@ -568,7 +783,50 @@ fn rdoq_decodes_bit_exactly() {
568 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));783 let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
569 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");784 assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
570 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();785 let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
571- assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");786+ if mismatches != 0 {
787+ // Which plane and where: a luma-only divergence is the transform
788+ // tree, a chroma-only one is the flags that ride on it.
789+ let luma = (w * h) as usize;
790+ let chroma = luma / 4;
791+ let first = decoded
792+ .iter()
793+ .zip(&recon)
794+ .position(|(a, b)| a != b)
795+ .unwrap();
796+ let count = |range: std::ops::Range<usize>| {
797+ decoded[range.clone()]
798+ .iter()
799+ .zip(&recon[range])
800+ .filter(|(a, b)| a != b)
801+ .count()
802+ };
803+ let mut map = String::new();
804+ for by in (0..h as usize).step_by(16) {
805+ for bx in (0..w as usize).step_by(16) {
806+ let mut c = 0;
807+ for row in by..by + 16 {
808+ for col in bx..bx + 16 {
809+ let i = row * w as usize + col;
810+ if decoded[i] != recon[i] {
811+ c += 1;
812+ }
813+ }
814+ }
815+ map.push_str(&format!("{c:4}"));
816+ }
817+ map.push('\n');
818+ }
819+ eprintln!("luma 16x16 mismatch map:\n{map}");
820+ panic!(
821+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
822+ ({}, {})",
823+ count(0..luma),
824+ count(luma..luma + chroma),
825+ count(luma + chroma..luma + 2 * chroma),
826+ first % w as usize,
827+ first / w as usize,
828+ );
829+ }
572 let quality = psnr(&planes_of(&source), &recon);830 let quality = psnr(&planes_of(&source), &recon);
573 assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27");831 assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27");
574 }832 }
@@ -587,3 +845,90 @@ fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, Enc
587 let coded = encoder.encode_idr(&frame).expect("encode");845 let coded = encoder.encode_idr(&frame).expect("encode");
588 (frame, coded)846 (frame, coded)
589 }847 }
848+
849+/// RQT must produce a bitstream a conformant decoder reads back to the exact
850+/// samples the encoder reconstructed.
851+#[test]
852+fn rqt_decodes_bit_exactly() {
853+ if !have_ffmpeg() {
854+ eprintln!("skipping: ffmpeg not installed");
855+ return;
856+ }
857+ for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] {
858+ let (source, coded) = encode_rqt(w, h, 27, true);
859+ let (_, plain) = encode_rqt(w, h, 27, false);
860+ let name = format!("rqt-{w}x{h}");
861+ assert_ne!(
862+ coded.au, plain.au,
863+ "{name}: RQT changed no byte, so the split path is not running"
864+ );
865+ let path = write_au(&name, &coded);
866+ let decoded = match ffmpeg_decode(&path) {
867+ Ok(bytes) => bytes,
868+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
869+ };
870+ let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
871+ assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
872+ let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
873+ if mismatches != 0 {
874+ // Which plane and where: a luma-only divergence is the transform
875+ // tree, a chroma-only one is the flags that ride on it.
876+ let luma = (w * h) as usize;
877+ let chroma = luma / 4;
878+ let first = decoded
879+ .iter()
880+ .zip(&recon)
881+ .position(|(a, b)| a != b)
882+ .unwrap();
883+ let count = |range: std::ops::Range<usize>| {
884+ decoded[range.clone()]
885+ .iter()
886+ .zip(&recon[range])
887+ .filter(|(a, b)| a != b)
888+ .count()
889+ };
890+ let mut map = String::new();
891+ for by in (0..h as usize).step_by(16) {
892+ for bx in (0..w as usize).step_by(16) {
893+ let mut c = 0;
894+ for row in by..by + 16 {
895+ for col in bx..bx + 16 {
896+ let i = row * w as usize + col;
897+ if decoded[i] != recon[i] {
898+ c += 1;
899+ }
900+ }
901+ }
902+ map.push_str(&format!("{c:4}"));
903+ }
904+ map.push('\n');
905+ }
906+ eprintln!("luma 16x16 mismatch map:\n{map}");
907+ panic!(
908+ "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \
909+ ({}, {})",
910+ count(0..luma),
911+ count(luma..luma + chroma),
912+ count(luma + chroma..luma + 2 * chroma),
913+ first % w as usize,
914+ first / w as usize,
915+ );
916+ }
917+ let quality = psnr(&planes_of(&source), &recon);
918+ assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27");
919+ }
920+}
921+
922+/// The natural frame coded with RQT on or off, everything else left at its
923+/// default.
924+fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) {
925+ let mut cfg = EncoderConfig::new(width, height);
926+ cfg.rqt = rqt;
927+ cfg.rate_control = RateControl::ConstantQp(qp);
928+ cfg.keep_recon = true;
929+ cfg.picture_hash = true;
930+ let encoder = Encoder::new(cfg).expect("encoder");
931+ let frame = natural_frame(width, height, 0);
932+ let coded = encoder.encode_idr(&frame).expect("encode");
933+ (frame, coded)
934+}
crates/ec-h265/tests/encode.rsmodified+3 -0
@@ -451,6 +451,9 @@ fn bd_psnr_vs_x265() {
451 if let Ok(v) = std::env::var("EC_H265_NXN") {451 if let Ok(v) = std::env::var("EC_H265_NXN") {
452 cfg.intra_nxn = v != "0";452 cfg.intra_nxn = v != "0";
453 }453 }
454+ if let Ok(v) = std::env::var("EC_H265_RQT") {
455+ cfg.rqt = v != "0";
456+ }
454 if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") {457 if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") {
455 cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number");458 cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number");
456 }459 }
lanes/h265-rqt-r1.report.mdadded+56 -0
@@ -0,0 +1,56 @@
1+# lane-h265-rqt r1 — residual quadtree, one split level
2+
3+## What landed
4+
5+`max_transform_hierarchy_depth_intra = 1`: a 2N×2N intra coding unit may split its
6+luma transform once into four half-size children, chosen by `J = SSD + lambda * bits`
7+against the unsplit block. Chroma splits with the tree while its own blocks stay 4×4
8+or larger (log2 > 3); at an 8×8 luma tree chroma stays at the parent size and is
9+coded with the last child, per 7.3.8.8. The parent luma cbf is the OR of the
10+children's. Default: on.
11+
12+## Gates
13+
14+| gate | result |
15+| --- | --- |
16+| `cargo test --release -p ec-h265` | 14/14 conformance, whole suite green |
17+| `rqt_decodes_bit_exactly` | ffmpeg reconstruction sample-exact |
18+| `transform_skip_decodes_bit_exactly` | sample-exact with rqt on (see defect below) |
19+| clippy `--all-targets` | 0 warnings |
20+
21+## Rate-distortion, four-point ladder against x265
22+
23+BD-PSNR of ours against x265 (higher = closer to x265; both arms same ladder):
24+
25+| clip class | rqt off | rqt on | delta |
26+| --- | --- | --- | --- |
27+| film | +0.036 | +0.046 | **+0.010** |
28+| screen capture | −0.043 | +0.037 | **+0.080** |
29+
30+Ladder QP shift: −1 on film, 0 on screen. RQT wins on both content classes, so it
31+is on by default — the ffmpeg/x265 default for intra depth is likewise ≥1.
32+
33+## Defect found and fixed in-lane
34+
35+Flipping the default to on broke `transform_skip_decodes_bit_exactly`:
36+`2955 samples differ -- Y 1938, Cb 510, Cr 507, first at (8, 32)`, everything from
37+luma row 32 down diverging — a CABAC desync, not a reconstruction difference.
38+
39+Cause: `transform_skip_flag` is read by the decoder for **every** 4×4 residual block
40+once the picture parameter set enables skip, and the encoder decided it from the
41+coding unit's size (`transform_skip && n == 8`, i.e. "chroma is 4×4 only under an
42+8×8 unit"). With a transform tree, a 16×16 unit splits chroma to 4×4 as well; those
43+blocks were coded with a real transform and no flag written, while the decoder read
44+one. The decision now travels by the block's own size — `code_chroma` and
45+`encode_residual` each already apply it only at 4×4.
46+
47+Class: **decision carried at the wrong granularity** — a syntax element that belongs
48+to the transform block was decided from the coding unit. Swept: the only other
49+size-conditioned decisions (`ctu.rs:1268` skip, `intra.rs:122/146` filtering and
50+strong smoothing) all take the transform block's own size. Clean.
51+
52+## Not in this lane
53+
54+- Depth > 1 (`max_transform_hierarchy_depth_intra = 2`), and the inter tree.
55+- NxN partitions above 8×8 (still 2Nx2N only outside the minimum unit).
56+- 64×64 coding units — the remaining lever for the screen-capture gap.