From 47083d34ae11b74b563f2816b1f73611a65a122e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 24 Aug 2026 01:26:49 +0300 Subject: [PATCH] h264: choose inter luma levels against the CABAC coder's own price Rate-distortion quantisation for inter luma 4x4: each level is offered the cheaper magnitudes below it, and takes one when the squared error it gives up costs less than the bits it saves. The rate is exact. `CabacEnc::residual_block_cost` runs the same bins `residual_block` writes -- one body behind a `BinSink` the writer and the price share -- against a copy of the context state, charging each bin -log2(p) for its state and moving the state as the coder would. Over 400 random blocks it predicts 2649288/256 bits where the coder then spends 2650112/256, an error of 0.03%, which is asserted rather than assumed: a wrong price is invisible in the stream and shows up only as lost dB. An exact rate on its own was worth almost nothing (film -0.728 -> -0.732, screen capture -0.500 -> -0.449). The half that pays is the dead zone: a search that can only walk levels down cannot see a level the quantiser's 1/6 dead zone already threw away, so it was choosing among the survivors of the decision it was meant to replace. Quantising the searched path at 1/2 and letting the search take the levels back down is worth 0.102 dB on the film clip and 0.301 on the synthetic gate. Deciding the whole-block zero on exact bits too adds 0.142 dB there. BD-PSNR against x264 at matched features: film 3840x1608 -0.728 -> -0.628, screen capture 2560x1440 -0.500 -> -0.471, synthetic -4.523 -> -4.073, the floor moved to -4.15. Bounding the search to levels of 2 or less keeps it free (synthetic run 1.08 s before, 1.09 s after; unbounded it was 3.53 s). Intra stays out: its reconstruction is what the next block in the macroblock predicts from. Inter chroma AC and the 8x8 path are not covered yet. --- crates/ec-h264/src/enc/cabac_enc.rs | 322 ++++++++++++++++++++-------- crates/ec-h264/src/enc/entropy.rs | 16 ++ crates/ec-h264/src/enc/mb.rs | 176 ++++++++++++--- crates/ec-h264/src/enc/quant.rs | 18 +- crates/ec-h264/tests/encode.rs | 6 +- lanes/h264x264-r2.report.md | 85 ++++++++ 6 files changed, 501 insertions(+), 122 deletions(-) diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index 45c67033..ddff054d 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -375,18 +375,7 @@ impl CabacEnc { /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string. fn ueg_suffix(&mut self, value: u32, k0: u32) { - let mut k = k0; - let mut v = value; - while v >= 1 << k { - self.bypass(true); - v -= 1 << k; - k += 1; - } - self.bypass(false); - while k > 0 { - k -= 1; - self.bypass(v >> k & 1 != 0); - } + ueg_suffix_bins(self, value, k0); } /// transform_size_8x8_flag (9.3.3.1.1.10), mirroring the decoder's @@ -418,7 +407,7 @@ impl CabacEnc { } } } - self.encode_levels(coeff, last, OFF_ABS_8X8, false) + levels_bins(self, coeff, last, OFF_ABS_8X8, false) } /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the @@ -438,104 +427,221 @@ impl CabacEnc { "cat 5 goes through residual_block_8x8" ); let cat_i = cat.ctx_block_cat(); - let max = cat.max_num_coeff(); - let last = (0..max).rev().find(|&i| coeff[i] != 0); + let (a, b) = self.cbf_neighbours(cat, na, nb); + residual_bins(self, coeff, cat, OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b) + } + + /// The same bins [`Self::residual_block`] would write, costed against the + /// context state as it stands, in 1/256ths of a bit. Nothing is written and + /// no state moves: this is what a quantisation decision asks before it + /// commits. + pub(crate) fn residual_block_cost( + &self, + coeff: &[i32], + cat: BlockCat, + na: Option, + nb: Option, + ) -> u32 { + let cat_i = cat.ctx_block_cat(); + let (a, b) = self.cbf_neighbours(cat, na, nb); + let mut sink = CostSink { + state: self.state, + bits: 0, + }; + residual_bins( + &mut sink, + coeff, + cat, + OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, + ); + sink.bits + } + /// The coded_block_flag neighbour conditions (9.3.3.1.1.9), which the cost + /// path needs on exactly the terms the write path uses them. + fn cbf_neighbours(&self, cat: BlockCat, na: Option, nb: Option) -> (usize, usize) { let intra = self.cur_intra; let cond = |n: Option| match n { None => usize::from(intra), Some(v) => usize::from(v != 0), }; - let (a, b) = match cat { + match cat { BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)), BlockCat::ChromaDc(c) => ( self.dc_cbf(self.ctx.a, 1 + c), self.dc_cbf(self.ctx.b, 1 + c), ), _ => (cond(na), cond(nb)), + } + } + + fn dc_cbf(&self, n: Option, which: u8) -> usize { + match n { + None => usize::from(self.cur_intra), + Some(i) if i.flags & FLAG_PCM != 0 => 1, + Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), + } + } +} + +/// Where a residual block's bins go: the arithmetic coder that writes them, or +/// the counter that only prices them. +/// +/// The two share one body so that a price can never drift from what the writer +/// would spend — the whole value of an exact rate is that it is the same code. +trait BinSink { + /// A context-coded bin (9.3.4.1). + fn bin(&mut self, ctx_idx: usize, bin: bool); + /// An equiprobable bin (9.3.4.3). + fn bypass_bin(&mut self, bin: bool); +} + +impl BinSink for CabacEnc { + fn bin(&mut self, ctx_idx: usize, bin: bool) { + self.decision(ctx_idx, bin); + } + fn bypass_bin(&mut self, bin: bool) { + self.bypass(bin); + } +} + +/// Bits, in 1/256ths, that a bin costs against each of the 64 probability +/// states: `[2 * pStateIdx]` for a bin equal to the MPS, `+ 1` for the LPS. +/// +/// The state's LPS probability is the one clause 9.3.3.2.1 is built from, +/// p(sigma) = 0.5 * (0.01875 / 0.5)^(sigma / 63), so the entry is -log2 of it. +/// State 0 costs a whole bit either way, state 63 costs 7/256 of one for the +/// MPS: this spread is what makes an exact rate worth measuring at all. +const BIN_COST: [u16; 128] = [ + 256, 256, 238, 275, 221, 294, 206, 314, 192, 333, 180, 352, 168, 371, 157, 391, 148, 410, 139, + 429, 130, 448, 122, 468, 115, 487, 108, 506, 102, 525, 96, 545, 90, 564, 85, 583, 80, 602, 76, + 622, 72, 641, 68, 660, 64, 679, 60, 699, 57, 718, 54, 737, 51, 756, 48, 776, 46, 795, 43, 814, + 41, 833, 39, 853, 37, 872, 35, 891, 33, 910, 31, 930, 29, 949, 28, 968, 26, 987, 25, 1007, 24, + 1026, 22, 1045, 21, 1064, 20, 1084, 19, 1103, 18, 1122, 17, 1141, 16, 1161, 15, 1180, 15, 1199, + 14, 1218, 13, 1238, 12, 1257, 12, 1276, 11, 1295, 11, 1315, 10, 1334, 10, 1353, 9, 1372, 9, + 1392, 8, 1411, 8, 1430, 7, 1449, 7, 1469, +]; + +/// A [`BinSink`] that prices bins instead of writing them, carrying its own +/// copy of the context state so the adaptation inside the block is priced too. +struct CostSink { + state: [u8; NUM_CTX], + /// 1/256ths of a bit. + bits: u32, +} + +impl BinSink for CostSink { + fn bin(&mut self, ctx_idx: usize, bin: bool) { + let s = self.state[ctx_idx]; + let p = usize::from(s >> 1); + let mps = s & 1 != 0; + self.bits += u32::from(BIN_COST[2 * p + usize::from(bin != mps)]); + self.state[ctx_idx] = if bin != mps { + let mps = if p == 0 { !mps } else { mps }; + (crate::cabac_tables::TRANS_LPS[p] << 1) | u8::from(mps) + } else { + (crate::cabac_tables::TRANS_MPS[p] << 1) | u8::from(mps) }; - let Some(last) = last else { - self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, false); - return 0; - }; - self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, true); - - // Significance map. The decoder stops at the last significant position - // and infers the final coefficient, so nothing is written past `last`. - let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i]; - let last_base = OFF_LAST + SIG_CAT_OFF[cat_i]; - for i in 0..max - 1 { - let inc = sig_inc(cat, i); - let significant = coeff[i] != 0; - self.decision(sig_base + inc, significant); - if significant { - self.decision(last_base + inc, i == last); - if i == last { - break; - } + } + fn bypass_bin(&mut self, _bin: bool) { + self.bits += 256; + } +} + +/// coded_block_flag, the significance map and the levels of one residual block +/// (7.3.5.3.3), against a caller-derived coded_block_flag context. +fn residual_bins(s: &mut S, coeff: &[i32], cat: BlockCat, cbf_ctx: usize) -> u8 { + let cat_i = cat.ctx_block_cat(); + let max = cat.max_num_coeff(); + let Some(last) = (0..max).rev().find(|&i| coeff[i] != 0) else { + s.bin(cbf_ctx, false); + return 0; + }; + s.bin(cbf_ctx, true); + + // Significance map. The decoder stops at the last significant position + // and infers the final coefficient, so nothing is written past `last`. + let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i]; + let last_base = OFF_LAST + SIG_CAT_OFF[cat_i]; + for i in 0..max - 1 { + let inc = sig_inc(cat, i); + let significant = coeff[i] != 0; + s.bin(sig_base + inc, significant); + if significant { + s.bin(last_base + inc, i == last); + if i == last { + break; } } + } - self.encode_levels(coeff, last, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3) + levels_bins(s, coeff, last, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3) +} + +/// The UEGk suffix of 9.3.2.3, all bypass bins. +fn ueg_suffix_bins(s: &mut S, value: u32, k0: u32) { + let mut k = k0; + let mut v = value; + while v >= 1 << k { + s.bypass_bin(true); + v -= 1 << k; + k += 1; + } + s.bypass_bin(false); + while k > 0 { + k -= 1; + s.bypass_bin(v >> k & 1 != 0); } +} - /// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest - /// scanning position first (9.3.3.1.3 counters). Returns the number of - /// levels written. - fn encode_levels( - &mut self, - coeff: &[i32], - last: usize, - abs_base: usize, - chroma_dc: bool, - ) -> u8 { - let mut num_eq1 = 0u32; - let mut num_gt1 = 0u32; - let mut total = 0u8; - for pos in (0..=last).rev() { - let level = coeff[pos]; - if level == 0 { - continue; - } - let inc0 = if num_gt1 != 0 { - 0 - } else { - 4.min(1 + num_eq1) as usize - }; - let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize; - let abs_minus1 = level.unsigned_abs() - 1; - let mut prefix = 0u32; - while prefix < 14 { - let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 }; - if prefix < abs_minus1 { - self.decision(ctx_idx, true); - prefix += 1; - } else { - self.decision(ctx_idx, false); - break; - } - } - if abs_minus1 >= 14 { - self.ueg_suffix(abs_minus1 - 14, 0); - } - self.bypass(level < 0); - if abs_minus1 == 0 { - num_eq1 += 1; +/// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest +/// scanning position first (9.3.3.1.3 counters). Returns the number of +/// levels written. +fn levels_bins( + s: &mut S, + coeff: &[i32], + last: usize, + abs_base: usize, + chroma_dc: bool, +) -> u8 { + let mut num_eq1 = 0u32; + let mut num_gt1 = 0u32; + let mut total = 0u8; + for pos in (0..=last).rev() { + let level = coeff[pos]; + if level == 0 { + continue; + } + let inc0 = if num_gt1 != 0 { + 0 + } else { + 4.min(1 + num_eq1) as usize + }; + let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize; + let abs_minus1 = level.unsigned_abs() - 1; + let mut prefix = 0u32; + while prefix < 14 { + let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 }; + if prefix < abs_minus1 { + s.bin(ctx_idx, true); + prefix += 1; } else { - num_gt1 += 1; + s.bin(ctx_idx, false); + break; } - total += 1; } - total - } - - fn dc_cbf(&self, n: Option, which: u8) -> usize { - match n { - None => usize::from(self.cur_intra), - Some(i) if i.flags & FLAG_PCM != 0 => 1, - Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), + if abs_minus1 >= 14 { + ueg_suffix_bins(s, abs_minus1 - 14, 0); } + s.bypass_bin(level < 0); + if abs_minus1 == 0 { + num_eq1 += 1; + } else { + num_gt1 += 1; + } + total += 1; } + total } #[cfg(test)] @@ -639,4 +745,44 @@ mod tests { assert!(dec.more_macroblocks().expect("terminate"), "block {i} end"); } } + /// The price is the thing itself: `residual_block_cost` predicts what + /// `residual_block` then spends. A quantisation decision that trusts a + /// wrong price picks wrong levels, and the error would be invisible in the + /// stream — it only shows up as lost dB — so it is asserted here in + /// 1/256ths of a bit against the arithmetic coder's own output. + #[test] + fn residual_cost_predicts_the_bits_spent() { + let mut state = 0x1234_5678u32; + let mut rand = move |m: u32| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state % m + }; + let mut enc = CabacEnc::new(BitWriter::new(), 26, 0); + let (mut predicted, mut spent) = (0i64, 0i64); + for _ in 0..400 { + let mut coeff = [0i32; 16]; + let nz = rand(8); + for _ in 0..nz { + let i = rand(16) as usize; + let mag = 1 + rand(6) as i32 * rand(4) as i32; + coeff[i] = if rand(2) == 0 { mag } else { -mag }; + } + let (na, nb) = (Some(rand(4) as u8), Some(rand(4) as u8)); + let cost = enc.residual_block_cost(&coeff, BlockCat::Luma4x4, na, nb); + let before = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros()); + enc.residual_block(&coeff, BlockCat::Luma4x4, na, nb); + let after = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros()); + predicted += i64::from(cost); + spent += after as i64 - before as i64; + } + // Per block the arithmetic coder carries fractional bits across the + // boundary, so the claim is on the total: within 1%. + let err = (predicted - spent).abs(); + assert!( + err * 100 < spent, + "predicted {predicted}/256 bits, spent {spent}/256" + ); + } } diff --git a/crates/ec-h264/src/enc/entropy.rs b/crates/ec-h264/src/enc/entropy.rs index 8b093002..113d1c8d 100644 --- a/crates/ec-h264/src/enc/entropy.rs +++ b/crates/ec-h264/src/enc/entropy.rs @@ -194,6 +194,22 @@ impl EncEntropy { } } + /// What [`Self::residual_block`] would spend on `coeff`, in 1/256ths of a + /// bit, without writing it. `None` under CAVLC, whose cost a caller can + /// only estimate. + pub(crate) fn residual_block_cost( + &self, + coeff: &[i32], + cat: BlockCat, + na: Option, + nb: Option, + ) -> Option { + match self { + EncEntropy::Cavlc { .. } => None, + EncEntropy::Cabac(c) => Some(c.residual_block_cost(coeff, cat, na, nb)), + } + } + pub(crate) fn is_cabac(&self) -> bool { matches!(self, EncEntropy::Cabac(_)) } diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 9fc0ef33..2aa78bfd 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -17,32 +17,32 @@ use wide::i16x16; use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line}; use crate::decoder::{ - chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors, + MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, }; -use crate::dpb::{Picture, Plane8, BLK_SKIP}; +use crate::dpb::{BLK_SKIP, Picture, Plane8}; use crate::entropy::{ - BlockCat, MbCtx, MbInfo, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, - FLAG_TRANS8X8, + BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8, + MbCtx, MbInfo, }; -use crate::inter::{integer_origin, mc_chroma, mc_luma, RefPlane}; -use crate::mv::{neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd, MvCtx}; +use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; +use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd}; use crate::pred::{ - add_residual_4x4, add_residual_8x8, filter_nbr8, pred_16x16, pred_4x4, pred_8x8, - pred_chroma_8x8, PlaneWindow, + PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16, + pred_chroma_8x8, }; use crate::tables::{BLK4_POS, CHROMA_QP}; use crate::transform::{ - chroma_dc_transform_420, dequant_4x4, dequant_8x8, inverse_transform_4x4, - inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, unzigzag_ac15, LevelScale4x4, - LevelScale8x8, + LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8, + inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, + unzigzag_ac15, }; use super::quant::{ - forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8, - quant_chroma_dc, quant_luma_dc, + forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, + quant_4x4_offset, quant_8x8, quant_chroma_dc, quant_luma_dc, }; use super::{ - entropy::{sub_block_4x4, EncEntropy}, + entropy::{EncEntropy, sub_block_4x4}, lambda_ssd, }; @@ -316,7 +316,6 @@ fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { (lambda * bits).round() as i32 } - /// Everything one macroblock's coding writes into the picture, kept so that a /// branch can be coded, measured and undone. struct MbState { @@ -602,7 +601,6 @@ fn intra_pre_cost( /// below a half and falls away above it. const MV_BITS_WEIGHT: f64 = 0.5; - /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13. #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum PShape { @@ -857,9 +855,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter /// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock, /// prediction already in the plane. +#[allow(clippy::too_many_arguments)] fn code_luma_4x4( pic: &mut Picture, e: &MbEnc<'_>, + w: &EncEntropy, mb_x: usize, mb_y: usize, qp: i32, @@ -880,7 +880,15 @@ fn code_luma_4x4( } let source = d; forward_4x4(&mut d); - let nz = quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]); + let rdoq = !intra && w.is_cabac(); + let mut nz = if rdoq { + quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk]) + } else { + quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]) + }; + if rdoq && nz != 0 { + nz = rdoq_4x4(e, w, &source, &mut lv.luma[blk], qp); + } lv.luma_nz[blk] = nz; if nz == 0 { continue; @@ -895,7 +903,8 @@ fn code_luma_4x4( // half of rate-distortion optimised quantisation, and the half that // pays. Intra blocks are left alone: their reconstruction is what the // next block in the macroblock predicts from. - if !intra + if !rdoq + && !intra && !worth_coding( &source, &resid, @@ -912,6 +921,118 @@ fn code_luma_4x4( } } +/// Squared error of coding `levels`, in the pixels the block reconstructs to. +fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32) -> i64 { + let mut raster = [0i32; 16]; + unzigzag(levels, &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + let mut ssd = 0i64; + for i in 0..16 { + let d = i64::from(source[i] - resid[i]); + ssd += d * d; + } + ssd +} + +/// How much of the mode-decision lambda rate-distortion quantisation uses. +/// +/// The bits here are the coder's own, not an estimate, so there is no +/// over-estimate to correct for and the scale starts at 1. Swept over 0.5, +/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a +/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5 +/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is +/// the crossing point that costs neither (-0.628 and -0.471). Table in +/// `lanes/h264x264-r2.report.md`. +const RDOQ_LAMBDA: f64 = 1.0; + +/// The dead zone rate-distortion quantisation starts from, as a divisor of the +/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which +/// has already thrown away the levels this search would weigh -- a search +/// bounded by the heuristic it replaces measures the heuristic. This is the +/// half of the change that pays: 1/6 -> 1/2 under the same search is worth +/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read +/// -0.647 and -0.677 dB where 1/2 reads -0.630. +const RDOQ_DEAD_ZONE: i32 = 2; + +/// The largest level the search offers a smaller magnitude to. A big level is +/// carrying real signal and never wins by shrinking; bounding the search is +/// what keeps it free. Unbounded it tripled the synthetic clip's encode time +/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over +/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and +/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture. +const RDOQ_MAX_LEVEL: i32 = 2; + +/// Rate-distortion quantisation of one inter luma block: each level is offered +/// the two cheaper 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 against the +/// context state as it stands, so dropping a level is priced with the +/// significance map that follows from it — which is where most of the saving +/// is. Intra blocks stay out: their reconstruction is what the next block in +/// the macroblock predicts from, so a level changed here would move a +/// prediction the decision cannot see. +fn rdoq_4x4( + e: &MbEnc<'_>, + w: &EncEntropy, + source: &[i32; 16], + levels: &mut [i32; 16], + qp: i32, +) -> u8 { + let Some(bits) = w.residual_block_cost(levels, BlockCat::Luma4x4, Some(1), Some(1)) else { + return levels.iter().filter(|&&l| l != 0).count() as u8; + }; + let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0; + let mut cost = block_ssd(e, source, levels, qp) as f64 + lambda * f64::from(bits); + // Highest scanning position first: dropping the last significant level is + // what shortens the significance map, so it is tried while the levels + // above it are still gone. + for pos in (0..16).rev() { + let level = levels[pos]; + if level == 0 { + continue; + } + let mag = level.abs(); + if mag > RDOQ_MAX_LEVEL { + continue; + } + let mut tried = mag; + for candidate in [mag - 1, 0] { + if candidate == tried { + continue; + } + tried = candidate; + let keep = levels[pos]; + levels[pos] = candidate * level.signum(); + let Some(bits) = w.residual_block_cost(levels, BlockCat::Luma4x4, Some(1), Some(1)) + else { + unreachable!("CAVLC returned early"); + }; + let trial = block_ssd(e, source, levels, qp) as f64 + lambda * f64::from(bits); + if trial < cost { + cost = trial; + } else { + levels[pos] = keep; + } + } + } + // And the block as a whole: zeroing it drops the coded_block_pattern bit as + // well as every level, which no single-coefficient step can see. This is + // the same decision `worth_coding` makes for the paths without an exact + // rate, made here with one. + let zero_bits = w + .residual_block_cost(&[0; 16], BlockCat::Luma4x4, Some(1), Some(1)) + .expect("CABAC"); + let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum(); + if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost { + *levels = [0; 16]; + return 0; + } + levels.iter().filter(|&&l| l != 0).count() as u8 +} + /// How much of the mode-decision lambda the zero-block test uses. /// /// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what @@ -2162,8 +2283,7 @@ fn ssd_mb_deblocked( for row in 0..16 { let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16; for x in 0..16 { - let d = - i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]); + let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]); sum += d * d; } } @@ -2173,11 +2293,7 @@ fn ssd_mb_deblocked( /// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its /// macroblock edges, 3 on the internal luma edges. fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 { - if edge == 0 { - 4 - } else { - 3 - } + if edge == 0 { 4 } else { 3 } } /// Rough bit cost of a macroblock's luma residual. @@ -2216,11 +2332,7 @@ fn block_bits(b: &[i32]) -> i64 { n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; } } - if n > 0 { - n + 6 - } else { - 2 - } + if n > 0 { n + 6 } else { 2 } } /// Rough bit cost of a macroblock's residual, for the skip decision: a level @@ -2381,7 +2493,7 @@ fn encode_inter_mb( let mut pred = [0u8; 256]; save_luma(pic, mb_x, mb_y, &mut pred); let mut lv4 = chroma_lv.clone(); - code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv4); + code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4); let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4); let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64; let mut recon4 = [0u8; 256]; @@ -2398,7 +2510,7 @@ fn encode_inter_mb( restore_luma(pic, mb_x, mb_y, &recon4); } } else { - code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); + code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv); } let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; let skip = match ssd_skip { diff --git a/crates/ec-h264/src/enc/quant.rs b/crates/ec-h264/src/enc/quant.rs index b17066e1..71ffdfd3 100644 --- a/crates/ec-h264/src/enc/quant.rs +++ b/crates/ec-h264/src/enc/quant.rs @@ -213,10 +213,26 @@ pub(crate) fn quant_4x4( intra: bool, skip_dc: bool, out: &mut [i32; 16], +) -> u8 { + quant_4x4_offset(coef, qp, if intra { 3 } else { 6 }, skip_dc, out) +} + +/// [`quant_4x4`] with the dead zone spelled out: the rounding offset is +/// `1 / divisor` of a quantiser step. +/// +/// Rate-distortion quantisation asks for a *smaller* dead zone than the plain +/// path uses, because it walks levels down itself and cannot walk them up: a +/// level the dead zone already dropped is not a candidate any more. +pub(crate) fn quant_4x4_offset( + coef: &[i32; 16], + qp: i32, + divisor: i32, + skip_dc: bool, + out: &mut [i32; 16], ) -> u8 { let m = (qp % 6) as usize; let qbits = 15 + (qp / 6) as u32; - let f = round_offset(qbits, intra); + let f = (1i32 << qbits) / divisor; let start = usize::from(skip_dc); let mut nz = 0; *out = [0; 16]; diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index a71cbb09..b790f2a0 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -893,7 +893,11 @@ fn real_clip_t8x8_bd_psnr() { /// clip and 0.564 on the screen capture, and takes fewer bits at every QP /// while doing it. This clip prefers a heavier rate term in that decision /// (see the sweep in `enc/mb.rs`), which the two real clips do not. -const BD_PSNR_VS_X264_FLOOR: f64 = -4.6; +/// +/// It moved -4.523 -> -4.073 when inter luma levels started being chosen +/// against the CABAC coder's own price for them (0.100 dB on the film clip, +/// 0.029 on the screen capture). +const BD_PSNR_VS_X264_FLOOR: f64 = -4.15; fn have_x264() -> bool { std::process::Command::new("ffmpeg") diff --git a/lanes/h264x264-r2.report.md b/lanes/h264x264-r2.report.md index 72df44ed..44aca917 100644 --- a/lanes/h264x264-r2.report.md +++ b/lanes/h264x264-r2.report.md @@ -267,3 +267,88 @@ which inter luma allows because its reconstruction does not feed the next block's prediction the way intra's does; and it needs a term for what a reference picture's quality is worth to the pictures that predict from it, without which more search measures worse. + +## Rate-distortion quantisation, landed on the coder's own price + +The attempt above failed on an estimate. This one prices bins with the CABAC +engine itself and lands 0.100 dB on the film clip, 0.029 on the screen capture +and 0.450 on the synthetic gate, for no measurable encode time. + +### The price is the thing itself + +`CabacEnc::residual_block_cost` runs the bins `residual_block` would write -- +the same code, through a `BinSink` the two share -- against a copy of the +context state, charging each bin `-log2(p)` for its state from a 128-entry +table and moving the state exactly as the coder would. So a level dropped is +priced with the significance map that follows from it, and the adaptation +inside the block is priced too. + +Its accuracy is asserted, not assumed: over 400 random blocks it predicts +2 649 288/256 bits where the arithmetic coder then spends 2 650 112/256, an +error of 0.03% (`residual_cost_predicts_the_bits_spent`). A wrong price would +be invisible in the stream -- it would only show up as lost dB -- which is why +it is a test and not a comment. + +### What actually moved the numbers + +Three changes, measured one at a time against film -0.728, screen -0.500, +synthetic -4.523: + +| change | synthetic | film | screen | +|-----------------------------------------------|-----------|--------|--------| +| levels walked down on exact cost | -4.530 | -0.732 | -0.449 | +| + dead zone 1/6 -> 1/2 for the walked path | -4.229 | -0.630 | -0.496 | +| + whole-block zero decided on exact cost | -4.087 | -0.628 | -0.469 | +| + search bounded to levels <= 2 | -4.073 | -0.628 | -0.471 | + +The first row is the honest answer to the previous attempt's question: an exact +rate on its own buys 0.05 dB on screen content and nothing on film. **The dead +zone was the missing half.** A search that can only walk levels *down* cannot +see a level the quantiser's 1/6 dead zone already threw away, so it was +choosing among the survivors of a decision it was meant to replace. Quantising +the searched path at 1/2 -- round to nearest, x264's own arrangement when +trellis is on -- and letting the search take the levels back down is worth +0.102 dB on film and 0.301 on the synthetic clip. + +The class: **a search bounded by the heuristic it replaces measures the +heuristic.** The dead zone constant was swept and defended (`enc/quant.rs` +says the inter offset is inert across 6/64 to 32/64), and that was true -- +of a path with no search after it. + +### The constants + +| RDOQ_LAMBDA (x lambda_ssd), dead zone | synthetic | film | screen | +|---------------------------------------|-----------|--------|--------| +| 1.0, 1/6 | -4.530 | -0.732 | -0.449 | +| 0.5, 1/2 | -4.203 | -0.607 | -0.620 | +| 1.0, 1/2 | -4.229 | -0.630 | -0.496 | +| 1.25, 1/2 | -4.103 | -0.657 | -0.433 | +| 1.5, 1/2 | -4.362 | -0.680 | -0.444 | +| 2.0, 1/2 | -4.526 | -- | -- | +| 1.0, 1/3 | -4.295 | -0.647 | -0.465 | +| 1.0, 1/4 | -4.416 | -0.677 | -0.465 | + +The two real clips disagree about the rate term -- film wants it lighter, +screen capture heavier -- and 1.0 is the crossing point that costs neither. +The 1.25 and 1.5 rows are what a screen-only tuning would take, at 0.03 to +0.05 dB of the film clip. + +Bounding the search to levels of 2 or less (`RDOQ_MAX_LEVEL`) costs nothing and +is what makes it free: unbounded, the search tripled our encode time on the +synthetic clip (1.08 s -> 3.53 s); bounded, it is 1.09 s. A large level is +carrying real signal and never wins by shrinking. 1, 2 and 3 read +-4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and -4.065/-0.629/-0.477; 2 is the +best of the three on the clip that gains least. + +### What is not covered + +Intra blocks stay out: their reconstruction is what the next block in the +macroblock predicts from, so a level changed there moves a prediction the +decision cannot see. Inter chroma AC and the 8x8 transform path are untouched +and are the next place to look -- x264's trellis covers both. The +coded_block_flag context the price is taken against assumes both neighbours +carry coefficients rather than reading them, which is a constant shift across +candidates except for the whole-block-zero one. + +x264's own trellis is worth 0.193 dB on the film clip and 0.208 on the screen +capture (measured by ablation, r2 above). We now take 0.100 and 0.029 of that.