forge
Explore
Log in

Don't you dare go Hollow

Choose chroma_qp_index_offset from the source

Browse files at this commit

eb83b6ffbded7c502c9b8dcc37a59cdcc965074eAhmet Kaan GümüşParent: 6897ed7
  • perf
    • choose chroma_qp_index_offset from the source
Show full message
perf(h264): choose chroma_qp_index_offset from the source

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.rsmodified+8 -5
@@ -131,7 +131,7 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> {
131 }131 }
132 132
133 /// Write the picture parameter set RBSP (7.3.2.2).133 /// Write the picture parameter set RBSP (7.3.2.2).
134-pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec<u8> {134+pub(crate) fn write_pps(cabac: bool, transform_8x8: bool, cqo: i32) -> Vec<u8> {
135 let mut w = BitWriter::with_capacity(8);135 let mut w = BitWriter::with_capacity(8);
136 w.write_ue(0); // pic_parameter_set_id136 w.write_ue(0); // pic_parameter_set_id
137 w.write_ue(0); // seq_parameter_set_id137 w.write_ue(0); // seq_parameter_set_id
@@ -144,14 +144,14 @@ pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec<u8> {
144 w.write_bits(0, 2); // weighted_bipred_idc144 w.write_bits(0, 2); // weighted_bipred_idc
145 w.write_se(0); // pic_init_qp_minus26145 w.write_se(0); // pic_init_qp_minus26
146 w.write_se(0); // pic_init_qs_minus26146 w.write_se(0); // pic_init_qs_minus26
147- w.write_se(0); // chroma_qp_index_offset147+ w.write_se(cqo); // chroma_qp_index_offset
148 w.write_bit(false); // deblocking_filter_control_present_flag148 w.write_bit(false); // deblocking_filter_control_present_flag
149 w.write_bit(false); // constrained_intra_pred_flag149 w.write_bit(false); // constrained_intra_pred_flag
150 w.write_bit(false); // redundant_pic_cnt_present_flag150 w.write_bit(false); // redundant_pic_cnt_present_flag
151 if transform_8x8 {151 if transform_8x8 {
152 w.write_bit(true); // transform_8x8_mode_flag152 w.write_bit(true); // transform_8x8_mode_flag
153 w.write_bit(false); // pic_scaling_matrix_present_flag153 w.write_bit(false); // pic_scaling_matrix_present_flag
154- w.write_se(0); // second_chroma_qp_index_offset154+ w.write_se(cqo); // second_chroma_qp_index_offset
155 }155 }
156 trailing(&mut w);156 trailing(&mut w);
157 w.into_bytes()157 w.into_bytes()
@@ -264,10 +264,13 @@ mod tests {
264 assert_eq!(sps.chroma_format_idc, 1);264 assert_eq!(sps.chroma_format_idc, 1);
265 assert_eq!(sps.bit_depth_luma, 8);265 assert_eq!(sps.bit_depth_luma, 8);
266 }266 }
267- let pps = Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses");267+ let pps = Pps::parse(&write_pps(cabac, t8x8, -2), |_| Some(&sps)).expect("PPS parses");
268 assert_eq!(pps.entropy_coding_mode, cabac);268 assert_eq!(pps.entropy_coding_mode, cabac);
269 assert_eq!(pps.pic_init_qp, 26);269 assert_eq!(pps.pic_init_qp, 26);
270 assert_eq!(pps.transform_8x8_mode, t8x8);270 assert_eq!(pps.transform_8x8_mode, t8x8);
271+ assert_eq!(pps.chroma_qp_index_offset, -2);
272+ // Absent, it is inferred equal to chroma_qp_index_offset (7.4.2.2).
273+ assert_eq!(pps.second_chroma_qp_index_offset, -2);
271 }274 }
272 }275 }
273 276
@@ -286,7 +289,7 @@ mod tests {
286 fn slice_header_parses_back() {289 fn slice_header_parses_back() {
287 let p = params(320, 240);290 let p = params(320, 240);
288 let sps = Sps::parse(&write_sps(&p)).unwrap();291 let sps = Sps::parse(&write_sps(&p)).unwrap();
289- let pps = Pps::parse(&write_pps(true, false), |_| Some(&sps)).unwrap();292+ let pps = Pps::parse(&write_pps(true, false, 0), |_| Some(&sps)).unwrap();
290 for (idr, slice_type, first_mb, qp) in [293 for (idr, slice_type, first_mb, qp) in [
291 (true, SliceType::I, 0u32, 30i32),294 (true, SliceType::I, 0u32, 30i32),
292 (false, SliceType::P, 40, 18),295 (false, SliceType::P, 40, 18),
crates/ec-h264/src/enc/mb.rsmodified+7 -4
@@ -102,6 +102,9 @@ pub(crate) struct MbEnc<'a> {
102 pub ls8: LevelScale8x8,102 pub ls8: LevelScale8x8,
103 /// Neighbourhood of the macroblock being written (CABAC).103 /// Neighbourhood of the macroblock being written (CABAC).
104 pub mb_ctx: MbCtx,104 pub mb_ctx: MbCtx,
105+ /// The picture's `chroma_qp_index_offset`, chosen from the source in
106+ /// `Encoder::chroma_qp_offset_for_source`.
107+ pub cqo: i32,
105 /// ctxIdxInc for this macroblock's mb_skip_flag.108 /// ctxIdxInc for this macroblock's mb_skip_flag.
106 pub skip_inc: usize,109 pub skip_inc: usize,
107 /// `qp_delta_inc` of 9.3.3.1.1.5: whether the previous macroblock in this110 /// `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 {
285 (32 - (k + 1).leading_zeros()) as i32 * 2 - 1288 (32 - (k + 1).leading_zeros()) as i32 * 2 - 1
286 }289 }
287 290
288-/// Chroma QP of a luma QP under a zero `chroma_qp_index_offset`.291+/// Chroma QP of a luma QP under the picture's `chroma_qp_index_offset`.
289 #[inline]292 #[inline]
290-fn chroma_qp(qp: i32) -> i32 {293+fn chroma_qp(qp: i32, cqo: i32) -> i32 {
291- i32::from(CHROMA_QP[qp.clamp(0, 51) as usize])294+ i32::from(CHROMA_QP[(qp + cqo).clamp(0, 51) as usize])
292 }295 }
293 296
294 /// Which intra 4x4 modes the available neighbours allow (8.3.1.2).297 /// Which intra 4x4 modes the available neighbours allow (8.3.1.2).
@@ -1614,7 +1617,7 @@ fn code_chroma(
1614 intra: bool,1617 intra: bool,
1615 lv: &mut Levels,1618 lv: &mut Levels,
1616 ) {1619 ) {
1617- let qp_c = chroma_qp(qp_y);1620+ let qp_c = chroma_qp(qp_y, e.cqo);
1618 let mut dc_lists = [[0i32; 4]; 2];1621 let mut dc_lists = [[0i32; 4]; 2];
1619 let mut ac = [[[0i32; 16]; 4]; 2];1622 let mut ac = [[[0i32; 16]; 4]; 2];
1620 let mut srcs = [[[0i32; 16]; 4]; 2];1623 let mut srcs = [[[0i32; 16]; 4]; 2];
crates/ec-h264/src/enc/mod.rsmodified+147 -9
@@ -28,21 +28,21 @@ mod quant;
28 mod rc;28 mod rc;
29 mod vlc;29 mod vlc;
30 30
31-use ec_core::error::{Error, Result};
32 use ec_core::BitWriter;31 use ec_core::BitWriter;
33-use ec_h264_syntax::nal::{escape_rbsp, NalUnitType};32+use ec_core::error::{Error, Result};
33+use ec_h264_syntax::nal::{NalUnitType, escape_rbsp};
34 use ec_h264_syntax::{SliceType, Sps};34 use ec_h264_syntax::{SliceType, Sps};
35 35
36 use crate::decoder::deblock_picture;36 use crate::decoder::deblock_picture;
37 use crate::dpb::{Picture, SliceParams as DeblockParams};37 use crate::dpb::{Picture, SliceParams as DeblockParams};
38-use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
39 #[cfg(feature = "rd-ablation")]38 #[cfg(feature = "rd-ablation")]
40 use crate::entropy::FLAG_SKIP;39 use crate::entropy::FLAG_SKIP;
40+use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
41 use crate::transform::{LevelScale4x4, LevelScale8x8};41 use crate::transform::{LevelScale4x4, LevelScale8x8};
42 42
43 use entropy::EncEntropy;43 use entropy::EncEntropy;
44-use headers::{write_pps, write_slice_header, write_sps, SeqParams, SliceParams};44+use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
45-use mb::{encode_mb, MbEnc, Source};45+use mb::{MbEnc, Source, encode_mb};
46 use rc::RateControl;46 use rc::RateControl;
47 47
48 pub use mb::Preset;48 pub use mb::Preset;
@@ -140,6 +140,8 @@ pub struct Encoder {
140 sps: Sps,140 sps: Sps,
141 sps_nal: Vec<u8>,141 sps_nal: Vec<u8>,
142 pps_nal: Vec<u8>,142 pps_nal: Vec<u8>,
143+ /// `chroma_qp_index_offset`, decided from the first source picture.
144+ cqo: i32,
143 /// The previous reconstruction, which every P picture predicts from.145 /// The previous reconstruction, which every P picture predicts from.
144 reference: Picture,146 reference: Picture,
145 /// One private picture per worker; worker 0's doubles as the picture the147 /// One private picture per worker; worker 0's doubles as the picture the
@@ -234,7 +236,8 @@ impl Encoder {
234 };236 };
235 let sps_rbsp = write_sps(&seq);237 let sps_rbsp = write_sps(&seq);
236 let sps = Sps::parse(&sps_rbsp)?;238 let sps = Sps::parse(&sps_rbsp)?;
237- let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8);239+ // Rewritten once the first source picture has been measured.
240+ let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8, 0);
238 let threads = if cfg.threads == 0 {241 let threads = if cfg.threads == 0 {
239 std::thread::available_parallelism().map_or(1, |n| n.get())242 std::thread::available_parallelism().map_or(1, |n| n.get())
240 } else {243 } else {
@@ -246,6 +249,7 @@ impl Encoder {
246 Ok(Encoder {249 Ok(Encoder {
247 sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp),250 sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp),
248 pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp),251 pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp),
252+ cqo: 0,
249 sps,253 sps,
250 reference: Picture::default(),254 reference: Picture::default(),
251 workers,255 workers,
@@ -314,6 +318,11 @@ impl Encoder {
314 return Err(Error::corrupt("frame size differs from the encoder's"));318 return Err(Error::corrupt("frame size differs from the encoder's"));
315 }319 }
316 self.pad_source(frame)?;320 self.pad_source(frame)?;
321+ if self.frames == 0 {
322+ self.cqo = chroma_qp_offset_for_source(&self.src, self.cfg.width, self.cfg.height);
323+ let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo);
324+ self.pps_nal = annex_b(NalUnitType::Pps, 3, &pps_rbsp);
325+ }
317 let idr = self.cfg.gop_size <= 1326 let idr = self.cfg.gop_size <= 1
318 || self327 || self
319 .frames328 .frames
@@ -341,6 +350,7 @@ impl Encoder {
341 let frame_num = self.frame_num;350 let frame_num = self.frame_num;
342 let idr_pic_id = self.idr_pic_id;351 let idr_pic_id = self.idr_pic_id;
343 let target = rc.frame_target(idr);352 let target = rc.frame_target(idr);
353+ let cqo = self.cqo;
344 let total_mbs = (mb_w * mb_h) as f64;354 let total_mbs = (mb_w * mb_h) as f64;
345 355
346 let mut outputs: Vec<Vec<u8>> = Vec::new();356 let mut outputs: Vec<Vec<u8>> = Vec::new();
@@ -370,6 +380,7 @@ impl Encoder {
370 idr,380 idr,
371 idr_pic_id,381 idr_pic_id,
372 band_target: target * band_mbs / total_mbs,382 band_target: target * band_mbs / total_mbs,
383+ cqo,
373 },384 },
374 )385 )
375 }));386 }));
@@ -389,8 +400,8 @@ impl Encoder {
389 disable_deblock_idc: 0,400 disable_deblock_idc: 0,
390 alpha_offset: 0,401 alpha_offset: 0,
391 beta_offset: 0,402 beta_offset: 0,
392- cb_qp_offset: 0,403+ cb_qp_offset: self.cqo,
393- cr_qp_offset: 0,404+ cr_qp_offset: self.cqo,
394 });405 });
395 }406 }
396 for (band, worker) in bands.iter().skip(1).zip(rest.iter()) {407 for (band, worker) in bands.iter().skip(1).zip(rest.iter()) {
@@ -496,6 +507,79 @@ impl Encoder {
496 }507 }
497 508
498 /// Everything one band worker needs.509 /// Everything one band worker needs.
510+/// Mean absolute neighbour difference of one plane, horizontal and vertical
511+/// averaged, over the `w` by `h` samples at the top left of `plane`.
512+fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 {
513+ let (mut sum, mut n) = (0u64, 0u64);
514+ for y in 0..h {
515+ let row = &plane[y * stride..y * stride + w];
516+ for x in 1..w {
517+ sum += u64::from(row[x].abs_diff(row[x - 1]));
518+ n += 1;
519+ }
520+ if y > 0 {
521+ let prev = &plane[(y - 1) * stride..(y - 1) * stride + w];
522+ for x in 0..w {
523+ sum += u64::from(row[x].abs_diff(prev[x]));
524+ n += 1;
525+ }
526+ }
527+ }
528+ if n == 0 { 0.0 } else { sum as f64 / n as f64 }
529+}
530+
531+/// `chroma_qp_index_offset` for a source, from how textured its chroma is
532+/// relative to its luma.
533+///
534+/// A negative offset spends bits on chroma that luma would otherwise take.
535+/// That pays when the chroma planes are flat — screen capture, phone video,
536+/// anything with large constant-hue areas — because their few edges are what
537+/// the eye reads, and it loses on film, whose chroma carries as much detail as
538+/// its luma and whose luma is the better place for the same bits. The
539+/// separating statistic is the mean absolute sample gradient of the chroma
540+/// planes over that of luma, measured on the first source picture.
541+/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over
542+/// nine clips of the user's library, offset 0 against offset -2:
543+///
544+/// ```text
545+/// chroma/luma gradient 0 -> -2 (dB)
546+/// 0.013 +0.019
547+/// 0.092 +0.181
548+/// 0.094 +0.228
549+/// 0.098 +0.014
550+/// 0.118 +0.081
551+/// 0.122 +0.045
552+/// 0.128 +0.065
553+/// 0.286 +0.011
554+/// 0.911 -0.158
555+/// ```
556+///
557+/// Every clip whose chroma is flatter than its luma gains; the one film clip,
558+/// whose chroma gradient is nearly its luma's, loses. The threshold sits in
559+/// the middle of the gap the data leaves.
560+fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 {
561+ let (w, h) = (width as usize, height as usize);
562+ let (cw, ch) = (w / 2, h / 2);
563+ let luma = mean_gradient(&src.y, src.stride, w, h);
564+ if luma <= 0.0 {
565+ return 0;
566+ }
567+ let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch)
568+ + mean_gradient(&src.v, src.c_stride, cw, ch))
569+ / 2.0;
570+ if chroma / luma < CHROMA_FLAT_RATIO {
571+ CHROMA_FLAT_QP_OFFSET
572+ } else {
573+ 0
574+ }
575+}
576+
577+/// Chroma is "flat" below this share of the luma gradient.
578+const CHROMA_FLAT_RATIO: f64 = 0.5;
579+
580+/// The offset flat chroma is coded with.
581+const CHROMA_FLAT_QP_OFFSET: i32 = -2;
582+
499 struct BandJob<'a> {583 struct BandJob<'a> {
500 src: &'a Source,584 src: &'a Source,
501 reference: Option<&'a Picture>,585 reference: Option<&'a Picture>,
@@ -512,6 +596,7 @@ struct BandJob<'a> {
512 idr: bool,596 idr: bool,
513 idr_pic_id: u32,597 idr_pic_id: u32,
514 band_target: f64,598 band_target: f64,
599+ cqo: i32,
515 }600 }
516 601
517 /// Code one slice into its own RBSP.602 /// Code one slice into its own RBSP.
@@ -556,6 +641,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
556 ls: LevelScale4x4::new(&[16; 16]),641 ls: LevelScale4x4::new(&[16; 16]),
557 ls8: LevelScale8x8::new(&[16; 64]),642 ls8: LevelScale8x8::new(&[16; 64]),
558 mb_ctx: crate::entropy::MbCtx::default(),643 mb_ctx: crate::entropy::MbCtx::default(),
644+ cqo: job.cqo,
559 skip_inc: 0,645 skip_inc: 0,
560 qp_delta_inc: 0,646 qp_delta_inc: 0,
561 };647 };
@@ -653,7 +739,7 @@ fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option<Vec<(i64,
653 let mut out = std::fs::OpenOptions::new()739 let mut out = std::fs::OpenOptions::new()
654 .create(true)740 .create(true)
655 .append(true)741 .append(true)
656- .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture"))742+ .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture"))
657 .expect("open EC_H264_RD_TRACE");743 .expect("open EC_H264_RD_TRACE");
658 for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {744 for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {
659 let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);745 let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);
@@ -915,4 +1001,56 @@ mod tests {
915 cfg.transform_8x8 = true;1001 cfg.transform_8x8 = true;
916 assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26));1002 assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26));
917 }1003 }
1004+
1005+ /// Flat chroma over textured luma picks the negative chroma QP offset, and
1006+ /// it reaches the PPS the encoder emits; chroma as textured as the luma
1007+ /// keeps 0. The nine-clip measurement behind the rule is in
1008+ /// [`chroma_qp_offset_for_source`].
1009+ #[test]
1010+ fn chroma_offset_follows_the_source() {
1011+ let (w, h) = (64usize, 64usize);
1012+ let noise = |i: usize| ((i * 2654435761) >> 13) as u8;
1013+ let mut src = Source {
1014+ y: (0..w * h).map(noise).collect(),
1015+ u: vec![110; w * h / 4],
1016+ v: vec![130; w * h / 4],
1017+ stride: w,
1018+ c_stride: w / 2,
1019+ };
1020+ assert_eq!(
1021+ chroma_qp_offset_for_source(&src, w as u32, h as u32),
1022+ CHROMA_FLAT_QP_OFFSET,
1023+ "flat chroma must take the negative offset"
1024+ );
1025+ src.u = (0..w * h / 4).map(noise).collect();
1026+ src.v = (0..w * h / 4).map(|i| noise(i + 7)).collect();
1027+ assert_eq!(
1028+ chroma_qp_offset_for_source(&src, w as u32, h as u32),
1029+ 0,
1030+ "chroma as textured as the luma must keep 0"
1031+ );
1032+
1033+ // The chosen offset is what the decoder will read.
1034+ let mut enc = Encoder::new(EncoderConfig::new(w as u32, h as u32)).expect("encoder");
1035+ let y: Vec<u8> = (0..w * h).map(noise).collect();
1036+ let (u, v) = (vec![110u8; w * h / 4], vec![130u8; w * h / 4]);
1037+ let au = enc
1038+ .encode(&PictureView {
1039+ width: w as u32,
1040+ height: h as u32,
1041+ y: &y,
1042+ u: &u,
1043+ v: &v,
1044+ y_stride: w,
1045+ c_stride: w / 2,
1046+ })
1047+ .expect("first picture encodes");
1048+ assert!(
1049+ au.au
1050+ .windows(5)
1051+ .any(|n| n[..4] == [0, 0, 0, 1] && n[4] & 0x1f == 8),
1052+ "the IDR access unit carries a PPS"
1053+ );
1054+ assert_eq!(enc.cqo, CHROMA_FLAT_QP_OFFSET);
1055+ }
918 }1056 }