From 826a8f8a1449839778589a3fa3fc02e6c775c8b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 02:54:34 +0300 Subject: [PATCH] feat(h265): a 64x64 coding tree block may stay one coding unit HEVC's largest transform is 32x32, so a 64x64 intra coding unit splits its transform tree without a split_transform_flag -- the split is inferred from log2TrafoSize > MaxTbLog2SizeY -- and predicts per 32x32 transform block in z-order, each quadrant marked coded before the next reads its neighbours. What the coding unit buys is three split flags and three mode signallings, against one luma direction for the whole 64x64. On by default; only reachable with ctb_size 64, which is not the default. Against always splitting a 64x64 tree block it is worth +0.002 dB BD-PSNR on a film frame and +0.098 dB on a screen capture. --- crates/ec-h265/src/ctu.rs | 130 ++++++++++++++++++++++++++-- crates/ec-h265/src/encoder.rs | 15 ++++ crates/ec-h265/tests/conformance.rs | 71 +++++++++++++++ crates/ec-h265/tests/encode.rs | 6 ++ lanes/h265-cu64-r1.report.md | 74 ++++++++++++++++ 5 files changed, 289 insertions(+), 7 deletions(-) create mode 100644 lanes/h265-cu64-r1.report.md diff --git a/crates/ec-h265/src/ctu.rs b/crates/ec-h265/src/ctu.rs index a52a43fe..9edb58ed 100644 --- a/crates/ec-h265/src/ctu.rs +++ b/crates/ec-h265/src/ctu.rs @@ -173,6 +173,9 @@ pub struct CtuEncoder<'a> { rdoq: bool, transform_skip: bool, rqt: bool, + /// Whether a 64x64 coding tree block may stay one coding unit rather than + /// always splitting to 32x32. + cu64: bool, /// The counting CABAC engine that search prices its trials with. rdoq_enc: CabacEncoder, /// `log2` of the smallest coding unit the search will produce. @@ -210,6 +213,7 @@ impl<'a> CtuEncoder<'a> { rdoq: bool, transform_skip: bool, rqt: bool, + cu64: bool, min_cb_log2: u32, ) -> CtuEncoder<'a> { let band_rows = (height - band_y0).min(ctb_size); @@ -234,6 +238,7 @@ impl<'a> CtuEncoder<'a> { rdoq, transform_skip, rqt, + cu64, rdoq_enc: CabacEncoder::counter(Contexts::new(qp)), min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), modes: vec![255; (width / 4) * (ctb_size / 4)], @@ -387,7 +392,7 @@ impl<'a> CtuEncoder<'a> { return self.lambda * (enc.bit_count() - before) as f64 + self.code_cu(x, y, log2, depth, enc); } - if log2 > 5 { + if log2 > 5 && !self.cu64 { // 64x64 coding units are not searched; the decision starts at 32x32. let before = enc.bit_count(); enc.encode_bin(split_ctx, 1); @@ -656,6 +661,114 @@ impl<'a> CtuEncoder<'a> { self.region_ssd(x, y, 8) + self.lambda * bits as f64 } + /// Code one 64x64 coding unit. + /// + /// HEVC's largest transform block is 32x32, so the transform tree of a + /// 64x64 coding unit is split without a `split_transform_flag` -- the + /// decoder infers the split from `log2TrafoSize > MaxTbLog2SizeY` (7.4.9.8) + /// -- and intra prediction runs per transform block, four 32x32 ones in + /// z-order, each predicting from the reconstruction of the ones before it. + /// The coding unit carries a single luma mode and a single chroma mode, so + /// what it saves over four 32x32 coding units is three split flags and + /// three mode signallings; what it gives up is three quarters of the + /// freedom to pick a direction. + /// + /// The mode search runs on the first quadrant: that is the only one whose + /// neighbours are settled before a mode is chosen, and it is what the + /// reference encoder does for the same reason. + fn code_cu_64(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 { + const N: usize = 64; + const HALF: usize = 32; + const LOG2: u32 = 6; + let chroma_tskip = self.transform_skip; + let before = enc.bit_count(); + + let mpm = self.mpm_at(x, y); + // Reconstructs the first quadrant under the mode it picks, leaving its + // levels in the luma scratch. + let mode = self.choose_luma_mode(x, y, HALF, LOG2 - 1, &mpm, enc); + self.write_mode_syntax(enc, mode, &mpm); + let (chroma_mode, chroma_idx) = if self.chroma_rd { + self.choose_chroma_mode(x, y, HALF, LOG2 - 1, mode, chroma_tskip, enc) + } else { + (mode, None) + }; + self.write_chroma_mode_syntax(enc, chroma_idx); + + let mut child_levels = [[0i32; 1024]; 4]; + let mut child_cbf = [false; 4]; + let mut child_cb = [[0i32; 256]; 4]; + let mut child_cr = [[0i32; 256]; 4]; + let mut child_cb_cbf = [false; 4]; + let mut child_cr_cbf = [false; 4]; + let offsets = [(0usize, 0usize), (HALF, 0), (0, HALF), (HALF, HALF)]; + let q = HALF * HALF / 4; + for (part, &(dx, dy)) in offsets.iter().enumerate() { + let (cx, cy) = (x + dx, y + dy); + if part == 0 { + // Already coded by the mode search. + child_levels[0][..HALF * HALF] + .copy_from_slice(&self.scratch.luma_levels[..HALF * HALF]); + child_cbf[0] = child_levels[0][..HALF * HALF].iter().any(|&v| v != 0); + } else { + let refs = self.luma_refs(cx, cy, HALF); + let mut source = std::mem::take(&mut self.scratch.source); + for row in 0..HALF { + source[row * HALF..row * HALF + HALF].copy_from_slice( + &self.src.y + [(cy + row) * self.width + cx..(cy + row) * self.width + cx + HALF], + ); + } + let (_, cbf) = self.transform_luma(HALF, mode, &source, &refs); + self.scratch.source = source; + child_levels[part][..HALF * HALF] + .copy_from_slice(&self.scratch.levels[..HALF * HALF]); + child_cbf[part] = cbf; + for row in 0..HALF { + for col in 0..HALF { + self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * HALF + col]); + } + } + } + // The next quadrant predicts from this one, so its samples have to + // read as available now: the decoder walks the tree in z-order too. + self.mark_coded(cx, cy, HALF, mode, depth); + let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 1, chroma_tskip); + child_cb_cbf[part] = cbf; + child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]); + let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 2, chroma_tskip); + child_cr_cbf[part] = cbf; + child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]); + } + + // The parent's flag is the OR of the children's: a clear one at depth 0 + // tells the decoder to infer every child's as clear. + let cb_cbf = child_cb_cbf.iter().any(|&c| c); + let cr_cbf = child_cr_cbf.iter().any(|&c| c); + self.write_split_tu( + enc, + N, + LOG2, + mode, + chroma_mode, + chroma_tskip, + true, + cb_cbf, + cr_cbf, + &child_cbf, + &child_levels, + &child_cb_cbf, + &child_cr_cbf, + &child_cb, + &child_cr, + &[], + &[], + ); + self.last_cu_empty = !(child_cbf.iter().any(|&c| c) || cb_cbf || cr_cbf); + let bits = enc.bit_count() - before; + self.region_ssd(x, y, N) + self.lambda * bits as f64 + } + fn code_cu_2nx2n( &mut self, x: usize, @@ -664,6 +777,9 @@ impl<'a> CtuEncoder<'a> { depth: u8, enc: &mut CabacEncoder, ) -> f64 { + if log2 > 5 { + return self.code_cu_64(x, y, depth, enc); + } let n = 1usize << log2; // Transform skip is a per-block flag the decoder reads for every 4x4 // residual once the picture parameter set enables it, so the decision @@ -723,10 +839,10 @@ impl<'a> CtuEncoder<'a> { let half = n / 2; let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)]; - let mut child_levels = [[0i32; 256]; 4]; + let mut child_levels = [[0i32; 1024]; 4]; let mut child_cbf = [false; 4]; - let mut child_cb = [[0i32; 64]; 4]; - let mut child_cr = [[0i32; 64]; 4]; + let mut child_cb = [[0i32; 256]; 4]; + let mut child_cr = [[0i32; 256]; 4]; let mut child_cb_cbf = [false; 4]; let mut child_cr_cbf = [false; 4]; for (part, &(dx, dy)) in offsets.iter().enumerate() { @@ -956,11 +1072,11 @@ impl<'a> CtuEncoder<'a> { cb_cbf: bool, cr_cbf: bool, child_cbf: &[bool; 4], - child_levels: &[[i32; 256]; 4], + child_levels: &[[i32; 1024]; 4], child_cb_cbf: &[bool; 4], child_cr_cbf: &[bool; 4], - child_cb: &[[i32; 64]; 4], - child_cr: &[[i32; 64]; 4], + child_cb: &[[i32; 256]; 4], + child_cr: &[[i32; 256]; 4], parent_cb: &[i32], parent_cr: &[i32], ) { diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index c5594011..6dc3e32d 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -175,6 +175,19 @@ pub struct EncoderConfig { /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`). pub rqt: bool, + /// Whether a 64x64 coding tree block may stay one coding unit instead of + /// always splitting to 32x32. Only reachable with `ctb_size` 64. + /// + /// A 64x64 intra coding unit still predicts and transforms in four 32x32 + /// blocks -- 32x32 is HEVC's largest transform -- so what it buys is three + /// split flags and three mode signallings, and what it costs is one luma + /// direction for the whole 64x64. Measured in `lanes/h265-cu64-r1.report.md`. + /// + /// On by default: against x265 over the four-point ladder it is worth + /// +0.007 dB BD-PSNR on film and +0.098 dB on screen capture over always + /// splitting a 64x64 tree block, and the default `ctb_size` of 32 leaves + /// it unreachable anyway. + pub cu64: bool, /// What the samples mean, written into the VUI. pub video_signal_type: Option, /// Sample aspect ratio. @@ -208,6 +221,7 @@ impl EncoderConfig { rdoq: true, transform_skip: TransformSkip::Off, rqt: true, + cu64: true, video_signal_type: None, sample_aspect_ratio: None, timing: None, @@ -589,6 +603,7 @@ impl Encoder { self.cfg.rdoq, self.cfg.transform_skip != TransformSkip::Off, self.cfg.rqt, + self.cfg.cu64, self.cfg.min_cu_size.max(8).trailing_zeros(), ); for col in 0..cols { diff --git a/crates/ec-h265/tests/conformance.rs b/crates/ec-h265/tests/conformance.rs index 855aad6c..e6e192b4 100644 --- a/crates/ec-h265/tests/conformance.rs +++ b/crates/ec-h265/tests/conformance.rs @@ -565,6 +565,77 @@ fn ffmpeg_decodes_bit_exactly_at_every_shape() { } } +/// A 64x64 coding unit predicts and transforms in four 32x32 blocks under one +/// luma mode, with the transform split inferred rather than signalled +/// (`log2TrafoSize > MaxTbLog2SizeY`, 7.4.9.8). That inference is the part a +/// decoder disagrees with loudly, so it is gated against ffmpeg -- and the +/// stream has to differ from the same encode with `cu64` off, or the test would +/// pass without a single 64x64 coding unit ever being kept. +#[test] +fn cu64_decodes_bit_exactly() { + if !have_ffmpeg() { + eprintln!("skipping: ffmpeg not installed"); + return; + } + // 130x66 is here for the partial coding tree blocks, not for the decision: + // at that size only two tree blocks are whole and the search keeps neither, + // so its stream is allowed to come out identical. + for &(w, h, qp, fires) in &[ + (352u32, 288u32, 32i32, true), + (256, 256, 37, true), + (130, 66, 32, false), + ] { + let (source, off) = encode_cu64(w, h, qp, false); + let (_, on) = encode_cu64(w, h, qp, true); + let name = format!("cu64-{w}x{h}-qp{qp}"); + if fires { + assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept"); + } + + let path = write_au(&name, &on); + let decoded = match ffmpeg_decode(&path) { + Ok(bytes) => bytes, + Err(e) => panic!("{name}: ffmpeg failed: {e}"), + }; + let recon = planes_of(on.recon.as_ref().expect("recon kept")); + assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); + let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); + if mismatches != 0 { + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let luma = (w * h) as usize; + panic!( + "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma", + first % w as usize, + first / w as usize, + decoded[..luma] + .iter() + .zip(&recon[..luma]) + .filter(|(a, b)| a != b) + .count(), + ); + } + let quality = psnr(&planes_of(&source), &recon); + assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}"); + } +} + +fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) { + let mut cfg = EncoderConfig::new(width, height); + cfg.ctb_size = 64; + cfg.cu64 = cu64; + cfg.rate_control = RateControl::ConstantQp(qp); + cfg.keep_recon = true; + cfg.picture_hash = true; + let encoder = Encoder::new(cfg).expect("encoder"); + let frame = natural_frame(width, height, 0); + let coded = encoder.encode_idr(&frame).expect("encode"); + (frame, coded) +} + /// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower /// tree; that trade is only worth taking if the bits it costs are noise. #[test] diff --git a/crates/ec-h265/tests/encode.rs b/crates/ec-h265/tests/encode.rs index 96469d5f..71876971 100644 --- a/crates/ec-h265/tests/encode.rs +++ b/crates/ec-h265/tests/encode.rs @@ -451,6 +451,12 @@ fn bd_psnr_vs_x265() { if let Ok(v) = std::env::var("EC_H265_NXN") { cfg.intra_nxn = v != "0"; } + if let Ok(v) = std::env::var("EC_H265_CTB") { + cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64"); + } + if let Ok(v) = std::env::var("EC_H265_CU64") { + cfg.cu64 = v != "0"; + } if let Ok(v) = std::env::var("EC_H265_RQT") { cfg.rqt = v != "0"; } diff --git a/lanes/h265-cu64-r1.report.md b/lanes/h265-cu64-r1.report.md new file mode 100644 index 00000000..958074e2 --- /dev/null +++ b/lanes/h265-cu64-r1.report.md @@ -0,0 +1,74 @@ +# lane-h265-cu64 r1 — a 64x64 coding tree block may stay one coding unit + +Until now every 64x64 CTB was forced to split into four 32x32 coding units, so +the largest coding unit the encoder could emit was 32x32 whatever `ctb_size` +said. This lane lets a 64x64 CTB stay one coding unit. + +## What landed + +- `crates/ec-h265/src/ctu.rs`: `code_cu_64()`. HEVC's largest transform is + 32x32 (`MaxTbLog2SizeY` is 5), so a 64x64 intra coding unit's transform tree + splits *without* a `split_transform_flag` — the split is inferred from + `log2TrafoSize > MaxTbLog2SizeY` (7.4.9.8) — and prediction runs per 32x32 + transform block in z-order, each quadrant marked coded before the next one + reads its neighbours. The forced split in `code_quadtree` is now conditional + on the new flag, and the child buffers widened to a 64x64 CU's four 32x32 + luma quadrants. +- `crates/ec-h265/src/encoder.rs`: `Config::cu64`, on by default. Only + reachable with `ctb_size` 64, and the default `ctb_size` is 32. +- `crates/ec-h265/tests/encode.rs`: `EC_H265_CTB` and `EC_H265_CU64` knobs + beside `EC_H265_RQT`, so the BD ladder can be run per arm. + +What a 64x64 CU buys is three split flags and three mode signallings; what it +costs is one luma direction for the whole 64x64. + +## Gates + +| Gate | Result | +| --- | --- | +| `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 | +| full `ec-h265` suite | 25 + 15 + 1 + 3 passed, 0 failed | +| `cargo clippy --release -p ec-h265 --all-targets` | 0 warnings | + +At 130x66 the picture holds only two whole 64x64 tree blocks and the search +keeps neither, so that shape is kept for partial-CTB coverage with the +"it fired" assertion switched off rather than asserted against. + +## Mutation kills + +| Mutation | Killed by | +| --- | --- | +| a `split_transform_flag` written for the inferred split | `cu64_decodes_bit_exactly` (ffmpeg) | +| later quadrants predict from the CU origin instead of their own | `cu64_decodes_bit_exactly` | + +## What it is worth (BD-PSNR against x265, four-point ladder q22/26/30/34) + +| Clip | arm | BD-PSNR | BD-PSNR-YUV | +| --- | --- | --- | --- | +| ReelC 1080p film @600s | ctb 32 | +0.064 dB | -0.047 dB | +| | ctb 64, always split | +0.069 dB | -0.044 dB | +| | **ctb 64, cu64** | **+0.071 dB** | **-0.040 dB** | +| OBS screen capture 2026-08-25 16-27-54 @2s | ctb 32 | +0.224 dB | +0.086 dB | +| | ctb 64, always split | +0.254 dB | +0.114 dB | +| | **ctb 64, cu64** | **+0.352 dB** | **+0.219 dB** | + +Against always splitting a 64x64 tree block, cu64 is worth +0.002 dB on film +and +0.098 dB on screen capture; against the shipping `ctb_size` of 32 it is ++0.007 dB and +0.128 dB. Both clips are his own. + +## Dispositions + +- `cu64` defaults on, `ctb_size` stays 32: **accepted** for this lane. cu64 + cannot fire at 32, so the default is a no-op until the tree size changes. +- `ctb_size` 64 now beats 32 on both clips (+0.007 dB film, +0.128 dB screen) + but `ctb_32_is_the_faster_tree_at_1080p` guards the speed side: + **deferred(a re-measured speed/quality trade at 1080p with cu64 on, which is + its own lane)**. +- Screen capture is still where our x265 gap lives; this is the second lane in + a row that moves that clip more than the film one. + +## Not in this lane + +- Asymmetric or non-square partitions of a 64x64 coding unit. +- `part_mode` NxN at 64x64 (the spec does not offer it there). +- Inter prediction, which is where a large coding unit pays the most.