From eb83b6ffbded7c502c9b8dcc37a59cdcc965074e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 24 Aug 2026 07:21:45 +0300 Subject: [PATCH] perf(h264): choose chroma_qp_index_offset from the source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The offset was a hardcoded 0 in the PPS. Sweeping it showed the optimum is not a constant: a film clip is best at 0 and loses 0.16 dB at -2, while every screen capture and phone clip gains, one of them by 0.23 dB. What separates them is how textured the chroma planes are relative to luma — flat chroma is what wants the extra chroma bits, because its few edges are all the eye has to read there, and film's chroma carries as much detail as its luma, where the same bits buy more. So measure it: mean absolute sample gradient of the chroma planes over that of luma, taken on the first source picture, and code at -2 below half. The offset now reaches the PPS, the encoder's own chroma QP derivation and the deblocking parameters of every slice it writes, so reconstruction still matches a decode exactly. BD-PSNR-YUV against x264 (GOP 10, QP 22/26/30/34, Preset::Balanced) over nine clips, before -> after: -0.504 -> -0.504 (film, keeps 0), -0.406 -> -0.227, -0.495 -> -0.268, -0.601 -> -0.570, -0.639 -> -0.575, -0.931 -> -0.886, -0.510 -> -0.491, -0.352 -> -0.340, -0.376 -> -0.300. The rule reproduces each clip's own swept optimum. --- crates/ec-h264/src/enc/headers.rs | 13 ++- crates/ec-h264/src/enc/mb.rs | 11 ++- crates/ec-h264/src/enc/mod.rs | 156 ++++++++++++++++++++++++++++-- 3 files changed, 162 insertions(+), 18 deletions(-) diff --git a/crates/ec-h264/src/enc/headers.rs b/crates/ec-h264/src/enc/headers.rs index 9fe3784c..5f0a2afb 100644 --- a/crates/ec-h264/src/enc/headers.rs +++ b/crates/ec-h264/src/enc/headers.rs @@ -131,7 +131,7 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec { } /// Write the picture parameter set RBSP (7.3.2.2). -pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec { +pub(crate) fn write_pps(cabac: bool, transform_8x8: bool, cqo: i32) -> Vec { let mut w = BitWriter::with_capacity(8); w.write_ue(0); // pic_parameter_set_id w.write_ue(0); // seq_parameter_set_id @@ -144,14 +144,14 @@ pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec { w.write_bits(0, 2); // weighted_bipred_idc w.write_se(0); // pic_init_qp_minus26 w.write_se(0); // pic_init_qs_minus26 - w.write_se(0); // chroma_qp_index_offset + w.write_se(cqo); // chroma_qp_index_offset w.write_bit(false); // deblocking_filter_control_present_flag w.write_bit(false); // constrained_intra_pred_flag w.write_bit(false); // redundant_pic_cnt_present_flag if transform_8x8 { w.write_bit(true); // transform_8x8_mode_flag w.write_bit(false); // pic_scaling_matrix_present_flag - w.write_se(0); // second_chroma_qp_index_offset + w.write_se(cqo); // second_chroma_qp_index_offset } trailing(&mut w); w.into_bytes() @@ -264,10 +264,13 @@ mod tests { assert_eq!(sps.chroma_format_idc, 1); assert_eq!(sps.bit_depth_luma, 8); } - let pps = Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses"); + let pps = Pps::parse(&write_pps(cabac, t8x8, -2), |_| Some(&sps)).expect("PPS parses"); assert_eq!(pps.entropy_coding_mode, cabac); assert_eq!(pps.pic_init_qp, 26); assert_eq!(pps.transform_8x8_mode, t8x8); + assert_eq!(pps.chroma_qp_index_offset, -2); + // Absent, it is inferred equal to chroma_qp_index_offset (7.4.2.2). + assert_eq!(pps.second_chroma_qp_index_offset, -2); } } @@ -286,7 +289,7 @@ mod tests { fn slice_header_parses_back() { let p = params(320, 240); let sps = Sps::parse(&write_sps(&p)).unwrap(); - let pps = Pps::parse(&write_pps(true, false), |_| Some(&sps)).unwrap(); + let pps = Pps::parse(&write_pps(true, false, 0), |_| Some(&sps)).unwrap(); for (idr, slice_type, first_mb, qp) in [ (true, SliceType::I, 0u32, 30i32), (false, SliceType::P, 40, 18), diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 1e13afd8..a69ab616 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -102,6 +102,9 @@ pub(crate) struct MbEnc<'a> { pub ls8: LevelScale8x8, /// Neighbourhood of the macroblock being written (CABAC). pub mb_ctx: MbCtx, + /// The picture's `chroma_qp_index_offset`, chosen from the source in + /// `Encoder::chroma_qp_offset_for_source`. + pub cqo: i32, /// ctxIdxInc for this macroblock's mb_skip_flag. pub skip_inc: usize, /// `qp_delta_inc` of 9.3.3.1.1.5: whether the previous macroblock in this @@ -285,10 +288,10 @@ pub(crate) fn se_bits(v: i32) -> i32 { (32 - (k + 1).leading_zeros()) as i32 * 2 - 1 } -/// Chroma QP of a luma QP under a zero `chroma_qp_index_offset`. +/// Chroma QP of a luma QP under the picture's `chroma_qp_index_offset`. #[inline] -fn chroma_qp(qp: i32) -> i32 { - i32::from(CHROMA_QP[qp.clamp(0, 51) as usize]) +fn chroma_qp(qp: i32, cqo: i32) -> i32 { + i32::from(CHROMA_QP[(qp + cqo).clamp(0, 51) as usize]) } /// Which intra 4x4 modes the available neighbours allow (8.3.1.2). @@ -1614,7 +1617,7 @@ fn code_chroma( intra: bool, lv: &mut Levels, ) { - let qp_c = chroma_qp(qp_y); + let qp_c = chroma_qp(qp_y, e.cqo); let mut dc_lists = [[0i32; 4]; 2]; let mut ac = [[[0i32; 16]; 4]; 2]; let mut srcs = [[[0i32; 16]; 4]; 2]; diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 27abb338..2aa0a949 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -28,21 +28,21 @@ mod quant; mod rc; mod vlc; -use ec_core::error::{Error, Result}; use ec_core::BitWriter; -use ec_h264_syntax::nal::{escape_rbsp, NalUnitType}; +use ec_core::error::{Error, Result}; +use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; use ec_h264_syntax::{SliceType, Sps}; use crate::decoder::deblock_picture; use crate::dpb::{Picture, SliceParams as DeblockParams}; -use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; #[cfg(feature = "rd-ablation")] use crate::entropy::FLAG_SKIP; +use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; use crate::transform::{LevelScale4x4, LevelScale8x8}; use entropy::EncEntropy; -use headers::{write_pps, write_slice_header, write_sps, SeqParams, SliceParams}; -use mb::{encode_mb, MbEnc, Source}; +use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; +use mb::{MbEnc, Source, encode_mb}; use rc::RateControl; pub use mb::Preset; @@ -140,6 +140,8 @@ pub struct Encoder { sps: Sps, sps_nal: Vec, pps_nal: Vec, + /// `chroma_qp_index_offset`, decided from the first source picture. + cqo: i32, /// The previous reconstruction, which every P picture predicts from. reference: Picture, /// One private picture per worker; worker 0's doubles as the picture the @@ -234,7 +236,8 @@ impl Encoder { }; let sps_rbsp = write_sps(&seq); let sps = Sps::parse(&sps_rbsp)?; - let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8); + // Rewritten once the first source picture has been measured. + let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8, 0); let threads = if cfg.threads == 0 { std::thread::available_parallelism().map_or(1, |n| n.get()) } else { @@ -246,6 +249,7 @@ impl Encoder { Ok(Encoder { sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp), pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp), + cqo: 0, sps, reference: Picture::default(), workers, @@ -314,6 +318,11 @@ impl Encoder { return Err(Error::corrupt("frame size differs from the encoder's")); } self.pad_source(frame)?; + if self.frames == 0 { + self.cqo = chroma_qp_offset_for_source(&self.src, self.cfg.width, self.cfg.height); + let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo); + self.pps_nal = annex_b(NalUnitType::Pps, 3, &pps_rbsp); + } let idr = self.cfg.gop_size <= 1 || self .frames @@ -341,6 +350,7 @@ impl Encoder { let frame_num = self.frame_num; let idr_pic_id = self.idr_pic_id; let target = rc.frame_target(idr); + let cqo = self.cqo; let total_mbs = (mb_w * mb_h) as f64; let mut outputs: Vec> = Vec::new(); @@ -370,6 +380,7 @@ impl Encoder { idr, idr_pic_id, band_target: target * band_mbs / total_mbs, + cqo, }, ) })); @@ -389,8 +400,8 @@ impl Encoder { disable_deblock_idc: 0, alpha_offset: 0, beta_offset: 0, - cb_qp_offset: 0, - cr_qp_offset: 0, + cb_qp_offset: self.cqo, + cr_qp_offset: self.cqo, }); } for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { @@ -496,6 +507,79 @@ impl Encoder { } /// Everything one band worker needs. +/// Mean absolute neighbour difference of one plane, horizontal and vertical +/// averaged, over the `w` by `h` samples at the top left of `plane`. +fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 { + let (mut sum, mut n) = (0u64, 0u64); + for y in 0..h { + let row = &plane[y * stride..y * stride + w]; + for x in 1..w { + sum += u64::from(row[x].abs_diff(row[x - 1])); + n += 1; + } + if y > 0 { + let prev = &plane[(y - 1) * stride..(y - 1) * stride + w]; + for x in 0..w { + sum += u64::from(row[x].abs_diff(prev[x])); + n += 1; + } + } + } + if n == 0 { 0.0 } else { sum as f64 / n as f64 } +} + +/// `chroma_qp_index_offset` for a source, from how textured its chroma is +/// relative to its luma. +/// +/// A negative offset spends bits on chroma that luma would otherwise take. +/// That pays when the chroma planes are flat — screen capture, phone video, +/// anything with large constant-hue areas — because their few edges are what +/// the eye reads, and it loses on film, whose chroma carries as much detail as +/// its luma and whose luma is the better place for the same bits. The +/// separating statistic is the mean absolute sample gradient of the chroma +/// planes over that of luma, measured on the first source picture. +/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over +/// nine clips of the user's library, offset 0 against offset -2: +/// +/// ```text +/// chroma/luma gradient 0 -> -2 (dB) +/// 0.013 +0.019 +/// 0.092 +0.181 +/// 0.094 +0.228 +/// 0.098 +0.014 +/// 0.118 +0.081 +/// 0.122 +0.045 +/// 0.128 +0.065 +/// 0.286 +0.011 +/// 0.911 -0.158 +/// ``` +/// +/// Every clip whose chroma is flatter than its luma gains; the one film clip, +/// whose chroma gradient is nearly its luma's, loses. The threshold sits in +/// the middle of the gap the data leaves. +fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w / 2, h / 2); + let luma = mean_gradient(&src.y, src.stride, w, h); + if luma <= 0.0 { + return 0; + } + let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch) + + mean_gradient(&src.v, src.c_stride, cw, ch)) + / 2.0; + if chroma / luma < CHROMA_FLAT_RATIO { + CHROMA_FLAT_QP_OFFSET + } else { + 0 + } +} + +/// Chroma is "flat" below this share of the luma gradient. +const CHROMA_FLAT_RATIO: f64 = 0.5; + +/// The offset flat chroma is coded with. +const CHROMA_FLAT_QP_OFFSET: i32 = -2; + struct BandJob<'a> { src: &'a Source, reference: Option<&'a Picture>, @@ -512,6 +596,7 @@ struct BandJob<'a> { idr: bool, idr_pic_id: u32, band_target: f64, + cqo: i32, } /// Code one slice into its own RBSP. @@ -556,6 +641,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { ls: LevelScale4x4::new(&[16; 16]), ls8: LevelScale8x8::new(&[16; 64]), mb_ctx: crate::entropy::MbCtx::default(), + cqo: job.cqo, skip_inc: 0, qp_delta_inc: 0, }; @@ -653,7 +739,7 @@ fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option> 13) as u8; + let mut src = Source { + y: (0..w * h).map(noise).collect(), + u: vec![110; w * h / 4], + v: vec![130; w * h / 4], + stride: w, + c_stride: w / 2, + }; + assert_eq!( + chroma_qp_offset_for_source(&src, w as u32, h as u32), + CHROMA_FLAT_QP_OFFSET, + "flat chroma must take the negative offset" + ); + src.u = (0..w * h / 4).map(noise).collect(); + src.v = (0..w * h / 4).map(|i| noise(i + 7)).collect(); + assert_eq!( + chroma_qp_offset_for_source(&src, w as u32, h as u32), + 0, + "chroma as textured as the luma must keep 0" + ); + + // The chosen offset is what the decoder will read. + let mut enc = Encoder::new(EncoderConfig::new(w as u32, h as u32)).expect("encoder"); + let y: Vec = (0..w * h).map(noise).collect(); + let (u, v) = (vec![110u8; w * h / 4], vec![130u8; w * h / 4]); + let au = enc + .encode(&PictureView { + width: w as u32, + height: h as u32, + y: &y, + u: &u, + v: &v, + y_stride: w, + c_stride: w / 2, + }) + .expect("first picture encodes"); + assert!( + au.au + .windows(5) + .any(|n| n[..4] == [0, 0, 0, 1] && n[4] & 0x1f == 8), + "the IDR access unit carries a PPS" + ); + assert_eq!(enc.cqo, CHROMA_FLAT_QP_OFFSET); + } }