From fea923bb4eb164c91fa558944f07d5e83ee8b352 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 25 Aug 2026 04:15:39 +0300 Subject: [PATCH] feat(h265): chroma prediction mode search, measured and left off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chroma was always coded in the derived mode: `intra_chroma_pred_mode` was a hardcoded 0 bin. The syntax offers five modes — planar, vertical, horizontal and DC, each swapped for angular 34 when it collides with the luma mode, plus derived — and nothing had ever measured what the other four are worth. `choose_chroma_mode` now codes all five into a counting CABAC snapshot, both planes and their residuals, and keeps the lowest `SSD + lambda * bits`. It is off by default, because measured against x265 on four real clips it is a wash (BD-PSNR luma / all-plane, derived -> search): | clip | derived | search | |------|---------|--------| | 4K film | -0.685 / -0.703 | -0.757 / -0.606 | | 1138x640 web | -0.507 / -0.556 | -0.584 / -0.505 | | 1440p screen capture | -2.465 / -2.360 | -2.617 / -2.460 | | 1080p phone | -0.366 / -0.387 | -0.477 / -0.384 | Luma falls on every clip — the extra chroma bits come out of the same budget at a fixed QP — while all-plane gains 0.10 dB and 0.05 dB on the two camera clips, is flat on the third and loses 0.10 dB on the screen capture, for 10-15% more encode time. Average +0.01 dB all-plane is not a default. The lambda is not the cause: `chroma_rd_weight` swept at 0.25/0.5/1.0/2.0 leaves the screen capture losing at every weight, and 1.0 is the best weight wherever the search wins at all. Correctness is gated on its own: `chroma_mode_search_decodes_bit_exactly` asserts the stream differs from the derived-only one (so the explicit modes really fired) and that ffmpeg decodes it sample-for-sample. EC_H265_CHROMA_RD and EC_H265_CHROMA_W in the BD gate re-run both sweeps. --- crates/ec-h265/src/ctu.rs | 117 +++++++++++++++++++++++++--- crates/ec-h265/src/encoder.rs | 31 ++++++++ crates/ec-h265/tests/conformance.rs | 44 +++++++++++ crates/ec-h265/tests/encode.rs | 6 ++ 4 files changed, 188 insertions(+), 10 deletions(-) diff --git a/crates/ec-h265/src/ctu.rs b/crates/ec-h265/src/ctu.rs index 14a51d33..75235bd2 100644 --- a/crates/ec-h265/src/ctu.rs +++ b/crates/ec-h265/src/ctu.rs @@ -144,6 +144,10 @@ pub struct CtuEncoder<'a> { strong_smoothing: bool, /// How many of the 35 modes get a full rate-distortion trial. candidates: usize, + /// Whether the chroma mode is chosen by rate-distortion or always derived. + chroma_rd: bool, + /// Weight on chroma SSD in that decision, against luma's lambda. + chroma_rd_weight: f64, /// `log2` of the smallest coding unit the search will produce. min_cb_log2: u32, /// Intra mode per 4x4 block of the band; 255 = not coded yet. @@ -172,6 +176,8 @@ impl<'a> CtuEncoder<'a> { qp: i32, strong_smoothing: bool, candidates: usize, + chroma_rd: bool, + chroma_rd_weight: f64, min_cb_log2: u32, ) -> CtuEncoder<'a> { let band_rows = (height - band_y0).min(ctb_size); @@ -189,6 +195,8 @@ impl<'a> CtuEncoder<'a> { lambda_satd: lambda_for(qp).sqrt(), strong_smoothing, candidates: candidates.clamp(1, 35), + chroma_rd, + chroma_rd_weight, min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), modes: vec![255; (width / 4) * (ctb_size / 4)], depths: vec![0; (width / 4) * (ctb_size / 4)], @@ -485,13 +493,17 @@ impl<'a> CtuEncoder<'a> { let mpm = self.mpm_at(x, y); let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc); self.write_mode_syntax(enc, mode, &mpm); - // intra_chroma_pred_mode = 4 (derived from luma): the single bin 0. - enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0); + let (chroma_mode, chroma_idx) = if self.chroma_rd { + self.choose_chroma_mode(x, y, n, log2, mode, enc) + } else { + (mode, None) + }; + self.write_chroma_mode_syntax(enc, chroma_idx); // Luma was reconstructed by the mode search; chroma is coded now. let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0); - let cb_cbf = self.code_chroma(x, y, n, mode, 1); - let cr_cbf = self.code_chroma(x, y, n, mode, 2); + let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1).1; + let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2).1; enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); @@ -502,7 +514,7 @@ impl<'a> CtuEncoder<'a> { encode_residual(enc, &levels[..n * n], log2, 0, scan); self.scratch.luma_levels = levels; } - let chroma_scan = intra::scan_index(mode, log2 - 1, false); + let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false); if cb_cbf { let levels = std::mem::take(&mut self.scratch.cb_levels); encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan); @@ -743,9 +755,16 @@ impl<'a> CtuEncoder<'a> { (ssd as f64, cbf) } - /// Code one chroma transform block in derived mode; returns its `cbf` and - /// leaves the levels in the matching scratch buffer. - fn code_chroma(&mut self, x: usize, y: usize, n: usize, luma_mode: u8, plane: usize) -> bool { + /// Code one chroma transform block in `pred_mode`; returns its `(SSD, cbf)` + /// and leaves the levels in the matching scratch buffer. + fn code_chroma( + &mut self, + x: usize, + y: usize, + n: usize, + pred_mode: u8, + plane: usize, + ) -> (f64, bool) { let cn = n / 2; let (cx, cy) = (x / 2, y / 2); let refs = self.chroma_refs(cx, cy, cn, plane); @@ -753,7 +772,7 @@ impl<'a> CtuEncoder<'a> { let src = if plane == 1 { self.src.cb } else { self.src.cr }; intra::predict( &refs, - luma_mode, + pred_mode, cn, false, self.strong_smoothing, @@ -785,11 +804,14 @@ impl<'a> CtuEncoder<'a> { } else { self.scratch.residual[..cn * cn].fill(0); } + let mut ssd = 0i64; for row in 0..cn { for col in 0..cn { let value = (i32::from(self.scratch.pred[row * cn + col]) + self.scratch.residual[row * cn + col]) .clamp(0, 255) as u8; + let d = i64::from(src[(cy + row) * cw + cx + col]) - i64::from(value); + ssd += d * d; self.write_rec_c(cx + col, cy + row, plane, value); } } @@ -799,7 +821,82 @@ impl<'a> CtuEncoder<'a> { &mut self.scratch.cr_levels }; levels[..cn * cn].copy_from_slice(&self.scratch.levels[..cn * cn]); - cbf + (ssd as f64, cbf) + } + + // ---- chroma mode decision -------------------------------------------- + + /// Write `intra_chroma_pred_mode`: the single bin 0 for the derived mode, + /// or bin 1 and two bypass bits picking one of the four explicit modes. + fn write_chroma_mode_syntax(&self, enc: &mut CabacEncoder, idx: Option) { + match idx { + None => enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0), + Some(i) => { + enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 1); + enc.encode_bypass_bits(i, 2); + } + } + } + + /// Pick the chroma prediction mode by rate-distortion over the five the + /// syntax allows: planar, vertical, horizontal and DC — each replaced by + /// angular 34 when it collides with the luma mode — plus the derived mode, + /// which is the luma mode itself and costs one bin instead of three. + /// + /// Returns the mode and the index to code, `None` meaning derived. Neither + /// the winner's reconstruction nor its levels survive the trial: the caller + /// codes the winner again for real. + fn choose_chroma_mode( + &mut self, + x: usize, + y: usize, + n: usize, + log2: u32, + luma_mode: u8, + enc: &mut CabacEncoder, + ) -> (u8, Option) { + let mut explicit = [0u8, 26, 10, 1]; + for mode in explicit.iter_mut() { + if *mode == luma_mode { + *mode = 34; + } + } + let start = enc.snapshot(); + enc.set_counting(true); + let mut best = (f64::MAX, luma_mode, None); + for (i, mode) in explicit + .iter() + .copied() + .enumerate() + .map(|(i, m)| (Some(i as u32), m)) + .chain(std::iter::once((None, luma_mode))) + { + let bits_before = enc.bit_count(); + self.write_chroma_mode_syntax(enc, i); + let (cb_ssd, cb_cbf) = self.code_chroma(x, y, n, mode, 1); + let (cr_ssd, cr_cbf) = self.code_chroma(x, y, n, mode, 2); + enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); + enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); + let scan = intra::scan_index(mode, log2 - 1, false); + if cb_cbf { + let levels = std::mem::take(&mut self.scratch.cb_levels); + encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, scan); + self.scratch.cb_levels = levels; + } + if cr_cbf { + let levels = std::mem::take(&mut self.scratch.cr_levels); + encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, scan); + self.scratch.cr_levels = levels; + } + let bits = enc.bit_count() - bits_before; + enc.restore(&start); + let cost = self.chroma_rd_weight * (cb_ssd + cr_ssd) + self.lambda * bits as f64; + if cost < best.0 { + best = (cost, mode, i); + } + } + enc.set_counting(false); + (best.1, best.2) } // ---- reference samples ----------------------------------------------- diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index f15fb466..a8ade7b9 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -94,6 +94,33 @@ pub struct EncoderConfig { /// knee is where the default sits. `EC_H265_RDO_CANDIDATES` in the gate /// test re-runs the sweep. pub rdo_candidates: usize, + /// Whether the chroma prediction mode is chosen by rate-distortion over the + /// five modes the syntax allows, instead of always taking the derived mode. + /// + /// Off by default: measured against x265 on four real clips it is a wash, + /// and on screen capture it is a loss (BD-PSNR luma / all-plane, derived + /// mode -> search, `chroma_rd_weight: 1.0`): + /// + /// | clip | derived | search | + /// |------|---------|--------| + /// | 4K film | -0.685 / -0.703 | -0.757 / **-0.606** | + /// | 1138x640 web | -0.507 / -0.556 | -0.584 / **-0.505** | + /// | 1440p screen capture | **-2.465 / -2.360** | -2.617 / -2.460 | + /// | 1080p phone | -0.366 / **-0.387** | -0.477 / -0.384 | + /// + /// Luma falls on every clip because the extra chroma bits come out of the + /// same budget at a fixed QP; all-plane gains 0.10 dB and 0.05 dB on the two + /// camera clips, is flat on the third and loses 0.10 dB on the screen + /// capture, for 10-15% more encode time. The average is +0.01 dB all-plane, + /// which is not a default. [`EncoderConfig::chroma_rd_weight`] was swept at + /// 0.25/0.5/1.0/2.0 and did not change the shape of that table: the screen + /// capture loses at every weight, so the cause is not the lambda. + pub chroma_mode_search: bool, + /// Weight on chroma SSD in that decision, against the luma lambda. Swept + /// at 0.25/0.5/1.0/2.0 on three clips; 1.0 is the best of them everywhere + /// the search wins at all (4K film all-plane: -0.606 at 1.0 against -0.649 + /// at 0.25, -0.619 at 0.5, -0.657 at 2.0). + pub chroma_rd_weight: f64, /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a /// *coarser* search that is not always faster: on real pictures the 8x8 /// blocks pay for their search in residual bits (measured: -27% bits and @@ -125,6 +152,8 @@ impl EncoderConfig { threads: 0, ctb_size: 32, rdo_candidates: 5, + chroma_mode_search: false, + chroma_rd_weight: 1.0, min_cu_size: 8, video_signal_type: None, sample_aspect_ratio: None, @@ -498,6 +527,8 @@ impl Encoder { slice_qp, true, self.cfg.rdo_candidates, + self.cfg.chroma_mode_search, + self.cfg.chroma_rd_weight, 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 d64f3310..40d03dd3 100644 --- a/crates/ec-h265/tests/conformance.rs +++ b/crates/ec-h265/tests/conformance.rs @@ -90,7 +90,18 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { /// Encode one picture; `ctb` of `None` takes the configured default. fn encode(width: u32, height: u32, qp: i32, ctb: Option) -> (VideoFrame, EncodedPicture) { + encode_with(width, height, qp, ctb, false) +} + +fn encode_with( + width: u32, + height: u32, + qp: i32, + ctb: Option, + chroma_mode_search: bool, +) -> (VideoFrame, EncodedPicture) { let mut cfg = EncoderConfig::new(width, height); + cfg.chroma_mode_search = chroma_mode_search; cfg.rate_control = RateControl::ConstantQp(qp); if let Some(ctb) = ctb { cfg.ctb_size = ctb; @@ -103,6 +114,39 @@ fn encode(width: u32, height: u32, qp: i32, ctb: Option) -> (VideoFrame, (frame, coded) } +/// The chroma mode search is off by default (it loses on screen content, see +/// `EncoderConfig::chroma_mode_search`), so the shapes above never code an +/// `intra_chroma_pred_mode` other than the derived one. This exercises the four +/// explicit modes: the stream has to differ from the derived-only one — proving +/// the search actually fired — and still decode bit-exactly. +#[test] +fn chroma_mode_search_decodes_bit_exactly() { + if !have_ffmpeg() { + eprintln!("skipping: ffmpeg not installed"); + return; + } + for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { + let (source, coded) = encode_with(w, h, 27, None, true); + let (_, derived) = encode_with(w, h, 27, None, false); + let name = format!("chroma-rd-{w}x{h}"); + assert_ne!( + coded.au, derived.au, + "{name}: the search never picked a mode other than the derived one, so this decode proves nothing" + ); + let path = write_au(&name, &coded); + let decoded = match ffmpeg_decode(&path) { + Ok(bytes) => bytes, + Err(e) => panic!("{name}: ffmpeg failed: {e}"), + }; + let recon = planes_of(coded.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(); + assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + let quality = psnr(&planes_of(&source), &recon); + assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); + } +} + #[test] fn ffmpeg_decodes_bit_exactly_at_every_shape() { if !have_ffmpeg() { diff --git a/crates/ec-h265/tests/encode.rs b/crates/ec-h265/tests/encode.rs index 5c7b0707..95fa4b7a 100644 --- a/crates/ec-h265/tests/encode.rs +++ b/crates/ec-h265/tests/encode.rs @@ -429,6 +429,12 @@ fn bd_psnr_vs_x265() { cfg.threads = 0; // Ablation knob: how many SATD survivors reach the full rate-distortion // trial in the luma mode search. The shipped default is 5. + if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") { + cfg.chroma_mode_search = v != "0"; + } + if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { + cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); + } if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); }