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 @@
2424
2525 use crate::cabac::{CabacEncoder, CabacState, ctx};
2626 use crate::intra::{self, Availability, Refs};
27-use crate::residual::encode_residual;
27+use crate::residual::{self, encode_residual};
2828 use crate::transform::{
2929 chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst,
3030 };
@@ -150,6 +150,7 @@ pub struct CtuEncoder<'a> {
150150 chroma_rd_weight: f64,
151151 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions.
152152 intra_nxn: bool,
153+ sign_hiding: bool,
153154 /// `log2` of the smallest coding unit the search will produce.
154155 min_cb_log2: u32,
155156 /// Intra mode per 4x4 block of the band; 255 = not coded yet.
@@ -181,6 +182,7 @@ impl<'a> CtuEncoder<'a> {
181182 chroma_rd: bool,
182183 chroma_rd_weight: f64,
183184 intra_nxn: bool,
185+ sign_hiding: bool,
184186 min_cb_log2: u32,
185187 ) -> CtuEncoder<'a> {
186188 let band_rows = (height - band_y0).min(ctb_size);
@@ -201,6 +203,7 @@ impl<'a> CtuEncoder<'a> {
201203 chroma_rd,
202204 chroma_rd_weight,
203205 intra_nxn,
206+ sign_hiding,
204207 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
205208 modes: vec![255; (width / 4) * (ctb_size / 4)],
206209 depths: vec![0; (width / 4) * (ctb_size / 4)],
@@ -572,18 +575,18 @@ impl<'a> CtuEncoder<'a> {
572575 enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part]));
573576 if cbfs[part] {
574577 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);
576579 }
577580 if part == 3 {
578581 let chroma_scan = intra::scan_index(chroma_mode, 2, false);
579582 if cb_cbf {
580583 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);
582585 self.scratch.cb_levels = l;
583586 }
584587 if cr_cbf {
585588 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);
587590 self.scratch.cr_levels = l;
588591 }
589592 }
@@ -629,18 +632,32 @@ impl<'a> CtuEncoder<'a> {
629632 if luma_cbf {
630633 let scan = intra::scan_index(mode, log2, true);
631634 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);
633636 self.scratch.luma_levels = levels;
634637 }
635638 let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false);
636639 if cb_cbf {
637640 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+ );
639649 self.scratch.cb_levels = levels;
640650 }
641651 if cr_cbf {
642652 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+ );
644661 self.scratch.cr_levels = levels;
645662 }
646663
@@ -825,7 +842,7 @@ impl<'a> CtuEncoder<'a> {
825842 if cbf {
826843 let scan = intra::scan_index(mode, log2, true);
827844 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);
829846 self.scratch.levels = levels;
830847 }
831848 let bits = enc.bit_count() - bits_before;
@@ -866,7 +883,16 @@ impl<'a> CtuEncoder<'a> {
866883 }
867884 let dst = uses_dst(n, true);
868885 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+ }
870896 let cbf = nonzero > 0;
871897 if cbf {
872898 dequantize(&self.scratch.levels, &mut self.scratch.scaled, n, self.qp);
@@ -916,12 +942,21 @@ impl<'a> CtuEncoder<'a> {
916942 }
917943 }
918944 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
919- let nonzero = quantize(
945+ let mut nonzero = quantize(
920946 &self.scratch.coeffs,
921947 &mut self.scratch.levels,
922948 cn,
923949 self.qp_c,
924950 );
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+ }
925960 let cbf = nonzero > 0;
926961 if cbf {
927962 dequantize(
@@ -1010,12 +1045,26 @@ impl<'a> CtuEncoder<'a> {
10101045 let scan = intra::scan_index(mode, log2 - 1, false);
10111046 if cb_cbf {
10121047 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+ );
10141056 self.scratch.cb_levels = levels;
10151057 }
10161058 if cr_cbf {
10171059 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+ );
10191068 self.scratch.cr_levels = levels;
10201069 }
10211070 let bits = enc.bit_count() - bits_before;
crates/ec-h265/src/encoder.rsmodified+15 -0
@@ -132,6 +132,18 @@ pub struct EncoderConfig {
132132 /// capture (-2.619 dB against x265 without it, -0.479 dB with) and
133133 /// +0.007 dB on 1080p film, so it never loses.
134134 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,
135147 /// What the samples mean, written into the VUI.
136148 pub video_signal_type: Option<VideoSignalType>,
137149 /// Sample aspect ratio.
@@ -161,6 +173,7 @@ impl EncoderConfig {
161173 chroma_rd_weight: 1.0,
162174 min_cu_size: 8,
163175 intra_nxn: true,
176+ sign_hiding: false,
164177 video_signal_type: None,
165178 sample_aspect_ratio: None,
166179 timing: None,
@@ -289,6 +302,7 @@ impl Encoder {
289302 // changing what either side predicts from. Turning them off buys
290303 // that identity (and the picture-hash check that rides on it)
291304 // rather than a fraction of a dB.
305+ sign_data_hiding_enabled: cfg.sign_hiding,
292306 deblocking_filter_control_present: true,
293307 deblocking_filter_disabled: true,
294308 loop_filter_across_slices_enabled: false,
@@ -536,6 +550,7 @@ impl Encoder {
536550 self.cfg.chroma_mode_search,
537551 self.cfg.chroma_rd_weight,
538552 self.cfg.intra_nxn,
553+ self.cfg.sign_hiding,
539554 self.cfg.min_cu_size.max(8).trailing_zeros(),
540555 );
541556 for col in 0..cols {
crates/ec-h265/src/residual.rsmodified+79 -5
@@ -1,6 +1,7 @@
11 //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5).
22
33 use crate::cabac::{CabacEncoder, ctx};
4+use crate::transform::ideal_level;
45 use std::sync::LazyLock;
56
67 /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`.
@@ -129,6 +130,71 @@ fn last_prefix(coord: u32) -> (u32, u32) {
129130 }
130131 }
131132
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+
132198 /// Encode one transform block's levels.
133199 ///
134200 /// `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(
140206 log2_size: u32,
141207 c_idx: usize,
142208 scan_idx: usize,
209+ sign_hiding: bool,
143210 ) {
144211 let n = 1usize << log2_size;
145212 let sub_wide = n >> 2;
@@ -310,9 +377,16 @@ pub fn encode_residual(
310377 enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));
311378 }
312379
313- // Signs, then the remaining magnitudes. Sign data hiding is off, so
314- // every significant coefficient carries its own sign bit.
315- for &p in order {
380+ // Signs, then the remaining magnitudes. With sign data hiding on and
381+ // the significant coefficients of this sub-block more than three scan
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+ }
316390 let (xp, yp) = pos_scan[p];
317391 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];
318392 enc.encode_bypass(u32::from(level < 0));
@@ -491,7 +565,7 @@ mod tests {
491565 let mut costs = Vec::new();
492566 for levels in [&sparse, &dense] {
493567 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);
495569 costs.push(enc.bit_count());
496570 }
497571 assert!(costs[0] < costs[1], "{costs:?}");
@@ -517,7 +591,7 @@ mod tests {
517591 };
518592 }
519593 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);
521595 assert!(enc.bit_count() > 0);
522596 }
523597 }
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
293293 nonzero
294294 }
295295
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+
296306 /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.
297307 pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
298308 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() {
203203 }
204204 }
205205
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+
206258 #[test]
207259 fn ffmpeg_decodes_bit_exactly_at_every_shape() {
208260 if !have_ffmpeg() {
crates/ec-h265/tests/encode.rsmodified+3 -0
@@ -435,6 +435,9 @@ fn bd_psnr_vs_x265() {
435435 if let Ok(w) = std::env::var("EC_H265_CHROMA_W") {
436436 cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number");
437437 }
438+ if let Ok(v) = std::env::var("EC_H265_SDH") {
439+ cfg.sign_hiding = v != "0";
440+ }
438441 if let Ok(v) = std::env::var("EC_H265_NXN") {
439442 cfg.intra_nxn = v != "0";
440443 }