forge
Explore
Log in

Don't you dare go Hollow

h264: price the 8x8 inter blocks on their own bins too

Browse files at this commit

fad429706a3281a599a67f3c4bfb6c195008e6c9Ahmet Kaan GümüşParent: e21a764
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.rsmodified+75 -14
@@ -393,21 +393,23 @@ impl CabacEnc {
393393 /// coded_block_flag: for 4:2:0 the coded_block_pattern bit is the whole
394394 /// signal (7.3.5.3.3), so an all-zero block must not reach here.
395395 pub(crate) fn residual_block_8x8(&mut self, coeff: &[i32; 64]) -> u8 {
396- let last = (0..64)
397- .rev()
398- .find(|&i| coeff[i] != 0)
399- .expect("an 8x8 block with cbp set has a coefficient");
400- for i in 0..63 {
401- let significant = coeff[i] != 0;
402- self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i]), significant);
403- if significant {
404- self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i]), i == last);
405- if i == last {
406- break;
407- }
408- }
396+ residual_bins_8x8(self, coeff)
397+ }
398+
399+ /// What [`Self::residual_block_8x8`] would spend on `coeff`, in 1/256ths
400+ /// of a bit, against the context state as it stands. An all-zero block
401+ /// costs nothing here: it is not coded at all, and the coded block pattern
402+ /// that says so is priced by whoever writes it.
403+ pub(crate) fn residual_block_8x8_cost(&self, coeff: &[i32; 64]) -> u32 {
404+ if coeff.iter().all(|&c| c == 0) {
405+ return 0;
409406 }
410- levels_bins(self, coeff, last, OFF_ABS_8X8, false)
407+ let mut sink = CostSink {
408+ state: self.state,
409+ bits: 0,
410+ };
411+ residual_bins_8x8(&mut sink, coeff);
412+ sink.bits
411413 }
412414
413415 /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the
@@ -550,6 +552,26 @@ impl BinSink for CostSink {
550552
551553 /// coded_block_flag, the significance map and the levels of one residual block
552554 /// (7.3.5.3.3), against a caller-derived coded_block_flag context.
555+/// The bins of one 8x8 luma residual block (7.3.5.3.3, cat 5): its own
556+/// significance map and last-position contexts, then the levels.
557+fn residual_bins_8x8<S: BinSink>(s: &mut S, coeff: &[i32; 64]) -> u8 {
558+ let last = (0..64)
559+ .rev()
560+ .find(|&i| coeff[i] != 0)
561+ .expect("an 8x8 block with cbp set has a coefficient");
562+ for i in 0..63 {
563+ let significant = coeff[i] != 0;
564+ s.bin(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i]), significant);
565+ if significant {
566+ s.bin(OFF_LAST_8X8 + usize::from(LAST_8X8[i]), i == last);
567+ if i == last {
568+ break;
569+ }
570+ }
571+ }
572+ levels_bins(s, coeff, last, OFF_ABS_8X8, false)
573+}
574+
553575 fn residual_bins<S: BinSink>(s: &mut S, coeff: &[i32], cat: BlockCat, cbf_ctx: usize) -> u8 {
554576 let cat_i = cat.ctx_block_cat();
555577 let max = cat.max_num_coeff();
@@ -785,4 +807,43 @@ mod tests {
785807 "predicted {predicted}/256 bits, spent {spent}/256"
786808 );
787809 }
810+
811+ /// The same claim for the 8x8 block: `residual_block_8x8_cost` predicts
812+ /// what `residual_block_8x8` spends, which is what the 8x8 quantisation
813+ /// decision buys its levels with.
814+ #[test]
815+ fn residual_8x8_cost_predicts_the_bits_spent() {
816+ let mut state = 0x0bad_f00du32;
817+ let mut rand = move |m: u32| {
818+ state ^= state << 13;
819+ state ^= state >> 17;
820+ state ^= state << 5;
821+ state % m
822+ };
823+ let mut enc = CabacEnc::new(BitWriter::new(), 26, 0);
824+ let (mut predicted, mut spent) = (0i64, 0i64);
825+ for _ in 0..200 {
826+ let mut coeff = [0i32; 64];
827+ let nz = 1 + rand(20);
828+ for _ in 0..nz {
829+ let i = rand(64) as usize;
830+ let mag = 1 + rand(6) as i32 * rand(4) as i32;
831+ coeff[i] = if rand(2) == 0 { mag } else { -mag };
832+ }
833+ if coeff.iter().all(|&c| c == 0) {
834+ coeff[0] = 1;
835+ }
836+ let cost = enc.residual_block_8x8_cost(&coeff);
837+ let before = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros());
838+ enc.residual_block_8x8(&coeff);
839+ let after = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros());
840+ predicted += i64::from(cost);
841+ spent += after as i64 - before as i64;
842+ }
843+ let err = (predicted - spent).abs();
844+ assert!(
845+ err * 100 < spent,
846+ "predicted {predicted}/256 bits, spent {spent}/256"
847+ );
848+ }
788849 }
crates/ec-h264/src/enc/entropy.rsmodified+7 -0
@@ -197,6 +197,13 @@ impl EncEntropy {
197197 /// What [`Self::residual_block`] would spend on `coeff`, in 1/256ths of a
198198 /// bit, without writing it. `None` under CAVLC, whose cost a caller can
199199 /// only estimate.
200+ pub(crate) fn residual_block_8x8_cost(&self, coeff: &[i32; 64]) -> Option<u32> {
201+ match self {
202+ EncEntropy::Cavlc { .. } => None,
203+ EncEntropy::Cabac(c) => Some(c.residual_block_8x8_cost(coeff)),
204+ }
205+ }
206+
200207 pub(crate) fn residual_block_cost(
201208 &self,
202209 coeff: &[i32],
crates/ec-h264/src/enc/mb.rsmodified+102 -7
@@ -39,7 +39,7 @@ use crate::transform::{
3939
4040 use super::quant::{
4141 forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
42- quant_4x4_offset, quant_8x8, quant_chroma_dc, quant_luma_dc,
42+ quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc,
4343 };
4444 use super::{
4545 entropy::{EncEntropy, sub_block_4x4},
@@ -987,6 +987,15 @@ const RDOQ_MAX_LEVEL: i32 = 2;
987987 /// back; what pays is only the pruning.
988988 const RDOQ_CHROMA_DEAD_ZONE: i32 = 6;
989989
990+/// The rounding the 8x8 luma path keeps under the search. It answers the way
991+/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in
992+/// `transform_8x8` flag against flag-off, which isolates this path because the
993+/// flag-off curve does not run through it. Film 3840x1608 / screen capture
994+/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075,
995+/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough
996+/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do.
997+const RDOQ8_DEAD_ZONE: i32 = 2;
998+
990999 /// Rate-distortion quantisation of one inter luma block: each level is offered
9911000 /// the two cheaper magnitudes below it, and takes one when the squared error it
9921001 /// gives up costs less than the bits it saves.
@@ -1188,6 +1197,7 @@ fn code_luma_i16(
11881197 }
11891198
11901199 /// Chroma residual for both components (8.5.11 + the AC path).
1200+#[allow(clippy::too_many_arguments)]
11911201 fn code_chroma(
11921202 pic: &mut Picture,
11931203 e: &MbEnc<'_>,
@@ -1574,9 +1584,11 @@ fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8:
15741584 /// Residual of one 8x8 luma block against the prediction already in the
15751585 /// plane: forward transform, quantise, and — when anything survives —
15761586 /// reconstruct with the decoder's own inverse. Returns the non-zero count.
1587+#[allow(clippy::too_many_arguments)]
15771588 fn code_block_8x8(
15781589 pic: &mut Picture,
15791590 e: &MbEnc<'_>,
1591+ w: &EncEntropy,
15801592 x: usize,
15811593 y: usize,
15821594 qp: i32,
@@ -1592,16 +1604,29 @@ fn code_block_8x8(
15921604 - i32::from(pic.y.data[origin + ry * stride + rx]);
15931605 }
15941606 }
1595- let nz = quant_8x8(&forward_8x8(&d), &e.ls8, qp, intra, out);
1607+ let rdoq = !intra && w.is_cabac();
1608+ let fwd = forward_8x8(&d);
1609+ let mut nz = if rdoq {
1610+ quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out)
1611+ } else {
1612+ quant_8x8(&fwd, &e.ls8, qp, intra, out)
1613+ };
15961614 if nz == 0 {
15971615 return 0;
15981616 }
1617+ if rdoq {
1618+ nz = rdoq_8x8(e, w, &d, out, qp);
1619+ if nz == 0 {
1620+ return 0;
1621+ }
1622+ }
15991623 let mut raster = [0i32; 64];
16001624 unzigzag_8x8(out, &mut raster);
16011625 dequant_8x8(&mut raster, &e.ls8, qp);
16021626 let mut resid = [0i32; 64];
16031627 inverse_transform_8x8(&raster, &mut resid);
1604- if !intra
1628+ if !rdoq
1629+ && !intra
16051630 && !worth_coding(
16061631 &d,
16071632 &resid,
@@ -1619,9 +1644,11 @@ fn code_block_8x8(
16191644 /// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
16201645 /// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
16211646 /// samples, and every 4x4 mode slot of a block carries its mode.
1647+#[allow(clippy::too_many_arguments)]
16221648 fn code_intra_8x8(
16231649 pic: &mut Picture,
16241650 e: &MbEnc<'_>,
1651+ w: &EncEntropy,
16251652 mb_x: usize,
16261653 mb_y: usize,
16271654 qp: i32,
@@ -1669,7 +1696,7 @@ fn code_intra_8x8(
16691696 let row = origin + ry * stride;
16701697 pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
16711698 }
1672- if code_block_8x8(pic, e, x, y, qp, true, &mut lv.luma8[blk8]) > 0 {
1699+ if code_block_8x8(pic, e, w, x, y, qp, true, &mut lv.luma8[blk8]) > 0 {
16731700 lv.cbp_luma |= 1 << blk8;
16741701 }
16751702 }
@@ -1681,6 +1708,7 @@ fn code_intra_8x8(
16811708 fn code_luma_8x8(
16821709 pic: &mut Picture,
16831710 e: &MbEnc<'_>,
1711+ w: &EncEntropy,
16841712 mb_x: usize,
16851713 mb_y: usize,
16861714 qp: i32,
@@ -1689,12 +1717,79 @@ fn code_luma_8x8(
16891717 lv.trans8 = true;
16901718 for blk8 in 0..4 {
16911719 let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
1692- if code_block_8x8(pic, e, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
1720+ if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
16931721 lv.cbp_luma |= 1 << blk8;
16941722 }
16951723 }
16961724 }
16971725
1726+/// Squared error of coding `levels` as an 8x8 block, in its pixels.
1727+fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 {
1728+ let mut raster = [0i32; 64];
1729+ unzigzag_8x8(levels, &mut raster);
1730+ dequant_8x8(&mut raster, &e.ls8, qp);
1731+ let mut resid = [0i32; 64];
1732+ inverse_transform_8x8(&raster, &mut resid);
1733+ let mut ssd = 0i64;
1734+ for k in 0..64 {
1735+ let d = i64::from(source[k]) - i64::from(resid[k]);
1736+ ssd += d * d;
1737+ }
1738+ ssd
1739+}
1740+
1741+/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the
1742+/// CABAC coder's own price, with the 8x8 block's own contexts.
1743+fn rdoq_8x8(
1744+ e: &MbEnc<'_>,
1745+ w: &EncEntropy,
1746+ source: &[i32; 64],
1747+ levels: &mut [i32; 64],
1748+ qp: i32,
1749+) -> u8 {
1750+ let Some(bits) = w.residual_block_8x8_cost(levels) else {
1751+ return levels.iter().filter(|&&l| l != 0).count() as u8;
1752+ };
1753+ let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
1754+ let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
1755+ for pos in (0..64).rev() {
1756+ let level = levels[pos];
1757+ if level == 0 {
1758+ continue;
1759+ }
1760+ let mag = level.abs();
1761+ if mag > RDOQ_MAX_LEVEL {
1762+ continue;
1763+ }
1764+ let mut tried = mag;
1765+ for candidate in [mag - 1, 0] {
1766+ if candidate == tried {
1767+ continue;
1768+ }
1769+ tried = candidate;
1770+ let keep = levels[pos];
1771+ levels[pos] = candidate * level.signum();
1772+ let bits = w
1773+ .residual_block_8x8_cost(levels)
1774+ .expect("CAVLC returned early");
1775+ let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
1776+ if trial < cost {
1777+ cost = trial;
1778+ } else {
1779+ levels[pos] = keep;
1780+ break;
1781+ }
1782+ }
1783+ }
1784+ // The whole block against nothing, on the same exact price.
1785+ let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
1786+ if ssd_zero as f64 <= cost {
1787+ *levels = [0; 64];
1788+ return 0;
1789+ }
1790+ levels.iter().filter(|&&l| l != 0).count() as u8
1791+}
1792+
16981793 /// Squared error of the luma macroblock against the source.
16991794 fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
17001795 let stride = pic.y.stride;
@@ -2057,7 +2152,7 @@ fn encode_intra_mb(
20572152 let mut lv8 = chroma_lv.clone();
20582153 let mut recon8 = [0u8; 256];
20592154 let cost8 = if e.t8x8_intra(mb_y) {
2060- let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8);
2155+ let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8);
20612156 modes8 = m8;
20622157 pred_modes8 = p8;
20632158 save_luma(pic, mb_x, mb_y, &mut recon8);
@@ -2541,7 +2636,7 @@ fn encode_inter_mb(
25412636 save_luma(pic, mb_x, mb_y, &mut recon4);
25422637 restore_luma(pic, mb_x, mb_y, &pred);
25432638 let mut lv8 = chroma_lv;
2544- code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8);
2639+ code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8);
25452640 let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
25462641 let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64;
25472642 if cost8 + e.lambda * e.t8x8_margin_bits < cost4 {
crates/ec-h264/src/enc/quant.rsmodified+15 -5
@@ -162,10 +162,6 @@ pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] {
162162 /// precomputed shift because [`forward_8x8`]'s coefficients already carry
163163 /// far more headroom than a `<<15`-ish fixed point would give.
164164 #[inline]
165-fn round_div(raw: i64, denom: i64, intra: bool) -> i64 {
166- (raw + denom / if intra { 3 } else { 6 }) / denom
167-}
168-
169165 /// Quantise an 8x8 [`forward_8x8`] output into scan (zig-zag) order, undoing
170166 /// both the `2_088_025` transform gain and the per-position [`LevelScale8x8`]
171167 /// / QP scale that [`crate::transform::dequant_8x8`] will re-apply.
@@ -175,6 +171,20 @@ pub(crate) fn quant_8x8(
175171 qp: i32,
176172 intra: bool,
177173 out: &mut [i32; 64],
174+) -> u8 {
175+ quant_8x8_offset(coef, ls, qp, if intra { 3 } else { 6 }, out)
176+}
177+
178+/// [`quant_8x8`] with the rounding offset named outright: the level is
179+/// `(raw + denom / divisor) / denom`, so a divisor of 2 rounds to nearest and
180+/// 6 is the inter dead zone. A search that offers smaller magnitudes wants to
181+/// pick this itself.
182+pub(crate) fn quant_8x8_offset(
183+ coef: &[i64; 64],
184+ ls: &LevelScale8x8,
185+ qp: i32,
186+ divisor: i32,
187+ out: &mut [i32; 64],
178188 ) -> u8 {
179189 // 11560^2 / 64, see FWD8's doc comment.
180190 const TOTAL_SCALE: i64 = 2_088_025;
@@ -193,7 +203,7 @@ pub(crate) fn quant_8x8(
193203 } else {
194204 (c.unsigned_abs() as i64, denom << -p)
195205 };
196- let level = round_div(num, denom, intra) as i32;
206+ let level = ((num + denom / i64::from(divisor)) / denom) as i32;
197207 if level != 0 {
198208 nz += 1;
199209 }
lanes/h264x264-r2.report.mdmodified+28 -0
@@ -383,3 +383,31 @@ x264's trellis is worth 0.193 dB on the film clip and 0.208 on the screen
383383 capture, so the two slices together take 0.135 and 0.032 of it.
384384
385385 The 8x8 luma transform path is still untouched.
386+
387+## The same price, applied to the 8x8 transform path
388+
389+`code_block_8x8` now quantises, searches and zero-tests its inter blocks the
390+way the 4x4 luma path does, on a `residual_block_8x8_cost` that shares its
391+bins with the writer (asserted to 1% over 200 random 64-coefficient blocks,
392+`residual_8x8_cost_predicts_the_bits_spent`).
393+
394+The x264 comparison cannot see this path -- both sides run with `8x8dct=0` at
395+matched features -- so it is measured as BD-PSNR of the opt-in `transform_8x8`
396+flag against flag-off, which isolates it: the flag-off curve does not go
397+through an 8x8 block.
398+
399+| rounding under the search | film 3840x1608 | screen capture 2560x1440 |
400+|---|---|---|
401+| no search (baseline) | +0.535 | +0.042 |
402+| 1/6 | +0.551 | -- |
403+| 1/3 | +0.605 | +0.075 |
404+| **1/2** | **+0.619** | +0.067 |
405+
406+8x8 answers the way 4x4 luma did and chroma did not: its blocks carry enough
407+coefficients for the wider rounding to pay for itself. Landed at 1/2 --
408+film +0.535 -> +0.619 (0.084 dB), screen capture +0.042 -> +0.067. The average
409+8x8 macroblock share rises with it (19.0% -> 20.2% film), which is the flag
410+being chosen more often now that the blocks it picks are cheaper.
411+
412+`transform_8x8` is still opt-in, so this changes no default stream byte; the
413+open decision to flip that default is worth 0.084 dB more than it was.