forge
Explore
Log in

Don't you dare go Hollow

Sign data hiding, correct and shipped off

Browse files at this commit

0877a3629ced29df5b301e4a4363db04d8c6810dAhmet Kaan GümüşParent: 089675b
  • feat
    • sign data hiding, correct and shipped off
Show full message
feat(h265): sign data hiding, correct and shipped off

Implements sign_data_hiding_enabled_flag per 7.3.8.11: for each 4x4
sub-block whose first and last significant scan positions are more than
three apart, the sign at the first position is not coded and the decoder
infers it from the parity of the sub-block's summed absolute levels. The
encoder nudges one already-non-zero level by one when the parity comes
out wrong, picking the coefficient whose ideal (pre-rounding) level sits
closest to the nudge.

Proven bit-exact: sign_hiding_decodes_bit_exactly encodes 64x64, 130x66
and 352x288 with hiding on and off, asserts the streams differ, and
decodes both through ffmpeg with zero sample mismatches.

Shipped off. On the clip gate it loses: -0.033 dB BD-PSNR on a 2560x1440
screen capture (-0.479 -> -0.512 vs x265) and -0.043 dB on 1080p film
(+0.246 -> +0.203). Hiding is mandatory for a qualifying sub-block, so
every one of them pays whether its cheapest nudge is cheap or not, and
levels straight off the quantiser's rounding make that nudge expensive.
A rate bias on the nudge picker was swept at +-0.25 and +-0.5 units of
squared level error per bit and lost in both directions, so the picker
is distortion-only. Worth re-measuring once RDOQ lands, which is where
this pays for other encoders.
crates/ec-h265/src/ctu.rsmodified+61 -12
@@ -24,7 +24,7 @@
24 24
25 use crate::cabac::{CabacEncoder, CabacState, ctx};25 use crate::cabac::{CabacEncoder, CabacState, ctx};
26 use crate::intra::{self, Availability, Refs};26 use crate::intra::{self, Availability, Refs};
27-use crate::residual::encode_residual;27+use crate::residual::{self, encode_residual};
28 use crate::transform::{28 use crate::transform::{
29 chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst,29 chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst,
30 };30 };
@@ -150,6 +150,7 @@ pub struct CtuEncoder<'a> {
150 chroma_rd_weight: f64,150 chroma_rd_weight: f64,
151 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions.151 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions.
152 intra_nxn: bool,152 intra_nxn: bool,
153+ sign_hiding: bool,
153 /// `log2` of the smallest coding unit the search will produce.154 /// `log2` of the smallest coding unit the search will produce.
154 min_cb_log2: u32,155 min_cb_log2: u32,
155 /// Intra mode per 4x4 block of the band; 255 = not coded yet.156 /// Intra mode per 4x4 block of the band; 255 = not coded yet.
@@ -181,6 +182,7 @@ impl<'a> CtuEncoder<'a> {
181 chroma_rd: bool,182 chroma_rd: bool,
182 chroma_rd_weight: f64,183 chroma_rd_weight: f64,
183 intra_nxn: bool,184 intra_nxn: bool,
185+ sign_hiding: bool,
184 min_cb_log2: u32,186 min_cb_log2: u32,
185 ) -> CtuEncoder<'a> {187 ) -> CtuEncoder<'a> {
186 let band_rows = (height - band_y0).min(ctb_size);188 let band_rows = (height - band_y0).min(ctb_size);
@@ -201,6 +203,7 @@ impl<'a> CtuEncoder<'a> {
201 chroma_rd,203 chroma_rd,
202 chroma_rd_weight,204 chroma_rd_weight,
203 intra_nxn,205 intra_nxn,
206+ sign_hiding,
204 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),207 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
205 modes: vec![255; (width / 4) * (ctb_size / 4)],208 modes: vec![255; (width / 4) * (ctb_size / 4)],
206 depths: vec![0; (width / 4) * (ctb_size / 4)],209 depths: vec![0; (width / 4) * (ctb_size / 4)],
@@ -572,18 +575,18 @@ impl<'a> CtuEncoder<'a> {
572 enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part]));575 enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part]));
573 if cbfs[part] {576 if cbfs[part] {
574 let scan = intra::scan_index(modes[part], 2, true);577 let scan = intra::scan_index(modes[part], 2, true);
575- encode_residual(enc, &levels[part], 2, 0, scan);578+ encode_residual(enc, &levels[part], 2, 0, scan, self.sign_hiding);
576 }579 }
577 if part == 3 {580 if part == 3 {
578 let chroma_scan = intra::scan_index(chroma_mode, 2, false);581 let chroma_scan = intra::scan_index(chroma_mode, 2, false);
579 if cb_cbf {582 if cb_cbf {
580 let l = std::mem::take(&mut self.scratch.cb_levels);583 let l = std::mem::take(&mut self.scratch.cb_levels);
581- encode_residual(enc, &l[..16], 2, 1, chroma_scan);584+ encode_residual(enc, &l[..16], 2, 1, chroma_scan, self.sign_hiding);
582 self.scratch.cb_levels = l;585 self.scratch.cb_levels = l;
583 }586 }
584 if cr_cbf {587 if cr_cbf {
585 let l = std::mem::take(&mut self.scratch.cr_levels);588 let l = std::mem::take(&mut self.scratch.cr_levels);
586- encode_residual(enc, &l[..16], 2, 2, chroma_scan);589+ encode_residual(enc, &l[..16], 2, 2, chroma_scan, self.sign_hiding);
587 self.scratch.cr_levels = l;590 self.scratch.cr_levels = l;
588 }591 }
589 }592 }
@@ -629,18 +632,32 @@ impl<'a> CtuEncoder<'a> {
629 if luma_cbf {632 if luma_cbf {
630 let scan = intra::scan_index(mode, log2, true);633 let scan = intra::scan_index(mode, log2, true);
631 let levels = std::mem::take(&mut self.scratch.luma_levels);634 let levels = std::mem::take(&mut self.scratch.luma_levels);
632- encode_residual(enc, &levels[..n * n], log2, 0, scan);635+ encode_residual(enc, &levels[..n * n], log2, 0, scan, self.sign_hiding);
633 self.scratch.luma_levels = levels;636 self.scratch.luma_levels = levels;
634 }637 }
635 let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false);638 let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false);
636 if cb_cbf {639 if cb_cbf {
637 let levels = std::mem::take(&mut self.scratch.cb_levels);640 let levels = std::mem::take(&mut self.scratch.cb_levels);
638- encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan);641+ encode_residual(
642+ enc,
643+ &levels[..n * n / 4],
644+ log2 - 1,
645+ 1,
646+ chroma_scan,
647+ self.sign_hiding,
648+ );
639 self.scratch.cb_levels = levels;649 self.scratch.cb_levels = levels;
640 }650 }
641 if cr_cbf {651 if cr_cbf {
642 let levels = std::mem::take(&mut self.scratch.cr_levels);652 let levels = std::mem::take(&mut self.scratch.cr_levels);
643- encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, chroma_scan);653+ encode_residual(
654+ enc,
655+ &levels[..n * n / 4],
656+ log2 - 1,
657+ 2,
658+ chroma_scan,
659+ self.sign_hiding,
660+ );
644 self.scratch.cr_levels = levels;661 self.scratch.cr_levels = levels;
645 }662 }
646 663
@@ -825,7 +842,7 @@ impl<'a> CtuEncoder<'a> {
825 if cbf {842 if cbf {
826 let scan = intra::scan_index(mode, log2, true);843 let scan = intra::scan_index(mode, log2, true);
827 let levels = std::mem::take(&mut self.scratch.levels);844 let levels = std::mem::take(&mut self.scratch.levels);
828- encode_residual(enc, &levels[..n * n], log2, 0, scan);845+ encode_residual(enc, &levels[..n * n], log2, 0, scan, self.sign_hiding);
829 self.scratch.levels = levels;846 self.scratch.levels = levels;
830 }847 }
831 let bits = enc.bit_count() - bits_before;848 let bits = enc.bit_count() - bits_before;
@@ -866,7 +883,16 @@ impl<'a> CtuEncoder<'a> {
866 }883 }
867 let dst = uses_dst(n, true);884 let dst = uses_dst(n, true);
868 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);885 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);
869- let nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp);886+ let mut nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp);
887+ if self.sign_hiding && nonzero > 0 {
888+ nonzero = residual::hide_signs(
889+ &self.scratch.coeffs,
890+ &mut self.scratch.levels,
891+ n,
892+ self.qp,
893+ intra::scan_index(mode, n.trailing_zeros(), true),
894+ );
895+ }
870 let cbf = nonzero > 0;896 let cbf = nonzero > 0;
871 if cbf {897 if cbf {
872 dequantize(&self.scratch.levels, &mut self.scratch.scaled, n, self.qp);898 dequantize(&self.scratch.levels, &mut self.scratch.scaled, n, self.qp);
@@ -916,12 +942,21 @@ impl<'a> CtuEncoder<'a> {
916 }942 }
917 }943 }
918 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);944 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
919- let nonzero = quantize(945+ let mut nonzero = quantize(
920 &self.scratch.coeffs,946 &self.scratch.coeffs,
921 &mut self.scratch.levels,947 &mut self.scratch.levels,
922 cn,948 cn,
923 self.qp_c,949 self.qp_c,
924 );950 );
951+ if self.sign_hiding && nonzero > 0 {
952+ nonzero = residual::hide_signs(
953+ &self.scratch.coeffs,
954+ &mut self.scratch.levels,
955+ cn,
956+ self.qp_c,
957+ intra::scan_index(pred_mode, cn.trailing_zeros(), false),
958+ );
959+ }
925 let cbf = nonzero > 0;960 let cbf = nonzero > 0;
926 if cbf {961 if cbf {
927 dequantize(962 dequantize(
@@ -1010,12 +1045,26 @@ impl<'a> CtuEncoder<'a> {
1010 let scan = intra::scan_index(mode, log2 - 1, false);1045 let scan = intra::scan_index(mode, log2 - 1, false);
1011 if cb_cbf {1046 if cb_cbf {
1012 let levels = std::mem::take(&mut self.scratch.cb_levels);1047 let levels = std::mem::take(&mut self.scratch.cb_levels);
1013- encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, scan);1048+ encode_residual(
1049+ enc,
1050+ &levels[..n * n / 4],
1051+ log2 - 1,
1052+ 1,
1053+ scan,
1054+ self.sign_hiding,
1055+ );
1014 self.scratch.cb_levels = levels;1056 self.scratch.cb_levels = levels;
1015 }1057 }
1016 if cr_cbf {1058 if cr_cbf {
1017 let levels = std::mem::take(&mut self.scratch.cr_levels);1059 let levels = std::mem::take(&mut self.scratch.cr_levels);
1018- encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, scan);1060+ encode_residual(
1061+ enc,
1062+ &levels[..n * n / 4],
1063+ log2 - 1,
1064+ 2,
1065+ scan,
1066+ self.sign_hiding,
1067+ );
1019 self.scratch.cr_levels = levels;1068 self.scratch.cr_levels = levels;
1020 }1069 }
1021 let bits = enc.bit_count() - bits_before;1070 let bits = enc.bit_count() - bits_before;
crates/ec-h265/src/encoder.rsmodified+15 -0
@@ -132,6 +132,18 @@ pub struct EncoderConfig {
132 /// capture (-2.619 dB against x265 without it, -0.479 dB with) and132 /// capture (-2.619 dB against x265 without it, -0.479 dB with) and
133 /// +0.007 dB on 1080p film, so it never loses.133 /// +0.007 dB on 1080p film, so it never loses.
134 pub intra_nxn: bool,134 pub intra_nxn: bool,
135+
136+ /// Whether a sub-block's first sign is hidden in the parity of its
137+ /// absolute levels (`sign_data_hiding_enabled_flag`). Buys one bypass bin
138+ /// per qualifying sub-block for a level nudged by one.
139+ ///
140+ /// Off: measured at -0.033 dB BD-PSNR on a 2560x1440 screen capture and
141+ /// -0.043 dB on 1080p film. Hiding is not optional per sub-block, so every
142+ /// qualifying one pays for the bin whether the nudge is cheap or not, and
143+ /// with levels that come straight from the quantiser's rounding the nudges
144+ /// cost more than the signs save. Worth re-measuring once RDOQ lands: that
145+ /// is where the gain in other encoders comes from.
146+ pub sign_hiding: bool,
135 /// What the samples mean, written into the VUI.147 /// What the samples mean, written into the VUI.
136 pub video_signal_type: Option<VideoSignalType>,148 pub video_signal_type: Option<VideoSignalType>,
137 /// Sample aspect ratio.149 /// Sample aspect ratio.
@@ -161,6 +173,7 @@ impl EncoderConfig {
161 chroma_rd_weight: 1.0,173 chroma_rd_weight: 1.0,
162 min_cu_size: 8,174 min_cu_size: 8,
163 intra_nxn: true,175 intra_nxn: true,
176+ sign_hiding: false,
164 video_signal_type: None,177 video_signal_type: None,
165 sample_aspect_ratio: None,178 sample_aspect_ratio: None,
166 timing: None,179 timing: None,
@@ -289,6 +302,7 @@ impl Encoder {
289 // changing what either side predicts from. Turning them off buys302 // changing what either side predicts from. Turning them off buys
290 // that identity (and the picture-hash check that rides on it)303 // that identity (and the picture-hash check that rides on it)
291 // rather than a fraction of a dB.304 // rather than a fraction of a dB.
305+ sign_data_hiding_enabled: cfg.sign_hiding,
292 deblocking_filter_control_present: true,306 deblocking_filter_control_present: true,
293 deblocking_filter_disabled: true,307 deblocking_filter_disabled: true,
294 loop_filter_across_slices_enabled: false,308 loop_filter_across_slices_enabled: false,
@@ -536,6 +550,7 @@ impl Encoder {
536 self.cfg.chroma_mode_search,550 self.cfg.chroma_mode_search,
537 self.cfg.chroma_rd_weight,551 self.cfg.chroma_rd_weight,
538 self.cfg.intra_nxn,552 self.cfg.intra_nxn,
553+ self.cfg.sign_hiding,
539 self.cfg.min_cu_size.max(8).trailing_zeros(),554 self.cfg.min_cu_size.max(8).trailing_zeros(),
540 );555 );
541 for col in 0..cols {556 for col in 0..cols {
crates/ec-h265/src/residual.rsmodified+79 -5
@@ -1,6 +1,7 @@
1 //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5).1 //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5).
2 2
3 use crate::cabac::{CabacEncoder, ctx};3 use crate::cabac::{CabacEncoder, ctx};
4+use crate::transform::ideal_level;
4 use std::sync::LazyLock;5 use std::sync::LazyLock;
5 6
6 /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`.7 /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`.
@@ -129,6 +130,71 @@ fn last_prefix(coord: u32) -> (u32, u32) {
129 }130 }
130 }131 }
131 132
133+/// Make each sub-block's absolute levels carry the sign of its first
134+/// significant coefficient, so that sign need not be coded (7.3.8.11, the
135+/// `sign_data_hiding_enabled_flag` path). A sub-block qualifies when its first
136+/// and last significant coefficients are more than three scan positions apart;
137+/// where the parity is wrong, one level is nudged by one, the cheapest being
138+/// whichever coefficient the quantiser rounded furthest in that direction.
139+///
140+/// This runs on the levels before they are dequantised, so the encoder's own
141+/// reconstruction is built from what the decoder will read back.
142+pub fn hide_signs(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32, scan_idx: usize) -> usize {
143+ let log2_size = n.trailing_zeros();
144+ let sub_scan = scan(log2_size - 2, scan_idx);
145+ let pos_scan = scan(2, scan_idx);
146+ for &(xs, ys) in sub_scan {
147+ let (xs, ys) = (xs as usize, ys as usize);
148+ let at = |p: usize| {
149+ let (xp, yp) = pos_scan[p];
150+ (ys * 4 + yp as usize) * n + xs * 4 + xp as usize
151+ };
152+ let Some(first) = (0..16).find(|&p| levels[at(p)] != 0) else {
153+ continue;
154+ };
155+ let last = (0..16).rev().find(|&p| levels[at(p)] != 0).unwrap_or(first);
156+ if last - first <= 3 {
157+ continue;
158+ }
159+ let sum: i32 = (0..16).map(|p| levels[at(p)].abs()).sum();
160+ let negative = levels[at(first)] < 0;
161+ if (sum & 1 == 1) == negative {
162+ continue;
163+ }
164+ // The parity is wrong. Changing any level by one fixes it; take the
165+ // one whose rounding error the change reduces most (or grows least).
166+ // Only levels that stay non-zero are considered, so no coefficient
167+ // enters or leaves the block and the scan positions above still hold.
168+ let mut best: Option<(f64, usize, i32)> = None;
169+ for p in 0..16 {
170+ let i = at(p);
171+ let level = levels[i];
172+ if level == 0 {
173+ continue;
174+ }
175+ let magnitude = f64::from(level.abs());
176+ let ideal = ideal_level(coeffs[i], n, qp);
177+ // Distortion alone picks the coefficient: a rate bias favouring
178+ // decrements (or increments) was swept through the clip gate at
179+ // +-0.25 and +-0.5 units of squared level error per bit and lost
180+ // in both directions, so there is none.
181+ let mut consider = |cost: f64, delta: i32| {
182+ if best.is_none_or(|(b, _, _)| cost < b) {
183+ best = Some((cost, i, delta));
184+ }
185+ };
186+ consider(1.0 - 2.0 * (ideal - magnitude), 1);
187+ if level.abs() > 1 {
188+ consider(1.0 + 2.0 * (ideal - magnitude), -1);
189+ }
190+ }
191+ if let Some((_, i, delta)) = best {
192+ levels[i] += if levels[i] < 0 { -delta } else { delta };
193+ }
194+ }
195+ levels[..n * n].iter().filter(|&&l| l != 0).count()
196+}
197+
132 /// Encode one transform block's levels.198 /// Encode one transform block's levels.
133 ///199 ///
134 /// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma200 /// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma
@@ -140,6 +206,7 @@ pub fn encode_residual(
140 log2_size: u32,206 log2_size: u32,
141 c_idx: usize,207 c_idx: usize,
142 scan_idx: usize,208 scan_idx: usize,
209+ sign_hiding: bool,
143 ) {210 ) {
144 let n = 1usize << log2_size;211 let n = 1usize << log2_size;
145 let sub_wide = n >> 2;212 let sub_wide = n >> 2;
@@ -310,9 +377,16 @@ pub fn encode_residual(
310 enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));377 enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));
311 }378 }
312 379
313- // Signs, then the remaining magnitudes. Sign data hiding is off, so380+ // Signs, then the remaining magnitudes. With sign data hiding on and
314- // every significant coefficient carries its own sign bit.381+ // the significant coefficients of this sub-block more than three scan
315- for &p in order {382+ // positions apart, the first one's sign is not coded at all: the
383+ // decoder reads it off the parity of the sub-block's absolute levels,
384+ // which `hide_signs` has already made match.
385+ let hidden = sign_hiding && order[0] - order[order_len - 1] > 3;
386+ for (k, &p) in order.iter().enumerate() {
387+ if hidden && k == order_len - 1 {
388+ continue;
389+ }
316 let (xp, yp) = pos_scan[p];390 let (xp, yp) = pos_scan[p];
317 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];391 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];
318 enc.encode_bypass(u32::from(level < 0));392 enc.encode_bypass(u32::from(level < 0));
@@ -491,7 +565,7 @@ mod tests {
491 let mut costs = Vec::new();565 let mut costs = Vec::new();
492 for levels in [&sparse, &dense] {566 for levels in [&sparse, &dense] {
493 let mut enc = CabacEncoder::counter(Contexts::new(30));567 let mut enc = CabacEncoder::counter(Contexts::new(30));
494- encode_residual(&mut enc, levels, 3, 0, 0);568+ encode_residual(&mut enc, levels, 3, 0, 0, false);
495 costs.push(enc.bit_count());569 costs.push(enc.bit_count());
496 }570 }
497 assert!(costs[0] < costs[1], "{costs:?}");571 assert!(costs[0] < costs[1], "{costs:?}");
@@ -517,7 +591,7 @@ mod tests {
517 };591 };
518 }592 }
519 let mut enc = CabacEncoder::counter(Contexts::new(27));593 let mut enc = CabacEncoder::counter(Contexts::new(27));
520- encode_residual(&mut enc, &levels, log2, c_idx, scan_idx);594+ encode_residual(&mut enc, &levels, log2, c_idx, scan_idx, false);
521 assert!(enc.bit_count() > 0);595 assert!(enc.bit_count() > 0);
522 }596 }
523 }597 }
crates/ec-h265/src/transform.rsmodified+10 -0
@@ -293,6 +293,16 @@ pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize
293 nonzero293 nonzero
294 }294 }
295 295
296+/// The unrounded level a coefficient would quantise to: the quantiser divides
297+/// by a step, and this is that division carried out in full precision. Sign
298+/// data hiding needs it to tell which coefficient is cheapest to nudge.
299+pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> f64 {
300+ let log2n = n.trailing_zeros() as i32;
301+ let qbits = 21 + qp / 6 - log2n;
302+ let scale = QUANT_SCALE[(qp % 6) as usize] as f64;
303+ (coeff.unsigned_abs() as f64 * scale) / (1u64 << qbits) as f64
304+}
305+
296 /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.306 /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.
297 pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {307 pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
298 let log2n = n.trailing_zeros() as i32;308 let log2n = n.trailing_zeros() as i32;
crates/ec-h265/tests/conformance.rsmodified+52 -0
@@ -203,6 +203,58 @@ fn intra_nxn_decodes_bit_exactly() {
203 }203 }
204 }204 }
205 205
206+/// Sign data hiding drops one bypass bin per qualifying sub-block and pays for
207+/// it by nudging a level, so the encoder and the decoder only agree if the
208+/// parity the encoder wrote is the parity the decoder reads. The stream has to
209+/// differ from the hiding-off one, and ffmpeg's decode has to match the
210+/// encoder's reconstruction sample for sample.
211+///
212+/// Size is deliberately not asserted here: hiding is not optional per
213+/// sub-block, so a single small picture can come out a few bytes longer when
214+/// the nudges cost more than the signs saved. Whether it pays is what the
215+/// `EC_H265_SDH` arm of the clip gate measures.
216+#[test]
217+fn sign_hiding_decodes_bit_exactly() {
218+ if !have_ffmpeg() {
219+ eprintln!("skipping: ffmpeg not installed");
220+ return;
221+ }
222+ for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] {
223+ let (source, coded) = encode_sdh(w, h, 22, true);
224+ let (_, plain) = encode_sdh(w, h, 22, false);
225+ let name = format!("sign-hiding-{w}x{h}");
226+ assert_ne!(
227+ coded.au, plain.au,
228+ "{name}: no sub-block ever qualified, so this decode proves nothing"
229+ );
230+ let path = write_au(&name, &coded);
231+ let decoded = match ffmpeg_decode(&path) {
232+ Ok(bytes) => bytes,
233+ Err(e) => panic!("{name}: ffmpeg failed: {e}"),
234+ };
235+ let recon = planes_of(coded.recon.as_ref().expect("recon kept"));
236+ assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch");
237+ let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count();
238+ assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ");
239+ let quality = psnr(&planes_of(&source), &recon);
240+ assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22");
241+ }
242+}
243+
244+/// The natural frame coded with sign data hiding on or off, everything else
245+/// left at its default.
246+fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) {
247+ let mut cfg = EncoderConfig::new(width, height);
248+ cfg.sign_hiding = sign_hiding;
249+ cfg.rate_control = RateControl::ConstantQp(qp);
250+ cfg.keep_recon = true;
251+ cfg.picture_hash = true;
252+ let encoder = Encoder::new(cfg).expect("encoder");
253+ let frame = natural_frame(width, height, 0);
254+ let coded = encoder.encode_idr(&frame).expect("encode");
255+ (frame, coded)
256+}
257+
206 #[test]258 #[test]
207 fn ffmpeg_decodes_bit_exactly_at_every_shape() {259 fn ffmpeg_decodes_bit_exactly_at_every_shape() {
208 if !have_ffmpeg() {260 if !have_ffmpeg() {
crates/ec-h265/tests/encode.rsmodified+3 -0
@@ -435,6 +435,9 @@ fn bd_psnr_vs_x265() {
435 if let Ok(w) = std::env::var("EC_H265_CHROMA_W") {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");436 cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number");
437 }437 }
438+ if let Ok(v) = std::env::var("EC_H265_SDH") {
439+ cfg.sign_hiding = v != "0";
440+ }
438 if let Ok(v) = std::env::var("EC_H265_NXN") {441 if let Ok(v) = std::env::var("EC_H265_NXN") {
439 cfg.intra_nxn = v != "0";442 cfg.intra_nxn = v != "0";
440 }443 }