From fad429706a3281a599a67f3c4bfb6c195008e6c9 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:52:32 +0300 Subject: [PATCH] h264: price the 8x8 inter blocks on their own bins too residual_block_8x8_cost costs the cat-5 bins the writer writes, and the 8x8 path quantises, searches and zero-tests through it the way the 4x4 luma path does. quant_8x8 grew the same offset-naming sibling the 4x4 quantiser has, so the search picks the rounding that feeds it. Swept again rather than inherited: 8x8 answers like 4x4 luma, not like chroma, and keeps round-to-nearest. Measured as BD-PSNR of the opt-in transform_8x8 flag against flag-off, which is what isolates this path: film +0.535 -> +0.619, screen capture +0.042 -> +0.067. No default stream byte moves -- the flag is still off by default. --- crates/ec-h264/src/enc/cabac_enc.rs | 89 +++++++++++++++++++---- crates/ec-h264/src/enc/entropy.rs | 7 ++ crates/ec-h264/src/enc/mb.rs | 109 ++++++++++++++++++++++++++-- crates/ec-h264/src/enc/quant.rs | 20 +++-- lanes/h264x264-r2.report.md | 28 +++++++ 5 files changed, 227 insertions(+), 26 deletions(-) diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index ddff054d..ab63ac9d 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -393,21 +393,23 @@ impl CabacEnc { /// coded_block_flag: for 4:2:0 the coded_block_pattern bit is the whole /// signal (7.3.5.3.3), so an all-zero block must not reach here. pub(crate) fn residual_block_8x8(&mut self, coeff: &[i32; 64]) -> u8 { - let last = (0..64) - .rev() - .find(|&i| coeff[i] != 0) - .expect("an 8x8 block with cbp set has a coefficient"); - for i in 0..63 { - let significant = coeff[i] != 0; - self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i]), significant); - if significant { - self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i]), i == last); - if i == last { - break; - } - } + residual_bins_8x8(self, coeff) + } + + /// What [`Self::residual_block_8x8`] would spend on `coeff`, in 1/256ths + /// of a bit, against the context state as it stands. An all-zero block + /// costs nothing here: it is not coded at all, and the coded block pattern + /// that says so is priced by whoever writes it. + pub(crate) fn residual_block_8x8_cost(&self, coeff: &[i32; 64]) -> u32 { + if coeff.iter().all(|&c| c == 0) { + return 0; } - levels_bins(self, coeff, last, OFF_ABS_8X8, false) + let mut sink = CostSink { + state: self.state, + bits: 0, + }; + residual_bins_8x8(&mut sink, coeff); + sink.bits } /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the @@ -550,6 +552,26 @@ impl BinSink for CostSink { /// 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. +/// The bins of one 8x8 luma residual block (7.3.5.3.3, cat 5): its own +/// significance map and last-position contexts, then the levels. +fn residual_bins_8x8(s: &mut S, coeff: &[i32; 64]) -> u8 { + let last = (0..64) + .rev() + .find(|&i| coeff[i] != 0) + .expect("an 8x8 block with cbp set has a coefficient"); + for i in 0..63 { + let significant = coeff[i] != 0; + s.bin(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i]), significant); + if significant { + s.bin(OFF_LAST_8X8 + usize::from(LAST_8X8[i]), i == last); + if i == last { + break; + } + } + } + levels_bins(s, coeff, last, OFF_ABS_8X8, false) +} + 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(); @@ -785,4 +807,43 @@ mod tests { "predicted {predicted}/256 bits, spent {spent}/256" ); } + + /// The same claim for the 8x8 block: `residual_block_8x8_cost` predicts + /// what `residual_block_8x8` spends, which is what the 8x8 quantisation + /// decision buys its levels with. + #[test] + fn residual_8x8_cost_predicts_the_bits_spent() { + let mut state = 0x0bad_f00du32; + 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..200 { + let mut coeff = [0i32; 64]; + let nz = 1 + rand(20); + for _ in 0..nz { + let i = rand(64) as usize; + let mag = 1 + rand(6) as i32 * rand(4) as i32; + coeff[i] = if rand(2) == 0 { mag } else { -mag }; + } + if coeff.iter().all(|&c| c == 0) { + coeff[0] = 1; + } + let cost = enc.residual_block_8x8_cost(&coeff); + let before = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros()); + enc.residual_block_8x8(&coeff); + let after = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros()); + predicted += i64::from(cost); + spent += after as i64 - before as i64; + } + 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 113d1c8d..4044f61f 100644 --- a/crates/ec-h264/src/enc/entropy.rs +++ b/crates/ec-h264/src/enc/entropy.rs @@ -197,6 +197,13 @@ 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_8x8_cost(&self, coeff: &[i32; 64]) -> Option { + match self { + EncEntropy::Cavlc { .. } => None, + EncEntropy::Cabac(c) => Some(c.residual_block_8x8_cost(coeff)), + } + } + pub(crate) fn residual_block_cost( &self, coeff: &[i32], diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 021a0e2f..0a08a993 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -39,7 +39,7 @@ use crate::transform::{ use super::quant::{ forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, - quant_4x4_offset, quant_8x8, quant_chroma_dc, quant_luma_dc, + quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc, }; use super::{ entropy::{EncEntropy, sub_block_4x4}, @@ -987,6 +987,15 @@ const RDOQ_MAX_LEVEL: i32 = 2; /// back; what pays is only the pruning. const RDOQ_CHROMA_DEAD_ZONE: i32 = 6; +/// The rounding the 8x8 luma path keeps under the search. It answers the way +/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in +/// `transform_8x8` flag against flag-off, which isolates this path because the +/// flag-off curve does not run through it. Film 3840x1608 / screen capture +/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075, +/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough +/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do. +const RDOQ8_DEAD_ZONE: 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. @@ -1188,6 +1197,7 @@ fn code_luma_i16( } /// Chroma residual for both components (8.5.11 + the AC path). +#[allow(clippy::too_many_arguments)] fn code_chroma( pic: &mut Picture, e: &MbEnc<'_>, @@ -1574,9 +1584,11 @@ fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: /// Residual of one 8x8 luma block against the prediction already in the /// plane: forward transform, quantise, and — when anything survives — /// reconstruct with the decoder's own inverse. Returns the non-zero count. +#[allow(clippy::too_many_arguments)] fn code_block_8x8( pic: &mut Picture, e: &MbEnc<'_>, + w: &EncEntropy, x: usize, y: usize, qp: i32, @@ -1592,16 +1604,29 @@ fn code_block_8x8( - i32::from(pic.y.data[origin + ry * stride + rx]); } } - let nz = quant_8x8(&forward_8x8(&d), &e.ls8, qp, intra, out); + let rdoq = !intra && w.is_cabac(); + let fwd = forward_8x8(&d); + let mut nz = if rdoq { + quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out) + } else { + quant_8x8(&fwd, &e.ls8, qp, intra, out) + }; if nz == 0 { return 0; } + if rdoq { + nz = rdoq_8x8(e, w, &d, out, qp); + if nz == 0 { + return 0; + } + } let mut raster = [0i32; 64]; unzigzag_8x8(out, &mut raster); dequant_8x8(&mut raster, &e.ls8, qp); let mut resid = [0i32; 64]; inverse_transform_8x8(&raster, &mut resid); - if !intra + if !rdoq + && !intra && !worth_coding( &d, &resid, @@ -1619,9 +1644,11 @@ fn code_block_8x8( /// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of /// [`code_intra_4x4`]: neighbours are the decoder's filtered reference /// samples, and every 4x4 mode slot of a block carries its mode. +#[allow(clippy::too_many_arguments)] fn code_intra_8x8( pic: &mut Picture, e: &MbEnc<'_>, + w: &EncEntropy, mb_x: usize, mb_y: usize, qp: i32, @@ -1669,7 +1696,7 @@ fn code_intra_8x8( let row = origin + ry * stride; pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]); } - if code_block_8x8(pic, e, x, y, qp, true, &mut lv.luma8[blk8]) > 0 { + if code_block_8x8(pic, e, w, x, y, qp, true, &mut lv.luma8[blk8]) > 0 { lv.cbp_luma |= 1 << blk8; } } @@ -1681,6 +1708,7 @@ fn code_intra_8x8( fn code_luma_8x8( pic: &mut Picture, e: &MbEnc<'_>, + w: &EncEntropy, mb_x: usize, mb_y: usize, qp: i32, @@ -1689,12 +1717,79 @@ fn code_luma_8x8( lv.trans8 = true; for blk8 in 0..4 { let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); - if code_block_8x8(pic, e, x, y, qp, false, &mut lv.luma8[blk8]) > 0 { + if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 { lv.cbp_luma |= 1 << blk8; } } } +/// Squared error of coding `levels` as an 8x8 block, in its pixels. +fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 { + let mut raster = [0i32; 64]; + unzigzag_8x8(levels, &mut raster); + dequant_8x8(&mut raster, &e.ls8, qp); + let mut resid = [0i32; 64]; + inverse_transform_8x8(&raster, &mut resid); + let mut ssd = 0i64; + for k in 0..64 { + let d = i64::from(source[k]) - i64::from(resid[k]); + ssd += d * d; + } + ssd +} + +/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the +/// CABAC coder's own price, with the 8x8 block's own contexts. +fn rdoq_8x8( + e: &MbEnc<'_>, + w: &EncEntropy, + source: &[i32; 64], + levels: &mut [i32; 64], + qp: i32, +) -> u8 { + let Some(bits) = w.residual_block_8x8_cost(levels) 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_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits); + for pos in (0..64).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 bits = w + .residual_block_8x8_cost(levels) + .expect("CAVLC returned early"); + let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits); + if trial < cost { + cost = trial; + } else { + levels[pos] = keep; + break; + } + } + } + // The whole block against nothing, on the same exact price. + let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum(); + if ssd_zero as f64 <= cost { + *levels = [0; 64]; + return 0; + } + levels.iter().filter(|&&l| l != 0).count() as u8 +} + /// Squared error of the luma macroblock against the source. fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { let stride = pic.y.stride; @@ -2057,7 +2152,7 @@ fn encode_intra_mb( let mut lv8 = chroma_lv.clone(); let mut recon8 = [0u8; 256]; let cost8 = if e.t8x8_intra(mb_y) { - let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8); + let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8); modes8 = m8; pred_modes8 = p8; save_luma(pic, mb_x, mb_y, &mut recon8); @@ -2541,7 +2636,7 @@ fn encode_inter_mb( save_luma(pic, mb_x, mb_y, &mut recon4); restore_luma(pic, mb_x, mb_y, &pred); let mut lv8 = chroma_lv; - code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8); + code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8); let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; if cost8 + e.lambda * e.t8x8_margin_bits < cost4 { diff --git a/crates/ec-h264/src/enc/quant.rs b/crates/ec-h264/src/enc/quant.rs index 71ffdfd3..7f4f062b 100644 --- a/crates/ec-h264/src/enc/quant.rs +++ b/crates/ec-h264/src/enc/quant.rs @@ -162,10 +162,6 @@ pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] { /// precomputed shift because [`forward_8x8`]'s coefficients already carry /// far more headroom than a `<<15`-ish fixed point would give. #[inline] -fn round_div(raw: i64, denom: i64, intra: bool) -> i64 { - (raw + denom / if intra { 3 } else { 6 }) / denom -} - /// Quantise an 8x8 [`forward_8x8`] output into scan (zig-zag) order, undoing /// both the `2_088_025` transform gain and the per-position [`LevelScale8x8`] /// / QP scale that [`crate::transform::dequant_8x8`] will re-apply. @@ -175,6 +171,20 @@ pub(crate) fn quant_8x8( qp: i32, intra: bool, out: &mut [i32; 64], +) -> u8 { + quant_8x8_offset(coef, ls, qp, if intra { 3 } else { 6 }, out) +} + +/// [`quant_8x8`] with the rounding offset named outright: the level is +/// `(raw + denom / divisor) / denom`, so a divisor of 2 rounds to nearest and +/// 6 is the inter dead zone. A search that offers smaller magnitudes wants to +/// pick this itself. +pub(crate) fn quant_8x8_offset( + coef: &[i64; 64], + ls: &LevelScale8x8, + qp: i32, + divisor: i32, + out: &mut [i32; 64], ) -> u8 { // 11560^2 / 64, see FWD8's doc comment. const TOTAL_SCALE: i64 = 2_088_025; @@ -193,7 +203,7 @@ pub(crate) fn quant_8x8( } else { (c.unsigned_abs() as i64, denom << -p) }; - let level = round_div(num, denom, intra) as i32; + let level = ((num + denom / i64::from(divisor)) / denom) as i32; if level != 0 { nz += 1; } diff --git a/lanes/h264x264-r2.report.md b/lanes/h264x264-r2.report.md index f1181337..0be47619 100644 --- a/lanes/h264x264-r2.report.md +++ b/lanes/h264x264-r2.report.md @@ -383,3 +383,31 @@ x264's trellis is worth 0.193 dB on the film clip and 0.208 on the screen capture, so the two slices together take 0.135 and 0.032 of it. The 8x8 luma transform path is still untouched. + +## The same price, applied to the 8x8 transform path + +`code_block_8x8` now quantises, searches and zero-tests its inter blocks the +way the 4x4 luma path does, on a `residual_block_8x8_cost` that shares its +bins with the writer (asserted to 1% over 200 random 64-coefficient blocks, +`residual_8x8_cost_predicts_the_bits_spent`). + +The x264 comparison cannot see this path -- both sides run with `8x8dct=0` at +matched features -- so it is measured as BD-PSNR of the opt-in `transform_8x8` +flag against flag-off, which isolates it: the flag-off curve does not go +through an 8x8 block. + +| rounding under the search | film 3840x1608 | screen capture 2560x1440 | +|---|---|---| +| no search (baseline) | +0.535 | +0.042 | +| 1/6 | +0.551 | -- | +| 1/3 | +0.605 | +0.075 | +| **1/2** | **+0.619** | +0.067 | + +8x8 answers the way 4x4 luma did and chroma did not: its blocks carry enough +coefficients for the wider rounding to pay for itself. Landed at 1/2 -- +film +0.535 -> +0.619 (0.084 dB), screen capture +0.042 -> +0.067. The average +8x8 macroblock share rises with it (19.0% -> 20.2% film), which is the flag +being chosen more often now that the blocks it picks are cheaper. + +`transform_8x8` is still opt-in, so this changes no default stream byte; the +open decision to flip that default is worth 0.084 dB more than it was.