forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265-chroma': chroma mode search, measured and left off

Browse files at this commit

9d6633851cd15b1e4fc49f5455817cbf7503dd1fAhmet Kaan GümüşParent: 966bf25fea923b
crates/ec-h265/src/ctu.rsmodified+107 -10
@@ -144,6 +144,10 @@ pub struct CtuEncoder<'a> {
144 strong_smoothing: bool,144 strong_smoothing: bool,
145 /// How many of the 35 modes get a full rate-distortion trial.145 /// How many of the 35 modes get a full rate-distortion trial.
146 candidates: usize,146 candidates: usize,
147+ /// Whether the chroma mode is chosen by rate-distortion or always derived.
148+ chroma_rd: bool,
149+ /// Weight on chroma SSD in that decision, against luma's lambda.
150+ chroma_rd_weight: f64,
147 /// `log2` of the smallest coding unit the search will produce.151 /// `log2` of the smallest coding unit the search will produce.
148 min_cb_log2: u32,152 min_cb_log2: u32,
149 /// Intra mode per 4x4 block of the band; 255 = not coded yet.153 /// Intra mode per 4x4 block of the band; 255 = not coded yet.
@@ -172,6 +176,8 @@ impl<'a> CtuEncoder<'a> {
172 qp: i32,176 qp: i32,
173 strong_smoothing: bool,177 strong_smoothing: bool,
174 candidates: usize,178 candidates: usize,
179+ chroma_rd: bool,
180+ chroma_rd_weight: f64,
175 min_cb_log2: u32,181 min_cb_log2: u32,
176 ) -> CtuEncoder<'a> {182 ) -> CtuEncoder<'a> {
177 let band_rows = (height - band_y0).min(ctb_size);183 let band_rows = (height - band_y0).min(ctb_size);
@@ -189,6 +195,8 @@ impl<'a> CtuEncoder<'a> {
189 lambda_satd: lambda_for(qp).sqrt(),195 lambda_satd: lambda_for(qp).sqrt(),
190 strong_smoothing,196 strong_smoothing,
191 candidates: candidates.clamp(1, 35),197 candidates: candidates.clamp(1, 35),
198+ chroma_rd,
199+ chroma_rd_weight,
192 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),200 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
193 modes: vec![255; (width / 4) * (ctb_size / 4)],201 modes: vec![255; (width / 4) * (ctb_size / 4)],
194 depths: vec![0; (width / 4) * (ctb_size / 4)],202 depths: vec![0; (width / 4) * (ctb_size / 4)],
@@ -485,13 +493,17 @@ impl<'a> CtuEncoder<'a> {
485 let mpm = self.mpm_at(x, y);493 let mpm = self.mpm_at(x, y);
486 let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc);494 let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc);
487 self.write_mode_syntax(enc, mode, &mpm);495 self.write_mode_syntax(enc, mode, &mpm);
488- // intra_chroma_pred_mode = 4 (derived from luma): the single bin 0.496+ let (chroma_mode, chroma_idx) = if self.chroma_rd {
489- enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0);497+ self.choose_chroma_mode(x, y, n, log2, mode, enc)
498+ } else {
499+ (mode, None)
500+ };
501+ self.write_chroma_mode_syntax(enc, chroma_idx);
490 502
491 // Luma was reconstructed by the mode search; chroma is coded now.503 // Luma was reconstructed by the mode search; chroma is coded now.
492 let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0);504 let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0);
493- let cb_cbf = self.code_chroma(x, y, n, mode, 1);505+ let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1).1;
494- let cr_cbf = self.code_chroma(x, y, n, mode, 2);506+ let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2).1;
495 507
496 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));508 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
497 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));509 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
@@ -502,7 +514,7 @@ impl<'a> CtuEncoder<'a> {
502 encode_residual(enc, &levels[..n * n], log2, 0, scan);514 encode_residual(enc, &levels[..n * n], log2, 0, scan);
503 self.scratch.luma_levels = levels;515 self.scratch.luma_levels = levels;
504 }516 }
505- let chroma_scan = intra::scan_index(mode, log2 - 1, false);517+ let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false);
506 if cb_cbf {518 if cb_cbf {
507 let levels = std::mem::take(&mut self.scratch.cb_levels);519 let levels = std::mem::take(&mut self.scratch.cb_levels);
508 encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan);520 encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan);
@@ -743,9 +755,16 @@ impl<'a> CtuEncoder<'a> {
743 (ssd as f64, cbf)755 (ssd as f64, cbf)
744 }756 }
745 757
746- /// Code one chroma transform block in derived mode; returns its `cbf` and758+ /// Code one chroma transform block in `pred_mode`; returns its `(SSD, cbf)`
747- /// leaves the levels in the matching scratch buffer.759+ /// and leaves the levels in the matching scratch buffer.
748- fn code_chroma(&mut self, x: usize, y: usize, n: usize, luma_mode: u8, plane: usize) -> bool {760+ fn code_chroma(
761+ &mut self,
762+ x: usize,
763+ y: usize,
764+ n: usize,
765+ pred_mode: u8,
766+ plane: usize,
767+ ) -> (f64, bool) {
749 let cn = n / 2;768 let cn = n / 2;
750 let (cx, cy) = (x / 2, y / 2);769 let (cx, cy) = (x / 2, y / 2);
751 let refs = self.chroma_refs(cx, cy, cn, plane);770 let refs = self.chroma_refs(cx, cy, cn, plane);
@@ -753,7 +772,7 @@ impl<'a> CtuEncoder<'a> {
753 let src = if plane == 1 { self.src.cb } else { self.src.cr };772 let src = if plane == 1 { self.src.cb } else { self.src.cr };
754 intra::predict(773 intra::predict(
755 &refs,774 &refs,
756- luma_mode,775+ pred_mode,
757 cn,776 cn,
758 false,777 false,
759 self.strong_smoothing,778 self.strong_smoothing,
@@ -785,11 +804,14 @@ impl<'a> CtuEncoder<'a> {
785 } else {804 } else {
786 self.scratch.residual[..cn * cn].fill(0);805 self.scratch.residual[..cn * cn].fill(0);
787 }806 }
807+ let mut ssd = 0i64;
788 for row in 0..cn {808 for row in 0..cn {
789 for col in 0..cn {809 for col in 0..cn {
790 let value = (i32::from(self.scratch.pred[row * cn + col])810 let value = (i32::from(self.scratch.pred[row * cn + col])
791 + self.scratch.residual[row * cn + col])811 + self.scratch.residual[row * cn + col])
792 .clamp(0, 255) as u8;812 .clamp(0, 255) as u8;
813+ let d = i64::from(src[(cy + row) * cw + cx + col]) - i64::from(value);
814+ ssd += d * d;
793 self.write_rec_c(cx + col, cy + row, plane, value);815 self.write_rec_c(cx + col, cy + row, plane, value);
794 }816 }
795 }817 }
@@ -799,7 +821,82 @@ impl<'a> CtuEncoder<'a> {
799 &mut self.scratch.cr_levels821 &mut self.scratch.cr_levels
800 };822 };
801 levels[..cn * cn].copy_from_slice(&self.scratch.levels[..cn * cn]);823 levels[..cn * cn].copy_from_slice(&self.scratch.levels[..cn * cn]);
802- cbf824+ (ssd as f64, cbf)
825+ }
826+
827+ // ---- chroma mode decision --------------------------------------------
828+
829+ /// Write `intra_chroma_pred_mode`: the single bin 0 for the derived mode,
830+ /// or bin 1 and two bypass bits picking one of the four explicit modes.
831+ fn write_chroma_mode_syntax(&self, enc: &mut CabacEncoder, idx: Option<u32>) {
832+ match idx {
833+ None => enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0),
834+ Some(i) => {
835+ enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 1);
836+ enc.encode_bypass_bits(i, 2);
837+ }
838+ }
839+ }
840+
841+ /// Pick the chroma prediction mode by rate-distortion over the five the
842+ /// syntax allows: planar, vertical, horizontal and DC — each replaced by
843+ /// angular 34 when it collides with the luma mode — plus the derived mode,
844+ /// which is the luma mode itself and costs one bin instead of three.
845+ ///
846+ /// Returns the mode and the index to code, `None` meaning derived. Neither
847+ /// the winner's reconstruction nor its levels survive the trial: the caller
848+ /// codes the winner again for real.
849+ fn choose_chroma_mode(
850+ &mut self,
851+ x: usize,
852+ y: usize,
853+ n: usize,
854+ log2: u32,
855+ luma_mode: u8,
856+ enc: &mut CabacEncoder,
857+ ) -> (u8, Option<u32>) {
858+ let mut explicit = [0u8, 26, 10, 1];
859+ for mode in explicit.iter_mut() {
860+ if *mode == luma_mode {
861+ *mode = 34;
862+ }
863+ }
864+ let start = enc.snapshot();
865+ enc.set_counting(true);
866+ let mut best = (f64::MAX, luma_mode, None);
867+ for (i, mode) in explicit
868+ .iter()
869+ .copied()
870+ .enumerate()
871+ .map(|(i, m)| (Some(i as u32), m))
872+ .chain(std::iter::once((None, luma_mode)))
873+ {
874+ let bits_before = enc.bit_count();
875+ self.write_chroma_mode_syntax(enc, i);
876+ let (cb_ssd, cb_cbf) = self.code_chroma(x, y, n, mode, 1);
877+ let (cr_ssd, cr_cbf) = self.code_chroma(x, y, n, mode, 2);
878+ enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
879+ enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
880+ let scan = intra::scan_index(mode, log2 - 1, false);
881+ if cb_cbf {
882+ let levels = std::mem::take(&mut self.scratch.cb_levels);
883+ encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, scan);
884+ self.scratch.cb_levels = levels;
885+ }
886+ if cr_cbf {
887+ let levels = std::mem::take(&mut self.scratch.cr_levels);
888+ encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, scan);
889+ self.scratch.cr_levels = levels;
890+ }
891+ let bits = enc.bit_count() - bits_before;
892+ enc.restore(&start);
893+ let cost = self.chroma_rd_weight * (cb_ssd + cr_ssd) + self.lambda * bits as f64;
894+ if cost < best.0 {
895+ best = (cost, mode, i);
896+ }
897+ }
898+ enc.set_counting(false);
899+ (best.1, best.2)
803 }900 }
804 901
805 // ---- reference samples -----------------------------------------------902 // ---- reference samples -----------------------------------------------
crates/ec-h265/src/encoder.rsmodified+31 -0
@@ -94,6 +94,33 @@ pub struct EncoderConfig {
94 /// knee is where the default sits. `EC_H265_RDO_CANDIDATES` in the gate94 /// knee is where the default sits. `EC_H265_RDO_CANDIDATES` in the gate
95 /// test re-runs the sweep.95 /// test re-runs the sweep.
96 pub rdo_candidates: usize,96 pub rdo_candidates: usize,
97+ /// Whether the chroma prediction mode is chosen by rate-distortion over the
98+ /// five modes the syntax allows, instead of always taking the derived mode.
99+ ///
100+ /// Off by default: measured against x265 on four real clips it is a wash,
101+ /// and on screen capture it is a loss (BD-PSNR luma / all-plane, derived
102+ /// mode -> search, `chroma_rd_weight: 1.0`):
103+ ///
104+ /// | clip | derived | search |
105+ /// |------|---------|--------|
106+ /// | 4K film | -0.685 / -0.703 | -0.757 / **-0.606** |
107+ /// | 1138x640 web | -0.507 / -0.556 | -0.584 / **-0.505** |
108+ /// | 1440p screen capture | **-2.465 / -2.360** | -2.617 / -2.460 |
109+ /// | 1080p phone | -0.366 / **-0.387** | -0.477 / -0.384 |
110+ ///
111+ /// Luma falls on every clip because the extra chroma bits come out of the
112+ /// same budget at a fixed QP; all-plane gains 0.10 dB and 0.05 dB on the two
113+ /// camera clips, is flat on the third and loses 0.10 dB on the screen
114+ /// capture, for 10-15% more encode time. The average is +0.01 dB all-plane,
115+ /// which is not a default. [`EncoderConfig::chroma_rd_weight`] was swept at
116+ /// 0.25/0.5/1.0/2.0 and did not change the shape of that table: the screen
117+ /// capture loses at every weight, so the cause is not the lambda.
118+ pub chroma_mode_search: bool,
119+ /// Weight on chroma SSD in that decision, against the luma lambda. Swept
120+ /// at 0.25/0.5/1.0/2.0 on three clips; 1.0 is the best of them everywhere
121+ /// the search wins at all (4K film all-plane: -0.606 at 1.0 against -0.649
122+ /// at 0.25, -0.619 at 0.5, -0.657 at 2.0).
123+ pub chroma_rd_weight: f64,
97 /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a124 /// Smallest coding unit the search will produce, 8 or 16. Sixteen is a
98 /// *coarser* search that is not always faster: on real pictures the 8x8125 /// *coarser* search that is not always faster: on real pictures the 8x8
99 /// blocks pay for their search in residual bits (measured: -27% bits and126 /// blocks pay for their search in residual bits (measured: -27% bits and
@@ -125,6 +152,8 @@ impl EncoderConfig {
125 threads: 0,152 threads: 0,
126 ctb_size: 32,153 ctb_size: 32,
127 rdo_candidates: 5,154 rdo_candidates: 5,
155+ chroma_mode_search: false,
156+ chroma_rd_weight: 1.0,
128 min_cu_size: 8,157 min_cu_size: 8,
129 video_signal_type: None,158 video_signal_type: None,
130 sample_aspect_ratio: None,159 sample_aspect_ratio: None,
@@ -498,6 +527,8 @@ impl Encoder {
498 slice_qp,527 slice_qp,
499 true,528 true,
500 self.cfg.rdo_candidates,529 self.cfg.rdo_candidates,
530+ self.cfg.chroma_mode_search,
531+ self.cfg.chroma_rd_weight,
501 self.cfg.min_cu_size.max(8).trailing_zeros(),532 self.cfg.min_cu_size.max(8).trailing_zeros(),
502 );533 );
503 for col in 0..cols {534 for col in 0..cols {
crates/ec-h265/tests/conformance.rsmodified+44 -0
@@ -90,7 +90,18 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 {
90 90
91 /// Encode one picture; `ctb` of `None` takes the configured default.91 /// Encode one picture; `ctb` of `None` takes the configured default.
92 fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) {92 fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) {
93+ encode_with(width, height, qp, ctb, false)
94+}
95+
96+fn encode_with(
97+ width: u32,
98+ height: u32,
99+ qp: i32,
100+ ctb: Option<usize>,
101+ chroma_mode_search: bool,
102+) -> (VideoFrame, EncodedPicture) {
93 let mut cfg = EncoderConfig::new(width, height);103 let mut cfg = EncoderConfig::new(width, height);
104+ cfg.chroma_mode_search = chroma_mode_search;
94 cfg.rate_control = RateControl::ConstantQp(qp);105 cfg.rate_control = RateControl::ConstantQp(qp);
95 if let Some(ctb) = ctb {106 if let Some(ctb) = ctb {
96 cfg.ctb_size = ctb;107 cfg.ctb_size = ctb;
@@ -103,6 +114,39 @@ fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame,
103 (frame, coded)114 (frame, coded)
104 }115 }
105 116
117+/// The chroma mode search is off by default (it loses on screen content, see
118+/// `EncoderConfig::chroma_mode_search`), so the shapes above never code an
119+/// `intra_chroma_pred_mode` other than the derived one. This exercises the four
120+/// explicit modes: the stream has to differ from the derived-only one — proving
121+/// the search actually fired — and still decode bit-exactly.
122+#[test]
123+fn chroma_mode_search_decodes_bit_exactly() {
124+ if !have_ffmpeg() {
125+ eprintln!("skipping: ffmpeg not installed");
126+ return;
127+ }
128+ for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] {
129+ let (source, coded) = encode_with(w, h, 27, None, true);
130+ let (_, derived) = encode_with(w, h, 27, None, false);
131+ let name = format!("chroma-rd-{w}x{h}");
132+ assert_ne!(
133+ coded.au, derived.au,
134+ "{name}: the search never picked a mode other than the derived one, so this decode proves nothing"
135+ );
136+ let path = write_au(&name, &coded);
137+ let decoded = match ffmpeg_decode(&path) {
138+ Ok(bytes) => bytes,
139+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
140+ };
141+ let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
142+ assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
143+ let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
144+ assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");
145+ let quality = psnr(&planes_of(&source), &recon);
146+ assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27");
147+ }
148+}
149+
106 #[test]150 #[test]
107 fn ffmpeg_decodes_bit_exactly_at_every_shape() {151 fn ffmpeg_decodes_bit_exactly_at_every_shape() {
108 if !have_ffmpeg() {152 if !have_ffmpeg() {
crates/ec-h265/tests/encode.rsmodified+6 -0
@@ -429,6 +429,12 @@ fn bd_psnr_vs_x265() {
429 cfg.threads = 0;429 cfg.threads = 0;
430 // Ablation knob: how many SATD survivors reach the full rate-distortion430 // Ablation knob: how many SATD survivors reach the full rate-distortion
431 // trial in the luma mode search. The shipped default is 5.431 // trial in the luma mode search. The shipped default is 5.
432+ if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") {
433+ cfg.chroma_mode_search = v != "0";
434+ }
435+ if let Ok(w) = std::env::var("EC_H265_CHROMA_W") {
436+ cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number");
437+ }
432 if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") {438 if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") {
433 cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number");439 cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number");
434 }440 }