forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265-cu64': 64x64 coding units

Browse files at this commit

7f0bc2a66316695359bfab3ac69130d84af18ec0Ahmet Kaan GümüşParent: ecc4efc826a8f8
crates/ec-h265/src/ctu.rsmodified+123 -7
@@ -173,6 +173,9 @@ pub struct CtuEncoder<'a> {
173 rdoq: bool,173 rdoq: bool,
174 transform_skip: bool,174 transform_skip: bool,
175 rqt: bool,175 rqt: bool,
176+ /// Whether a 64x64 coding tree block may stay one coding unit rather than
177+ /// always splitting to 32x32.
178+ cu64: bool,
176 /// The counting CABAC engine that search prices its trials with.179 /// The counting CABAC engine that search prices its trials with.
177 rdoq_enc: CabacEncoder,180 rdoq_enc: CabacEncoder,
178 /// `log2` of the smallest coding unit the search will produce.181 /// `log2` of the smallest coding unit the search will produce.
@@ -210,6 +213,7 @@ impl<'a> CtuEncoder<'a> {
210 rdoq: bool,213 rdoq: bool,
211 transform_skip: bool,214 transform_skip: bool,
212 rqt: bool,215 rqt: bool,
216+ cu64: bool,
213 min_cb_log2: u32,217 min_cb_log2: u32,
214 ) -> CtuEncoder<'a> {218 ) -> CtuEncoder<'a> {
215 let band_rows = (height - band_y0).min(ctb_size);219 let band_rows = (height - band_y0).min(ctb_size);
@@ -234,6 +238,7 @@ impl<'a> CtuEncoder<'a> {
234 rdoq,238 rdoq,
235 transform_skip,239 transform_skip,
236 rqt,240 rqt,
241+ cu64,
237 rdoq_enc: CabacEncoder::counter(Contexts::new(qp)),242 rdoq_enc: CabacEncoder::counter(Contexts::new(qp)),
238 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),243 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
239 modes: vec![255; (width / 4) * (ctb_size / 4)],244 modes: vec![255; (width / 4) * (ctb_size / 4)],
@@ -387,7 +392,7 @@ impl<'a> CtuEncoder<'a> {
387 return self.lambda * (enc.bit_count() - before) as f64392 return self.lambda * (enc.bit_count() - before) as f64
388 + self.code_cu(x, y, log2, depth, enc);393 + self.code_cu(x, y, log2, depth, enc);
389 }394 }
390- if log2 > 5 {395+ if log2 > 5 && !self.cu64 {
391 // 64x64 coding units are not searched; the decision starts at 32x32.396 // 64x64 coding units are not searched; the decision starts at 32x32.
392 let before = enc.bit_count();397 let before = enc.bit_count();
393 enc.encode_bin(split_ctx, 1);398 enc.encode_bin(split_ctx, 1);
@@ -656,6 +661,114 @@ impl<'a> CtuEncoder<'a> {
656 self.region_ssd(x, y, 8) + self.lambda * bits as f64661 self.region_ssd(x, y, 8) + self.lambda * bits as f64
657 }662 }
658 663
664+ /// Code one 64x64 coding unit.
665+ ///
666+ /// HEVC's largest transform block is 32x32, so the transform tree of a
667+ /// 64x64 coding unit is split without a `split_transform_flag` -- the
668+ /// decoder infers the split from `log2TrafoSize > MaxTbLog2SizeY` (7.4.9.8)
669+ /// -- and intra prediction runs per transform block, four 32x32 ones in
670+ /// z-order, each predicting from the reconstruction of the ones before it.
671+ /// The coding unit carries a single luma mode and a single chroma mode, so
672+ /// what it saves over four 32x32 coding units is three split flags and
673+ /// three mode signallings; what it gives up is three quarters of the
674+ /// freedom to pick a direction.
675+ ///
676+ /// The mode search runs on the first quadrant: that is the only one whose
677+ /// neighbours are settled before a mode is chosen, and it is what the
678+ /// reference encoder does for the same reason.
679+ fn code_cu_64(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 {
680+ const N: usize = 64;
681+ const HALF: usize = 32;
682+ const LOG2: u32 = 6;
683+ let chroma_tskip = self.transform_skip;
684+ let before = enc.bit_count();
685+
686+ let mpm = self.mpm_at(x, y);
687+ // Reconstructs the first quadrant under the mode it picks, leaving its
688+ // levels in the luma scratch.
689+ let mode = self.choose_luma_mode(x, y, HALF, LOG2 - 1, &mpm, enc);
690+ self.write_mode_syntax(enc, mode, &mpm);
691+ let (chroma_mode, chroma_idx) = if self.chroma_rd {
692+ self.choose_chroma_mode(x, y, HALF, LOG2 - 1, mode, chroma_tskip, enc)
693+ } else {
694+ (mode, None)
695+ };
696+ self.write_chroma_mode_syntax(enc, chroma_idx);
697+
698+ let mut child_levels = [[0i32; 1024]; 4];
699+ let mut child_cbf = [false; 4];
700+ let mut child_cb = [[0i32; 256]; 4];
701+ let mut child_cr = [[0i32; 256]; 4];
702+ let mut child_cb_cbf = [false; 4];
703+ let mut child_cr_cbf = [false; 4];
704+ let offsets = [(0usize, 0usize), (HALF, 0), (0, HALF), (HALF, HALF)];
705+ let q = HALF * HALF / 4;
706+ for (part, &(dx, dy)) in offsets.iter().enumerate() {
707+ let (cx, cy) = (x + dx, y + dy);
708+ if part == 0 {
709+ // Already coded by the mode search.
710+ child_levels[0][..HALF * HALF]
711+ .copy_from_slice(&self.scratch.luma_levels[..HALF * HALF]);
712+ child_cbf[0] = child_levels[0][..HALF * HALF].iter().any(|&v| v != 0);
713+ } else {
714+ let refs = self.luma_refs(cx, cy, HALF);
715+ let mut source = std::mem::take(&mut self.scratch.source);
716+ for row in 0..HALF {
717+ source[row * HALF..row * HALF + HALF].copy_from_slice(
718+ &self.src.y
719+ [(cy + row) * self.width + cx..(cy + row) * self.width + cx + HALF],
720+ );
721+ }
722+ let (_, cbf) = self.transform_luma(HALF, mode, &source, &refs);
723+ self.scratch.source = source;
724+ child_levels[part][..HALF * HALF]
725+ .copy_from_slice(&self.scratch.levels[..HALF * HALF]);
726+ child_cbf[part] = cbf;
727+ for row in 0..HALF {
728+ for col in 0..HALF {
729+ self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * HALF + col]);
730+ }
731+ }
732+ }
733+ // The next quadrant predicts from this one, so its samples have to
734+ // read as available now: the decoder walks the tree in z-order too.
735+ self.mark_coded(cx, cy, HALF, mode, depth);
736+ let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 1, chroma_tskip);
737+ child_cb_cbf[part] = cbf;
738+ child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]);
739+ let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 2, chroma_tskip);
740+ child_cr_cbf[part] = cbf;
741+ child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]);
742+ }
743+
744+ // The parent's flag is the OR of the children's: a clear one at depth 0
745+ // tells the decoder to infer every child's as clear.
746+ let cb_cbf = child_cb_cbf.iter().any(|&c| c);
747+ let cr_cbf = child_cr_cbf.iter().any(|&c| c);
748+ self.write_split_tu(
749+ enc,
750+ N,
751+ LOG2,
752+ mode,
753+ chroma_mode,
754+ chroma_tskip,
755+ true,
756+ cb_cbf,
757+ cr_cbf,
758+ &child_cbf,
759+ &child_levels,
760+ &child_cb_cbf,
761+ &child_cr_cbf,
762+ &child_cb,
763+ &child_cr,
764+ &[],
765+ &[],
766+ );
767+ self.last_cu_empty = !(child_cbf.iter().any(|&c| c) || cb_cbf || cr_cbf);
768+ let bits = enc.bit_count() - before;
769+ self.region_ssd(x, y, N) + self.lambda * bits as f64
770+ }
771+
659 fn code_cu_2nx2n(772 fn code_cu_2nx2n(
660 &mut self,773 &mut self,
661 x: usize,774 x: usize,
@@ -664,6 +777,9 @@ impl<'a> CtuEncoder<'a> {
664 depth: u8,777 depth: u8,
665 enc: &mut CabacEncoder,778 enc: &mut CabacEncoder,
666 ) -> f64 {779 ) -> f64 {
780+ if log2 > 5 {
781+ return self.code_cu_64(x, y, depth, enc);
782+ }
667 let n = 1usize << log2;783 let n = 1usize << log2;
668 // Transform skip is a per-block flag the decoder reads for every 4x4784 // Transform skip is a per-block flag the decoder reads for every 4x4
669 // residual once the picture parameter set enables it, so the decision785 // residual once the picture parameter set enables it, so the decision
@@ -723,10 +839,10 @@ impl<'a> CtuEncoder<'a> {
723 839
724 let half = n / 2;840 let half = n / 2;
725 let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)];841 let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)];
726- let mut child_levels = [[0i32; 256]; 4];842+ let mut child_levels = [[0i32; 1024]; 4];
727 let mut child_cbf = [false; 4];843 let mut child_cbf = [false; 4];
728- let mut child_cb = [[0i32; 64]; 4];844+ let mut child_cb = [[0i32; 256]; 4];
729- let mut child_cr = [[0i32; 64]; 4];845+ let mut child_cr = [[0i32; 256]; 4];
730 let mut child_cb_cbf = [false; 4];846 let mut child_cb_cbf = [false; 4];
731 let mut child_cr_cbf = [false; 4];847 let mut child_cr_cbf = [false; 4];
732 for (part, &(dx, dy)) in offsets.iter().enumerate() {848 for (part, &(dx, dy)) in offsets.iter().enumerate() {
@@ -956,11 +1072,11 @@ impl<'a> CtuEncoder<'a> {
956 cb_cbf: bool,1072 cb_cbf: bool,
957 cr_cbf: bool,1073 cr_cbf: bool,
958 child_cbf: &[bool; 4],1074 child_cbf: &[bool; 4],
959- child_levels: &[[i32; 256]; 4],1075+ child_levels: &[[i32; 1024]; 4],
960 child_cb_cbf: &[bool; 4],1076 child_cb_cbf: &[bool; 4],
961 child_cr_cbf: &[bool; 4],1077 child_cr_cbf: &[bool; 4],
962- child_cb: &[[i32; 64]; 4],1078+ child_cb: &[[i32; 256]; 4],
963- child_cr: &[[i32; 64]; 4],1079+ child_cr: &[[i32; 256]; 4],
964 parent_cb: &[i32],1080 parent_cb: &[i32],
965 parent_cr: &[i32],1081 parent_cr: &[i32],
966 ) {1082 ) {
crates/ec-h265/src/encoder.rsmodified+15 -0
@@ -175,6 +175,19 @@ pub struct EncoderConfig {
175 /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which175 /// 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`).176 /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`).
177 pub rqt: bool,177 pub rqt: bool,
178+ /// Whether a 64x64 coding tree block may stay one coding unit instead of
179+ /// always splitting to 32x32. Only reachable with `ctb_size` 64.
180+ ///
181+ /// A 64x64 intra coding unit still predicts and transforms in four 32x32
182+ /// blocks -- 32x32 is HEVC's largest transform -- so what it buys is three
183+ /// split flags and three mode signallings, and what it costs is one luma
184+ /// direction for the whole 64x64. Measured in `lanes/h265-cu64-r1.report.md`.
185+ ///
186+ /// On by default: against x265 over the four-point ladder it is worth
187+ /// +0.007 dB BD-PSNR on film and +0.098 dB on screen capture over always
188+ /// splitting a 64x64 tree block, and the default `ctb_size` of 32 leaves
189+ /// it unreachable anyway.
190+ pub cu64: bool,
178 /// What the samples mean, written into the VUI.191 /// What the samples mean, written into the VUI.
179 pub video_signal_type: Option<VideoSignalType>,192 pub video_signal_type: Option<VideoSignalType>,
180 /// Sample aspect ratio.193 /// Sample aspect ratio.
@@ -208,6 +221,7 @@ impl EncoderConfig {
208 rdoq: true,221 rdoq: true,
209 transform_skip: TransformSkip::Off,222 transform_skip: TransformSkip::Off,
210 rqt: true,223 rqt: true,
224+ cu64: true,
211 video_signal_type: None,225 video_signal_type: None,
212 sample_aspect_ratio: None,226 sample_aspect_ratio: None,
213 timing: None,227 timing: None,
@@ -589,6 +603,7 @@ impl Encoder {
589 self.cfg.rdoq,603 self.cfg.rdoq,
590 self.cfg.transform_skip != TransformSkip::Off,604 self.cfg.transform_skip != TransformSkip::Off,
591 self.cfg.rqt,605 self.cfg.rqt,
606+ self.cfg.cu64,
592 self.cfg.min_cu_size.max(8).trailing_zeros(),607 self.cfg.min_cu_size.max(8).trailing_zeros(),
593 );608 );
594 for col in 0..cols {609 for col in 0..cols {
crates/ec-h265/tests/conformance.rsmodified+71 -0
@@ -565,6 +565,77 @@ fn ffmpeg_decodes_bit_exactly_at_every_shape() {
565 }565 }
566 }566 }
567 567
568+/// A 64x64 coding unit predicts and transforms in four 32x32 blocks under one
569+/// luma mode, with the transform split inferred rather than signalled
570+/// (`log2TrafoSize > MaxTbLog2SizeY`, 7.4.9.8). That inference is the part a
571+/// decoder disagrees with loudly, so it is gated against ffmpeg -- and the
572+/// stream has to differ from the same encode with `cu64` off, or the test would
573+/// pass without a single 64x64 coding unit ever being kept.
574+#[test]
575+fn cu64_decodes_bit_exactly() {
576+ if !have_ffmpeg() {
577+ eprintln!("skipping: ffmpeg not installed");
578+ return;
579+ }
580+ // 130x66 is here for the partial coding tree blocks, not for the decision:
581+ // at that size only two tree blocks are whole and the search keeps neither,
582+ // so its stream is allowed to come out identical.
583+ for &(w, h, qp, fires) in &[
584+ (352u32, 288u32, 32i32, true),
585+ (256, 256, 37, true),
586+ (130, 66, 32, false),
587+ ] {
588+ let (source, off) = encode_cu64(w, h, qp, false);
589+ let (_, on) = encode_cu64(w, h, qp, true);
590+ let name = format!("cu64-{w}x{h}-qp{qp}");
591+ if fires {
592+ assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept");
593+ }
594+
595+ let path = write_au(&name, &on);
596+ let decoded = match ffmpeg_decode(&path) {
597+ Ok(bytes) => bytes,
598+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
599+ };
600+ let recon = planes_of(on.recon.as_ref().expect("recon kept"));
601+ assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
602+ let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
603+ if mismatches != 0 {
604+ let first = decoded
605+ .iter()
606+ .zip(&recon)
607+ .position(|(a, b)| a != b)
608+ .unwrap();
609+ let luma = (w * h) as usize;
610+ panic!(
611+ "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma",
612+ first % w as usize,
613+ first / w as usize,
614+ decoded[..luma]
615+ .iter()
616+ .zip(&recon[..luma])
617+ .filter(|(a, b)| a != b)
618+ .count(),
619+ );
620+ }
621+ let quality = psnr(&planes_of(&source), &recon);
622+ assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}");
623+ }
624+}
625+
626+fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) {
627+ let mut cfg = EncoderConfig::new(width, height);
628+ cfg.ctb_size = 64;
629+ cfg.cu64 = cu64;
630+ cfg.rate_control = RateControl::ConstantQp(qp);
631+ cfg.keep_recon = true;
632+ cfg.picture_hash = true;
633+ let encoder = Encoder::new(cfg).expect("encoder");
634+ let frame = natural_frame(width, height, 0);
635+ let coded = encoder.encode_idr(&frame).expect("encode");
636+ (frame, coded)
637+}
638+
568 /// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower639 /// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower
569 /// tree; that trade is only worth taking if the bits it costs are noise.640 /// tree; that trade is only worth taking if the bits it costs are noise.
570 #[test]641 #[test]
crates/ec-h265/tests/encode.rsmodified+6 -0
@@ -451,6 +451,12 @@ 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_CTB") {
455+ cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64");
456+ }
457+ if let Ok(v) = std::env::var("EC_H265_CU64") {
458+ cfg.cu64 = v != "0";
459+ }
454 if let Ok(v) = std::env::var("EC_H265_RQT") {460 if let Ok(v) = std::env::var("EC_H265_RQT") {
455 cfg.rqt = v != "0";461 cfg.rqt = v != "0";
456 }462 }
lanes/h265-cu64-r1.report.mdadded+74 -0
@@ -0,0 +1,74 @@
1+# lane-h265-cu64 r1 — a 64x64 coding tree block may stay one coding unit
2+
3+Until now every 64x64 CTB was forced to split into four 32x32 coding units, so
4+the largest coding unit the encoder could emit was 32x32 whatever `ctb_size`
5+said. This lane lets a 64x64 CTB stay one coding unit.
6+
7+## What landed
8+
9+- `crates/ec-h265/src/ctu.rs`: `code_cu_64()`. HEVC's largest transform is
10+ 32x32 (`MaxTbLog2SizeY` is 5), so a 64x64 intra coding unit's transform tree
11+ splits *without* a `split_transform_flag` — the split is inferred from
12+ `log2TrafoSize > MaxTbLog2SizeY` (7.4.9.8) — and prediction runs per 32x32
13+ transform block in z-order, each quadrant marked coded before the next one
14+ reads its neighbours. The forced split in `code_quadtree` is now conditional
15+ on the new flag, and the child buffers widened to a 64x64 CU's four 32x32
16+ luma quadrants.
17+- `crates/ec-h265/src/encoder.rs`: `Config::cu64`, on by default. Only
18+ reachable with `ctb_size` 64, and the default `ctb_size` is 32.
19+- `crates/ec-h265/tests/encode.rs`: `EC_H265_CTB` and `EC_H265_CU64` knobs
20+ beside `EC_H265_RQT`, so the BD ladder can be run per arm.
21+
22+What a 64x64 CU buys is three split flags and three mode signallings; what it
23+costs is one luma direction for the whole 64x64.
24+
25+## Gates
26+
27+| Gate | Result |
28+| --- | --- |
29+| `cu64_decodes_bit_exactly` | ffmpeg decodes our stream bit-exactly at 352x288 q32, 256x256 q37 and 130x66 q32, and at the first two the stream differs from the `cu64=0` stream, so the feature really fires |
30+| full `ec-h265` suite | 25 + 15 + 1 + 3 passed, 0 failed |
31+| `cargo clippy --release -p ec-h265 --all-targets` | 0 warnings |
32+
33+At 130x66 the picture holds only two whole 64x64 tree blocks and the search
34+keeps neither, so that shape is kept for partial-CTB coverage with the
35+"it fired" assertion switched off rather than asserted against.
36+
37+## Mutation kills
38+
39+| Mutation | Killed by |
40+| --- | --- |
41+| a `split_transform_flag` written for the inferred split | `cu64_decodes_bit_exactly` (ffmpeg) |
42+| later quadrants predict from the CU origin instead of their own | `cu64_decodes_bit_exactly` |
43+
44+## What it is worth (BD-PSNR against x265, four-point ladder q22/26/30/34)
45+
46+| Clip | arm | BD-PSNR | BD-PSNR-YUV |
47+| --- | --- | --- | --- |
48+| ReelC 1080p film @600s | ctb 32 | +0.064 dB | -0.047 dB |
49+| | ctb 64, always split | +0.069 dB | -0.044 dB |
50+| | **ctb 64, cu64** | **+0.071 dB** | **-0.040 dB** |
51+| OBS screen capture 2026-08-25 16-27-54 @2s | ctb 32 | +0.224 dB | +0.086 dB |
52+| | ctb 64, always split | +0.254 dB | +0.114 dB |
53+| | **ctb 64, cu64** | **+0.352 dB** | **+0.219 dB** |
54+
55+Against always splitting a 64x64 tree block, cu64 is worth +0.002 dB on film
56+and +0.098 dB on screen capture; against the shipping `ctb_size` of 32 it is
57++0.007 dB and +0.128 dB. Both clips are his own.
58+
59+## Dispositions
60+
61+- `cu64` defaults on, `ctb_size` stays 32: **accepted** for this lane. cu64
62+ cannot fire at 32, so the default is a no-op until the tree size changes.
63+- `ctb_size` 64 now beats 32 on both clips (+0.007 dB film, +0.128 dB screen)
64+ but `ctb_32_is_the_faster_tree_at_1080p` guards the speed side:
65+ **deferred(a re-measured speed/quality trade at 1080p with cu64 on, which is
66+ its own lane)**.
67+- Screen capture is still where our x265 gap lives; this is the second lane in
68+ a row that moves that clip more than the film one.
69+
70+## Not in this lane
71+
72+- Asymmetric or non-square partitions of a 64x64 coding unit.
73+- `part_mode` NxN at 64x64 (the spec does not offer it there).
74+- Inter prediction, which is where a large coding unit pays the most.