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> {
131131 }
132132
133133 /// 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> {
135135 let mut w = BitWriter::with_capacity(8);
136136 w.write_ue(0); // pic_parameter_set_id
137137 w.write_ue(0); // seq_parameter_set_id
@@ -144,14 +144,14 @@ pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec<u8> {
144144 w.write_bits(0, 2); // weighted_bipred_idc
145145 w.write_se(0); // pic_init_qp_minus26
146146 w.write_se(0); // pic_init_qs_minus26
147- w.write_se(0); // chroma_qp_index_offset
147+ w.write_se(cqo); // chroma_qp_index_offset
148148 w.write_bit(false); // deblocking_filter_control_present_flag
149149 w.write_bit(false); // constrained_intra_pred_flag
150150 w.write_bit(false); // redundant_pic_cnt_present_flag
151151 if transform_8x8 {
152152 w.write_bit(true); // transform_8x8_mode_flag
153153 w.write_bit(false); // pic_scaling_matrix_present_flag
154- w.write_se(0); // second_chroma_qp_index_offset
154+ w.write_se(cqo); // second_chroma_qp_index_offset
155155 }
156156 trailing(&mut w);
157157 w.into_bytes()
@@ -264,10 +264,13 @@ mod tests {
264264 assert_eq!(sps.chroma_format_idc, 1);
265265 assert_eq!(sps.bit_depth_luma, 8);
266266 }
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");
268268 assert_eq!(pps.entropy_coding_mode, cabac);
269269 assert_eq!(pps.pic_init_qp, 26);
270270 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);
271274 }
272275 }
273276
@@ -286,7 +289,7 @@ mod tests {
286289 fn slice_header_parses_back() {
287290 let p = params(320, 240);
288291 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();
290293 for (idr, slice_type, first_mb, qp) in [
291294 (true, SliceType::I, 0u32, 30i32),
292295 (false, SliceType::P, 40, 18),
crates/ec-h264/src/enc/mb.rsmodified+7 -4
@@ -102,6 +102,9 @@ pub(crate) struct MbEnc<'a> {
102102 pub ls8: LevelScale8x8,
103103 /// Neighbourhood of the macroblock being written (CABAC).
104104 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,
105108 /// ctxIdxInc for this macroblock's mb_skip_flag.
106109 pub skip_inc: usize,
107110 /// `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 {
285288 (32 - (k + 1).leading_zeros()) as i32 * 2 - 1
286289 }
287290
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`.
289292 #[inline]
290-fn chroma_qp(qp: i32) -> i32 {
291- i32::from(CHROMA_QP[qp.clamp(0, 51) as usize])
293+fn chroma_qp(qp: i32, cqo: i32) -> i32 {
294+ i32::from(CHROMA_QP[(qp + cqo).clamp(0, 51) as usize])
292295 }
293296
294297 /// Which intra 4x4 modes the available neighbours allow (8.3.1.2).
@@ -1614,7 +1617,7 @@ fn code_chroma(
16141617 intra: bool,
16151618 lv: &mut Levels,
16161619 ) {
1617- let qp_c = chroma_qp(qp_y);
1620+ let qp_c = chroma_qp(qp_y, e.cqo);
16181621 let mut dc_lists = [[0i32; 4]; 2];
16191622 let mut ac = [[[0i32; 16]; 4]; 2];
16201623 let mut srcs = [[[0i32; 16]; 4]; 2];
crates/ec-h264/src/enc/mod.rsmodified+146 -8
@@ -28,21 +28,21 @@ mod quant;
2828 mod rc;
2929 mod vlc;
3030
31-use ec_core::error::{Error, Result};
3231 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};
3434 use ec_h264_syntax::{SliceType, Sps};
3535
3636 use crate::decoder::deblock_picture;
3737 use crate::dpb::{Picture, SliceParams as DeblockParams};
38-use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
3938 #[cfg(feature = "rd-ablation")]
4039 use crate::entropy::FLAG_SKIP;
40+use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
4141 use crate::transform::{LevelScale4x4, LevelScale8x8};
4242
4343 use entropy::EncEntropy;
44-use headers::{write_pps, write_slice_header, write_sps, SeqParams, SliceParams};
45-use mb::{encode_mb, MbEnc, Source};
44+use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
45+use mb::{MbEnc, Source, encode_mb};
4646 use rc::RateControl;
4747
4848 pub use mb::Preset;
@@ -140,6 +140,8 @@ pub struct Encoder {
140140 sps: Sps,
141141 sps_nal: Vec<u8>,
142142 pps_nal: Vec<u8>,
143+ /// `chroma_qp_index_offset`, decided from the first source picture.
144+ cqo: i32,
143145 /// The previous reconstruction, which every P picture predicts from.
144146 reference: Picture,
145147 /// One private picture per worker; worker 0's doubles as the picture the
@@ -234,7 +236,8 @@ impl Encoder {
234236 };
235237 let sps_rbsp = write_sps(&seq);
236238 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);
238241 let threads = if cfg.threads == 0 {
239242 std::thread::available_parallelism().map_or(1, |n| n.get())
240243 } else {
@@ -246,6 +249,7 @@ impl Encoder {
246249 Ok(Encoder {
247250 sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp),
248251 pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp),
252+ cqo: 0,
249253 sps,
250254 reference: Picture::default(),
251255 workers,
@@ -314,6 +318,11 @@ impl Encoder {
314318 return Err(Error::corrupt("frame size differs from the encoder's"));
315319 }
316320 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+ }
317326 let idr = self.cfg.gop_size <= 1
318327 || self
319328 .frames
@@ -341,6 +350,7 @@ impl Encoder {
341350 let frame_num = self.frame_num;
342351 let idr_pic_id = self.idr_pic_id;
343352 let target = rc.frame_target(idr);
353+ let cqo = self.cqo;
344354 let total_mbs = (mb_w * mb_h) as f64;
345355
346356 let mut outputs: Vec<Vec<u8>> = Vec::new();
@@ -370,6 +380,7 @@ impl Encoder {
370380 idr,
371381 idr_pic_id,
372382 band_target: target * band_mbs / total_mbs,
383+ cqo,
373384 },
374385 )
375386 }));
@@ -389,8 +400,8 @@ impl Encoder {
389400 disable_deblock_idc: 0,
390401 alpha_offset: 0,
391402 beta_offset: 0,
392- cb_qp_offset: 0,
393- cr_qp_offset: 0,
403+ cb_qp_offset: self.cqo,
404+ cr_qp_offset: self.cqo,
394405 });
395406 }
396407 for (band, worker) in bands.iter().skip(1).zip(rest.iter()) {
@@ -496,6 +507,79 @@ impl Encoder {
496507 }
497508
498509 /// 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+
499583 struct BandJob<'a> {
500584 src: &'a Source,
501585 reference: Option<&'a Picture>,
@@ -512,6 +596,7 @@ struct BandJob<'a> {
512596 idr: bool,
513597 idr_pic_id: u32,
514598 band_target: f64,
599+ cqo: i32,
515600 }
516601
517602 /// Code one slice into its own RBSP.
@@ -556,6 +641,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
556641 ls: LevelScale4x4::new(&[16; 16]),
557642 ls8: LevelScale8x8::new(&[16; 64]),
558643 mb_ctx: crate::entropy::MbCtx::default(),
644+ cqo: job.cqo,
559645 skip_inc: 0,
560646 qp_delta_inc: 0,
561647 };
@@ -915,4 +1001,56 @@ mod tests {
9151001 cfg.transform_8x8 = true;
9161002 assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26));
9171003 }
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+ }
9181056 }