diff --git a/crates/ec-h265/src/ctu.rs b/crates/ec-h265/src/ctu.rs index 01c51afb..c01cc0c9 100644 --- a/crates/ec-h265/src/ctu.rs +++ b/crates/ec-h265/src/ctu.rs @@ -22,14 +22,32 @@ //! which this encoder spends on the wavefront that makes one `encode` call use //! every core instead. -use crate::cabac::{CabacEncoder, CabacState, ctx}; +use crate::cabac::{CabacEncoder, CabacState, Contexts, ctx}; use crate::intra::{self, Availability, Refs}; use crate::residual::{self, encode_residual}; use crate::transform::{ - chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst, + chroma_qp, dequantize, forward_transform, inverse_transform, quantize, quantize_offset, + uses_dst, }; use std::sync::atomic::{AtomicU8, Ordering}; +/// The rounding the rate-distortion level search starts from, as a divisor of +/// the quantiser step: 2 is round-to-nearest, against the 3 the plain path +/// uses. A search that only takes levels down measures the rounding it was +/// handed, so it gets the wider one. Swept on 1080p film at the settled +/// lambda: 1/2 +0.360 dB BD-PSNR against x265, 1/3 +0.315, 1/4 +0.118. +const RDOQ_DEAD_ZONE: i64 = 2; + +/// The same rounding for the chroma path, swept on its own because the sparser +/// chroma of an intra picture answered differently in ec-h264. +/// +/// Here it does not: coarser chroma rounding reads better and better on luma +/// BD-PSNR (1/2 +0.360, 1/6 +0.525, 1/12 +0.568, 1/24 +0.585 dB) while the +/// all-plane figure falls the whole way (+0.276, +0.231, +0.169, +0.128). That +/// arm is chroma being starved to buy luma bits, which only a luma-only metric +/// calls a gain, so chroma keeps luma's rounding. +const RDOQ_DEAD_ZONE_C: i64 = 2; + /// `log2` of the smallest coding block this encoder makes: 8x8. pub const MIN_CB_LOG2: u32 = 3; @@ -151,6 +169,10 @@ pub struct CtuEncoder<'a> { /// Whether an 8x8 coding unit may split into four 4x4 intra partitions. intra_nxn: bool, sign_hiding: bool, + /// Whether the levels get a rate-distortion search after quantisation. + rdoq: bool, + /// The counting CABAC engine that search prices its trials with. + rdoq_enc: CabacEncoder, /// `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. @@ -183,6 +205,7 @@ impl<'a> CtuEncoder<'a> { chroma_rd_weight: f64, intra_nxn: bool, sign_hiding: bool, + rdoq: bool, min_cb_log2: u32, ) -> CtuEncoder<'a> { let band_rows = (height - band_y0).min(ctb_size); @@ -204,6 +227,8 @@ impl<'a> CtuEncoder<'a> { chroma_rd_weight, intra_nxn, sign_hiding, + rdoq, + rdoq_enc: CabacEncoder::counter(Contexts::new(qp)), 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)], @@ -883,7 +908,30 @@ impl<'a> CtuEncoder<'a> { } let dst = uses_dst(n, true); forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst); - let mut nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp); + let mut nonzero = if self.rdoq { + quantize_offset( + &self.scratch.coeffs, + &mut self.scratch.levels, + n, + self.qp, + RDOQ_DEAD_ZONE, + ) + } else { + quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp) + }; + if self.rdoq && nonzero > 0 { + nonzero = residual::rdoq( + &self.scratch.coeffs, + &mut self.scratch.levels, + n, + self.qp, + 0, + intra::scan_index(mode, n.trailing_zeros(), true), + ctx::CBF_LUMA + 1, + self.lambda, + &mut self.rdoq_enc, + ); + } if self.sign_hiding && nonzero > 0 { nonzero = residual::hide_signs( &self.scratch.coeffs, @@ -942,12 +990,35 @@ impl<'a> CtuEncoder<'a> { } } forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false); - let mut nonzero = quantize( - &self.scratch.coeffs, - &mut self.scratch.levels, - cn, - self.qp_c, - ); + let mut nonzero = if self.rdoq { + quantize_offset( + &self.scratch.coeffs, + &mut self.scratch.levels, + cn, + self.qp_c, + RDOQ_DEAD_ZONE_C, + ) + } else { + quantize( + &self.scratch.coeffs, + &mut self.scratch.levels, + cn, + self.qp_c, + ) + }; + if self.rdoq && nonzero > 0 { + nonzero = residual::rdoq( + &self.scratch.coeffs, + &mut self.scratch.levels, + cn, + self.qp_c, + plane, + intra::scan_index(pred_mode, cn.trailing_zeros(), false), + ctx::CBF_CHROMA, + self.lambda, + &mut self.rdoq_enc, + ); + } if self.sign_hiding && nonzero > 0 { nonzero = residual::hide_signs( &self.scratch.coeffs, diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index f20451e5..4fd87c1f 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -144,6 +144,17 @@ pub struct EncoderConfig { /// 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, + + /// Whether quantised levels get a rate-distortion search (RDOQ) that + /// offers each small level the magnitudes below it and takes one when the + /// squared error it gives up costs less than the bits it saves. + /// + /// On: worth +0.122 dB BD-PSNR on a 2560x1440 screen capture (-0.479 -> + /// -0.357 against x265) and +0.114 dB on 1080p film (+0.246 -> +0.360), + /// with the all-plane figures moving the same way. The rate is the CABAC + /// coder's own price for the whole block, so dropping a level is priced + /// with the significance map and last position that follow from it. + pub rdoq: bool, /// What the samples mean, written into the VUI. pub video_signal_type: Option, /// Sample aspect ratio. @@ -174,6 +185,7 @@ impl EncoderConfig { min_cu_size: 8, intra_nxn: true, sign_hiding: false, + rdoq: true, video_signal_type: None, sample_aspect_ratio: None, timing: None, @@ -551,6 +563,7 @@ impl Encoder { self.cfg.chroma_rd_weight, self.cfg.intra_nxn, self.cfg.sign_hiding, + self.cfg.rdoq, 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 95ae6840..56ac8f0c 100644 --- a/crates/ec-h265/src/residual.rs +++ b/crates/ec-h265/src/residual.rs @@ -1,7 +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 crate::cabac::{CabacEncoder, CabacState, ctx}; +use crate::transform::{coeff_ssd_scale, dequant_level, ideal_level}; use std::sync::LazyLock; /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`. @@ -195,6 +195,139 @@ pub fn hide_signs(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32, scan_id levels[..n * n].iter().filter(|&&l| l != 0).count() } +/// The largest level the rate-distortion search offers a smaller magnitude to. +/// +/// A big level carries real signal and never wins by shrinking, so bounding +/// the search is what keeps it affordable: every trial re-codes the whole +/// block. Swept on 1080p film, BD-PSNR-YUV against x265: 1 gives +0.244, the 2 +/// kept here +0.276, and 3 +0.277 for strictly more trials. +const RDOQ_MAX_LEVEL: i32 = 2; + +/// How much of the mode-decision lambda the level search uses. The bits are +/// the coder's own count, not an estimate, so the scale starts at 1. +/// +/// The two clips disagree above it and the disagreement is small: on +/// BD-PSNR-YUV against x265, 1080p film reads +0.276 at 1.0, +0.294 at 1.25 +/// and +0.293 at 1.5, while a 2560x1440 screen capture reads -0.392, -0.408 +/// and -0.441. The crossing sits just above 1.0, and the screen capture is the +/// content still behind x265, so it takes the tie. +const RDOQ_LAMBDA: f64 = 1.0; + +/// What one candidate set of levels costs in bits, priced by the CABAC coder +/// itself against `base`'s context state. +#[allow(clippy::too_many_arguments)] +fn levels_bits( + enc: &mut CabacEncoder, + base: &CabacState, + levels: &[i32], + log2_size: u32, + c_idx: usize, + scan_idx: usize, + cbf_ctx: usize, + coded: bool, +) -> u64 { + enc.restore(base); + let before = enc.bit_count(); + enc.encode_bin(cbf_ctx, u32::from(coded)); + if coded { + encode_residual(enc, levels, log2_size, c_idx, scan_idx, false); + } + enc.bit_count() - before +} + +/// Rate-distortion quantisation of one transform block: each small level is +/// offered the magnitudes below it, and takes one when the squared error it +/// gives up costs less than the bits it saves. +/// +/// The rate is the CABAC coder's own price for the whole block — `enc` is a +/// counting engine, and every trial is priced from the same context state — so +/// dropping a level is priced together with the significance map and the last +/// position that follow from it, which is where most of the saving is. The +/// distortion is the transform-domain error scaled back to samples by +/// [`coeff_ssd_scale`], so `lambda` is the caller's sample-domain lambda. +/// +/// Returns the number of non-zero levels left. +#[allow(clippy::too_many_arguments)] +pub fn rdoq( + coeffs: &[i32], + levels: &mut [i32], + n: usize, + qp: i32, + c_idx: usize, + scan_idx: usize, + cbf_ctx: usize, + lambda: f64, + enc: &mut CabacEncoder, +) -> usize { + let log2_size = n.trailing_zeros(); + let scale = coeff_ssd_scale(n); + let lambda = RDOQ_LAMBDA * lambda; + let base = enc.snapshot(); + let err = |level: i32, coeff: i32| { + let d = f64::from(dequant_level(level, n, qp) - coeff); + d * d + }; + + let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum(); + let bits = levels_bits( + enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, true, + ); + let mut cost = scale * dist + lambda * bits as f64; + + // Highest scanning position first: dropping the last significant level is + // what shortens the significance map and moves the coded last position, so + // it is tried while the levels above it are already gone. + let sub_scan = scan(log2_size - 2, scan_idx); + let pos_scan = scan(2, scan_idx); + let order: Vec = sub_scan + .iter() + .flat_map(|&(xs, ys)| { + pos_scan.iter().map(move |&(xp, yp)| { + (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize + }) + }) + .collect(); + for &i in order.iter().rev() { + let level = levels[i]; + if level == 0 || level.abs() > RDOQ_MAX_LEVEL { + continue; + } + let mut tried = level.abs(); + for candidate in [level.abs() - 1, 0] { + if candidate == tried { + continue; + } + tried = candidate; + let keep = levels[i]; + levels[i] = candidate * level.signum(); + let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]); + let any = levels[..n * n].iter().any(|&l| l != 0); + let trial_bits = + levels_bits(enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, any); + let trial = scale * trial_dist + lambda * trial_bits as f64; + if trial < cost { + cost = trial; + dist = trial_dist; + } else { + levels[i] = keep; + } + } + } + // And the block as a whole: zeroing it drops the coded-block flag as well + // as every level, which no single-coefficient step can see. + let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum(); + let zero_bits = levels_bits( + enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, false, + ); + if scale * zero_dist + lambda * zero_bits as f64 <= cost { + levels[..n * n].fill(0); + enc.restore(&base); + return 0; + } + enc.restore(&base); + 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 diff --git a/crates/ec-h265/src/transform.rs b/crates/ec-h265/src/transform.rs index 6b923ab9..10aff292 100644 --- a/crates/ec-h265/src/transform.rs +++ b/crates/ec-h265/src/transform.rs @@ -277,10 +277,27 @@ pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_typ /// encoder in this class uses: it costs a little distortion at the rounding /// boundary and buys back more in rate. pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize { + quantize_offset(coeffs, levels, n, qp, 3) +} + +/// [`quantize`] with the rounding written out: `dead_zone` is the divisor of +/// the quantiser step the rounding offset is, so 3 is the intra default and 2 +/// is round-to-nearest. +/// +/// A rate-distortion search over the levels wants the wider rounding: a search +/// that only ever takes levels down measures the rounding it started from, not +/// its own decisions. +pub fn quantize_offset( + coeffs: &[i32], + levels: &mut [i32], + n: usize, + qp: i32, + dead_zone: i64, +) -> usize { let log2n = n.trailing_zeros() as i32; let qbits = 21 + qp / 6 - log2n; let scale = QUANT_SCALE[(qp % 6) as usize] as i64; - let offset = (1i64 << qbits) / 3; + let offset = (1i64 << qbits) / dead_zone; let mut nonzero = 0; for (i, &c) in coeffs[..n * n].iter().enumerate() { let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32; @@ -305,15 +322,35 @@ pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> 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) { + for (i, &level) in levels[..n * n].iter().enumerate() { + scaled[i] = dequant_level(level, n, qp); + } +} + +/// One level scaled back to a coefficient, the per-coefficient half of +/// [`dequantize`]. A rate-distortion search over the levels prices one +/// coefficient at a time and has no use for the whole block. +pub fn dequant_level(level: i32, n: usize, qp: i32) -> i32 { let log2n = n.trailing_zeros() as i32; let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit let round = 1i64 << (bd_shift - 1); let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64; let shift = qp / 6; - for (i, &level) in levels[..n * n].iter().enumerate() { - let value = (((level as i64 * scale) << shift) + round) >> bd_shift; - scaled[i] = value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32; - } + let value = (((level as i64 * scale) << shift) + round) >> bd_shift; + value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32 +} + +/// What a squared error in the transform domain is worth as a squared error in +/// the sample domain. +/// +/// The forward transform's shifts leave the DC at 128 times the mean residual +/// whatever the block size, where an orthonormal transform would leave it at +/// `n` times; the transform is otherwise orthogonal, so coefficient error +/// energy is `(128 / n)^2` times sample error energy and this undoes it. A +/// rate-distortion search over the levels needs it to weigh transform-domain +/// error against a lambda calibrated on samples. +pub fn coeff_ssd_scale(n: usize) -> f64 { + (n * n) as f64 / (128.0 * 128.0) } /// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset. diff --git a/crates/ec-h265/tests/conformance.rs b/crates/ec-h265/tests/conformance.rs index 3ccc9dea..bfa209a6 100644 --- a/crates/ec-h265/tests/conformance.rs +++ b/crates/ec-h265/tests/conformance.rs @@ -491,3 +491,48 @@ fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { // Different pictures, different bitstreams. assert_ne!(coded[0].au, coded[1].au); } + +/// Rate-distortion quantisation changes which levels are coded, so the streams +/// it produces are a different set of bins from the plain quantiser's; ffmpeg +/// has to read them back to the same samples the encoder reconstructed. +#[test] +fn rdoq_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_rdoq(w, h, 27, true); + let (_, plain) = encode_rdoq(w, h, 27, false); + let name = format!("rdoq-{w}x{h}"); + assert_ne!( + coded.au, plain.au, + "{name}: the level search changed no byte, so it is not running" + ); + 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 > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); + } +} + +/// The natural frame coded with the level search on or off, everything else +/// left at its default. +fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { + let mut cfg = EncoderConfig::new(width, height); + cfg.rdoq = rdoq; + 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) +} diff --git a/crates/ec-h265/tests/encode.rs b/crates/ec-h265/tests/encode.rs index 062572ec..51e0cc4c 100644 --- a/crates/ec-h265/tests/encode.rs +++ b/crates/ec-h265/tests/encode.rs @@ -438,6 +438,9 @@ fn bd_psnr_vs_x265() { if let Ok(v) = std::env::var("EC_H265_SDH") { cfg.sign_hiding = v != "0"; } + if let Ok(v) = std::env::var("EC_H265_RDOQ") { + cfg.rdoq = v != "0"; + } if let Ok(v) = std::env::var("EC_H265_NXN") { cfg.intra_nxn = v != "0"; } @@ -542,7 +545,9 @@ fn bd_psnr_vs_x265() { // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that // shift. If the extrapolation share still exceeds 20% after measuring, the // shift is re-estimated from the geometric-mean bit ratio of the two full - // curves and the ladder is rebuilt — at most 2 extra alignment rounds + // curves and the ladder is rebuilt; once the rates match and the curves + // still do not meet, our ladder is drawn in towards its own centre until + // its bitrate range fits inside the anchor's — at most 8 alignment rounds // before the existing panic fires. const EXTRAP_LIMIT: f64 = 0.20; let x265_qps = [22, 26, 30, 34]; @@ -589,9 +594,17 @@ fn bd_psnr_vs_x265() { ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); let mut mine: Vec<(f64, f64, f64)>; let mut our_qps: [i32; 4]; + // How wide our QP ladder is against the anchor's, as a fraction of its + // spacing: one encoder can answer a QP step with far more bitrate than the + // other, and a BD number needs both curves over the same range. + let mut spread = 1.0_f64; - for round in 0..=2u32 { - our_qps = x265_qps.map(|q| (q + shift).clamp(1, 45)); + for round in 0..=8u32 { + our_qps = x265_qps.map(|q| { + let centre = f64::from(probe_qp + shift); + let offset = f64::from(q - probe_qp) * spread; + ((centre + offset).round() as i32).clamp(1, 45) + }); mine = our_qps .iter() .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) @@ -621,19 +634,33 @@ fn bd_psnr_vs_x265() { && anc_extrap <= EXTRAP_LIMIT && cand_extrap_yuv <= EXTRAP_LIMIT && anc_extrap_yuv <= EXTRAP_LIMIT; - if aligned || round == 2 { + if aligned || round == 8 { break; } // Re-estimate the shift from the geometric-mean bit ratio of the two - // full curves, then rebuild the ladder. + // full curves, then rebuild the ladder. A single-QP correction is + // ignored: it is within the rounding of the estimate and only makes the + // ladder oscillate between two neighbouring shifts. let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; - shift += delta; + if delta.abs() > 1 { + shift += delta; + eprintln!( + "alignment round {}: shift {delta:+} -> {shift:+} \ + (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", + round + 1, + gm(&mine) / 1e6, + gm(&theirs) / 1e6, + ); + continue; + } + // The rates match and the curves still do not overlap, so our ladder + // spans a much wider bitrate range than the anchor's: their union is + // then mostly outside what x265 measured and the cubic through its four + // points extrapolates over most of it. Draw our ladder in. + spread *= 0.5; eprintln!( - "alignment round {}: shift {delta:+} -> {shift:+} \ - (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", - round + 1, - gm(&mine) / 1e6, - gm(&theirs) / 1e6, + "alignment round {}: ladder spread -> {spread:.2} of the anchor's", + round + 1 ); }