From 0877a3629ced29df5b301e4a4363db04d8c6810d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 25 Aug 2026 05:02:53 +0300 Subject: [PATCH] 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.rs | 73 ++++++++++++++++++++----- crates/ec-h265/src/encoder.rs | 15 ++++++ crates/ec-h265/src/residual.rs | 84 +++++++++++++++++++++++++++-- crates/ec-h265/src/transform.rs | 10 ++++ crates/ec-h265/tests/conformance.rs | 52 ++++++++++++++++++ crates/ec-h265/tests/encode.rs | 3 ++ 6 files changed, 220 insertions(+), 17 deletions(-) diff --git a/crates/ec-h265/src/ctu.rs b/crates/ec-h265/src/ctu.rs index fa7bd59a..01c51afb 100644 --- a/crates/ec-h265/src/ctu.rs +++ b/crates/ec-h265/src/ctu.rs @@ -24,7 +24,7 @@ use crate::cabac::{CabacEncoder, CabacState, ctx}; use crate::intra::{self, Availability, Refs}; -use crate::residual::encode_residual; +use crate::residual::{self, encode_residual}; use crate::transform::{ chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst, }; @@ -150,6 +150,7 @@ pub struct CtuEncoder<'a> { chroma_rd_weight: f64, /// Whether an 8x8 coding unit may split into four 4x4 intra partitions. intra_nxn: bool, + sign_hiding: bool, /// `log2` of the smallest coding unit the search will produce. min_cb_log2: u32, /// Intra mode per 4x4 block of the band; 255 = not coded yet. @@ -181,6 +182,7 @@ impl<'a> CtuEncoder<'a> { chroma_rd: bool, chroma_rd_weight: f64, intra_nxn: bool, + sign_hiding: bool, min_cb_log2: u32, ) -> CtuEncoder<'a> { let band_rows = (height - band_y0).min(ctb_size); @@ -201,6 +203,7 @@ impl<'a> CtuEncoder<'a> { chroma_rd, chroma_rd_weight, intra_nxn, + sign_hiding, min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), modes: vec![255; (width / 4) * (ctb_size / 4)], depths: vec![0; (width / 4) * (ctb_size / 4)], @@ -572,18 +575,18 @@ impl<'a> CtuEncoder<'a> { enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part])); if cbfs[part] { let scan = intra::scan_index(modes[part], 2, true); - encode_residual(enc, &levels[part], 2, 0, scan); + encode_residual(enc, &levels[part], 2, 0, scan, self.sign_hiding); } if part == 3 { let chroma_scan = intra::scan_index(chroma_mode, 2, false); if cb_cbf { let l = std::mem::take(&mut self.scratch.cb_levels); - encode_residual(enc, &l[..16], 2, 1, chroma_scan); + encode_residual(enc, &l[..16], 2, 1, chroma_scan, self.sign_hiding); self.scratch.cb_levels = l; } if cr_cbf { let l = std::mem::take(&mut self.scratch.cr_levels); - encode_residual(enc, &l[..16], 2, 2, chroma_scan); + encode_residual(enc, &l[..16], 2, 2, chroma_scan, self.sign_hiding); self.scratch.cr_levels = l; } } @@ -629,18 +632,32 @@ impl<'a> CtuEncoder<'a> { if luma_cbf { let scan = intra::scan_index(mode, log2, true); let levels = std::mem::take(&mut self.scratch.luma_levels); - encode_residual(enc, &levels[..n * n], log2, 0, scan); + encode_residual(enc, &levels[..n * n], log2, 0, scan, self.sign_hiding); self.scratch.luma_levels = levels; } let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false); if cb_cbf { let levels = std::mem::take(&mut self.scratch.cb_levels); - encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan); + encode_residual( + enc, + &levels[..n * n / 4], + log2 - 1, + 1, + chroma_scan, + self.sign_hiding, + ); self.scratch.cb_levels = levels; } if cr_cbf { let levels = std::mem::take(&mut self.scratch.cr_levels); - encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, chroma_scan); + encode_residual( + enc, + &levels[..n * n / 4], + log2 - 1, + 2, + chroma_scan, + self.sign_hiding, + ); self.scratch.cr_levels = levels; } @@ -825,7 +842,7 @@ impl<'a> CtuEncoder<'a> { if cbf { let scan = intra::scan_index(mode, log2, true); let levels = std::mem::take(&mut self.scratch.levels); - encode_residual(enc, &levels[..n * n], log2, 0, scan); + encode_residual(enc, &levels[..n * n], log2, 0, scan, self.sign_hiding); self.scratch.levels = levels; } let bits = enc.bit_count() - bits_before; @@ -866,7 +883,16 @@ impl<'a> CtuEncoder<'a> { } let dst = uses_dst(n, true); forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst); - let nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp); + let mut nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp); + if self.sign_hiding && nonzero > 0 { + nonzero = residual::hide_signs( + &self.scratch.coeffs, + &mut self.scratch.levels, + n, + self.qp, + intra::scan_index(mode, n.trailing_zeros(), true), + ); + } let cbf = nonzero > 0; if cbf { dequantize(&self.scratch.levels, &mut self.scratch.scaled, n, self.qp); @@ -916,12 +942,21 @@ impl<'a> CtuEncoder<'a> { } } forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false); - let nonzero = quantize( + let mut nonzero = quantize( &self.scratch.coeffs, &mut self.scratch.levels, cn, self.qp_c, ); + if self.sign_hiding && nonzero > 0 { + nonzero = residual::hide_signs( + &self.scratch.coeffs, + &mut self.scratch.levels, + cn, + self.qp_c, + intra::scan_index(pred_mode, cn.trailing_zeros(), false), + ); + } let cbf = nonzero > 0; if cbf { dequantize( @@ -1010,12 +1045,26 @@ impl<'a> CtuEncoder<'a> { let scan = intra::scan_index(mode, log2 - 1, false); if cb_cbf { let levels = std::mem::take(&mut self.scratch.cb_levels); - encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, scan); + encode_residual( + enc, + &levels[..n * n / 4], + log2 - 1, + 1, + scan, + self.sign_hiding, + ); self.scratch.cb_levels = levels; } if cr_cbf { let levels = std::mem::take(&mut self.scratch.cr_levels); - encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, scan); + encode_residual( + enc, + &levels[..n * n / 4], + log2 - 1, + 2, + scan, + self.sign_hiding, + ); self.scratch.cr_levels = levels; } let bits = enc.bit_count() - bits_before; diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index 5f0a1c35..f20451e5 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -132,6 +132,18 @@ pub struct EncoderConfig { /// capture (-2.619 dB against x265 without it, -0.479 dB with) and /// +0.007 dB on 1080p film, so it never loses. pub intra_nxn: bool, + + /// Whether a sub-block's first sign is hidden in the parity of its + /// absolute levels (`sign_data_hiding_enabled_flag`). Buys one bypass bin + /// per qualifying sub-block for a level nudged by one. + /// + /// Off: measured at -0.033 dB BD-PSNR on a 2560x1440 screen capture and + /// -0.043 dB on 1080p film. Hiding is not optional per sub-block, so every + /// qualifying one pays for the bin whether the nudge is cheap or not, and + /// with levels that come straight from the quantiser's rounding the nudges + /// cost more than the signs save. Worth re-measuring once RDOQ lands: that + /// is where the gain in other encoders comes from. + pub sign_hiding: bool, /// What the samples mean, written into the VUI. pub video_signal_type: Option, /// Sample aspect ratio. @@ -161,6 +173,7 @@ impl EncoderConfig { chroma_rd_weight: 1.0, min_cu_size: 8, intra_nxn: true, + sign_hiding: false, video_signal_type: None, sample_aspect_ratio: None, timing: None, @@ -289,6 +302,7 @@ impl Encoder { // changing what either side predicts from. Turning them off buys // that identity (and the picture-hash check that rides on it) // rather than a fraction of a dB. + sign_data_hiding_enabled: cfg.sign_hiding, deblocking_filter_control_present: true, deblocking_filter_disabled: true, loop_filter_across_slices_enabled: false, @@ -536,6 +550,7 @@ impl Encoder { self.cfg.chroma_mode_search, self.cfg.chroma_rd_weight, self.cfg.intra_nxn, + self.cfg.sign_hiding, self.cfg.min_cu_size.max(8).trailing_zeros(), ); for col in 0..cols { diff --git a/crates/ec-h265/src/residual.rs b/crates/ec-h265/src/residual.rs index eb129ba9..95ae6840 100644 --- a/crates/ec-h265/src/residual.rs +++ b/crates/ec-h265/src/residual.rs @@ -1,6 +1,7 @@ //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5). use crate::cabac::{CabacEncoder, ctx}; +use crate::transform::ideal_level; use std::sync::LazyLock; /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`. @@ -129,6 +130,71 @@ fn last_prefix(coord: u32) -> (u32, u32) { } } +/// Make each sub-block's absolute levels carry the sign of its first +/// significant coefficient, so that sign need not be coded (7.3.8.11, the +/// `sign_data_hiding_enabled_flag` path). A sub-block qualifies when its first +/// and last significant coefficients are more than three scan positions apart; +/// where the parity is wrong, one level is nudged by one, the cheapest being +/// whichever coefficient the quantiser rounded furthest in that direction. +/// +/// This runs on the levels before they are dequantised, so the encoder's own +/// reconstruction is built from what the decoder will read back. +pub fn hide_signs(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32, scan_idx: usize) -> usize { + let log2_size = n.trailing_zeros(); + let sub_scan = scan(log2_size - 2, scan_idx); + let pos_scan = scan(2, scan_idx); + for &(xs, ys) in sub_scan { + let (xs, ys) = (xs as usize, ys as usize); + let at = |p: usize| { + let (xp, yp) = pos_scan[p]; + (ys * 4 + yp as usize) * n + xs * 4 + xp as usize + }; + let Some(first) = (0..16).find(|&p| levels[at(p)] != 0) else { + continue; + }; + let last = (0..16).rev().find(|&p| levels[at(p)] != 0).unwrap_or(first); + if last - first <= 3 { + continue; + } + let sum: i32 = (0..16).map(|p| levels[at(p)].abs()).sum(); + let negative = levels[at(first)] < 0; + if (sum & 1 == 1) == negative { + continue; + } + // The parity is wrong. Changing any level by one fixes it; take the + // one whose rounding error the change reduces most (or grows least). + // Only levels that stay non-zero are considered, so no coefficient + // enters or leaves the block and the scan positions above still hold. + let mut best: Option<(f64, usize, i32)> = None; + for p in 0..16 { + let i = at(p); + let level = levels[i]; + if level == 0 { + continue; + } + let magnitude = f64::from(level.abs()); + let ideal = ideal_level(coeffs[i], n, qp); + // Distortion alone picks the coefficient: a rate bias favouring + // decrements (or increments) was swept through the clip gate at + // +-0.25 and +-0.5 units of squared level error per bit and lost + // in both directions, so there is none. + let mut consider = |cost: f64, delta: i32| { + if best.is_none_or(|(b, _, _)| cost < b) { + best = Some((cost, i, delta)); + } + }; + consider(1.0 - 2.0 * (ideal - magnitude), 1); + if level.abs() > 1 { + consider(1.0 + 2.0 * (ideal - magnitude), -1); + } + } + if let Some((_, i, delta)) = best { + levels[i] += if levels[i] < 0 { -delta } else { delta }; + } + } + levels[..n * n].iter().filter(|&&l| l != 0).count() +} + /// Encode one transform block's levels. /// /// `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( log2_size: u32, c_idx: usize, scan_idx: usize, + sign_hiding: bool, ) { let n = 1usize << log2_size; let sub_wide = n >> 2; @@ -310,9 +377,16 @@ pub fn encode_residual( enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2)); } - // Signs, then the remaining magnitudes. Sign data hiding is off, so - // every significant coefficient carries its own sign bit. - for &p in order { + // Signs, then the remaining magnitudes. With sign data hiding on and + // the significant coefficients of this sub-block more than three scan + // positions apart, the first one's sign is not coded at all: the + // decoder reads it off the parity of the sub-block's absolute levels, + // which `hide_signs` has already made match. + let hidden = sign_hiding && order[0] - order[order_len - 1] > 3; + for (k, &p) in order.iter().enumerate() { + if hidden && k == order_len - 1 { + continue; + } let (xp, yp) = pos_scan[p]; let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize]; enc.encode_bypass(u32::from(level < 0)); @@ -491,7 +565,7 @@ mod tests { let mut costs = Vec::new(); for levels in [&sparse, &dense] { let mut enc = CabacEncoder::counter(Contexts::new(30)); - encode_residual(&mut enc, levels, 3, 0, 0); + encode_residual(&mut enc, levels, 3, 0, 0, false); costs.push(enc.bit_count()); } assert!(costs[0] < costs[1], "{costs:?}"); @@ -517,7 +591,7 @@ mod tests { }; } let mut enc = CabacEncoder::counter(Contexts::new(27)); - encode_residual(&mut enc, &levels, log2, c_idx, scan_idx); + encode_residual(&mut enc, &levels, log2, c_idx, scan_idx, false); assert!(enc.bit_count() > 0); } } diff --git a/crates/ec-h265/src/transform.rs b/crates/ec-h265/src/transform.rs index 0995ae74..6b923ab9 100644 --- a/crates/ec-h265/src/transform.rs +++ b/crates/ec-h265/src/transform.rs @@ -293,6 +293,16 @@ pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize nonzero } +/// The unrounded level a coefficient would quantise to: the quantiser divides +/// by a step, and this is that division carried out in full precision. Sign +/// data hiding needs it to tell which coefficient is cheapest to nudge. +pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> f64 { + let log2n = n.trailing_zeros() as i32; + let qbits = 21 + qp / 6 - log2n; + let scale = QUANT_SCALE[(qp % 6) as usize] as f64; + (coeff.unsigned_abs() as f64 * scale) / (1u64 << qbits) as f64 +} + /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies. pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) { let log2n = n.trailing_zeros() as i32; diff --git a/crates/ec-h265/tests/conformance.rs b/crates/ec-h265/tests/conformance.rs index 40e442e3..3ccc9dea 100644 --- a/crates/ec-h265/tests/conformance.rs +++ b/crates/ec-h265/tests/conformance.rs @@ -203,6 +203,58 @@ fn intra_nxn_decodes_bit_exactly() { } } +/// Sign data hiding drops one bypass bin per qualifying sub-block and pays for +/// it by nudging a level, so the encoder and the decoder only agree if the +/// parity the encoder wrote is the parity the decoder reads. The stream has to +/// differ from the hiding-off one, and ffmpeg's decode has to match the +/// encoder's reconstruction sample for sample. +/// +/// Size is deliberately not asserted here: hiding is not optional per +/// sub-block, so a single small picture can come out a few bytes longer when +/// the nudges cost more than the signs saved. Whether it pays is what the +/// `EC_H265_SDH` arm of the clip gate measures. +#[test] +fn sign_hiding_decodes_bit_exactly() { + if !have_ffmpeg() { + eprintln!("skipping: ffmpeg not installed"); + return; + } + for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { + let (source, coded) = encode_sdh(w, h, 22, true); + let (_, plain) = encode_sdh(w, h, 22, false); + let name = format!("sign-hiding-{w}x{h}"); + assert_ne!( + coded.au, plain.au, + "{name}: no sub-block ever qualified, so this decode proves nothing" + ); + let path = write_au(&name, &coded); + let decoded = match ffmpeg_decode(&path) { + Ok(bytes) => bytes, + Err(e) => panic!("{name}: ffmpeg failed: {e}"), + }; + let recon = planes_of(coded.recon.as_ref().expect("recon kept")); + assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); + let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); + assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + let quality = psnr(&planes_of(&source), &recon); + assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); + } +} + +/// The natural frame coded with sign data hiding on or off, everything else +/// left at its default. +fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) { + let mut cfg = EncoderConfig::new(width, height); + cfg.sign_hiding = sign_hiding; + cfg.rate_control = RateControl::ConstantQp(qp); + cfg.keep_recon = true; + cfg.picture_hash = true; + let encoder = Encoder::new(cfg).expect("encoder"); + let frame = natural_frame(width, height, 0); + let coded = encoder.encode_idr(&frame).expect("encode"); + (frame, coded) +} + #[test] fn ffmpeg_decodes_bit_exactly_at_every_shape() { if !have_ffmpeg() { diff --git a/crates/ec-h265/tests/encode.rs b/crates/ec-h265/tests/encode.rs index ae892d78..062572ec 100644 --- a/crates/ec-h265/tests/encode.rs +++ b/crates/ec-h265/tests/encode.rs @@ -435,6 +435,9 @@ fn bd_psnr_vs_x265() { if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); } + if let Ok(v) = std::env::var("EC_H265_SDH") { + cfg.sign_hiding = v != "0"; + } if let Ok(v) = std::env::var("EC_H265_NXN") { cfg.intra_nxn = v != "0"; }