forge
Explore
Log in

Don't you dare go Hollow

h264: choose inter luma levels against the CABAC coder's own price

Browse files at this commit

47083d34ae11b74b563f2816b1f73611a65a122eAhmet Kaan GümüşParent: c844bb5
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.rsmodified+234 -88
@@ -375,18 +375,7 @@ impl CabacEnc {
375375
376376 /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string.
377377 fn ueg_suffix(&mut self, value: u32, k0: u32) {
378- let mut k = k0;
379- let mut v = value;
380- while v >= 1 << k {
381- self.bypass(true);
382- v -= 1 << k;
383- k += 1;
384- }
385- self.bypass(false);
386- while k > 0 {
387- k -= 1;
388- self.bypass(v >> k & 1 != 0);
389- }
378+ ueg_suffix_bins(self, value, k0);
390379 }
391380
392381 /// transform_size_8x8_flag (9.3.3.1.1.10), mirroring the decoder's
@@ -418,7 +407,7 @@ impl CabacEnc {
418407 }
419408 }
420409 }
421- self.encode_levels(coeff, last, OFF_ABS_8X8, false)
410+ levels_bins(self, coeff, last, OFF_ABS_8X8, false)
422411 }
423412
424413 /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the
@@ -438,104 +427,221 @@ impl CabacEnc {
438427 "cat 5 goes through residual_block_8x8"
439428 );
440429 let cat_i = cat.ctx_block_cat();
441- let max = cat.max_num_coeff();
442- let last = (0..max).rev().find(|&i| coeff[i] != 0);
430+ let (a, b) = self.cbf_neighbours(cat, na, nb);
431+ residual_bins(self, coeff, cat, OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b)
432+ }
433+
434+ /// The same bins [`Self::residual_block`] would write, costed against the
435+ /// context state as it stands, in 1/256ths of a bit. Nothing is written and
436+ /// no state moves: this is what a quantisation decision asks before it
437+ /// commits.
438+ pub(crate) fn residual_block_cost(
439+ &self,
440+ coeff: &[i32],
441+ cat: BlockCat,
442+ na: Option<u8>,
443+ nb: Option<u8>,
444+ ) -> u32 {
445+ let cat_i = cat.ctx_block_cat();
446+ let (a, b) = self.cbf_neighbours(cat, na, nb);
447+ let mut sink = CostSink {
448+ state: self.state,
449+ bits: 0,
450+ };
451+ residual_bins(
452+ &mut sink,
453+ coeff,
454+ cat,
455+ OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b,
456+ );
457+ sink.bits
458+ }
443459
460+ /// The coded_block_flag neighbour conditions (9.3.3.1.1.9), which the cost
461+ /// path needs on exactly the terms the write path uses them.
462+ fn cbf_neighbours(&self, cat: BlockCat, na: Option<u8>, nb: Option<u8>) -> (usize, usize) {
444463 let intra = self.cur_intra;
445464 let cond = |n: Option<u8>| match n {
446465 None => usize::from(intra),
447466 Some(v) => usize::from(v != 0),
448467 };
449- let (a, b) = match cat {
468+ match cat {
450469 BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)),
451470 BlockCat::ChromaDc(c) => (
452471 self.dc_cbf(self.ctx.a, 1 + c),
453472 self.dc_cbf(self.ctx.b, 1 + c),
454473 ),
455474 _ => (cond(na), cond(nb)),
475+ }
476+ }
477+
478+ fn dc_cbf(&self, n: Option<MbInfo>, which: u8) -> usize {
479+ match n {
480+ None => usize::from(self.cur_intra),
481+ Some(i) if i.flags & FLAG_PCM != 0 => 1,
482+ Some(i) => usize::from(i.dc_cbf & (1 << which) != 0),
483+ }
484+ }
485+}
486+
487+/// Where a residual block's bins go: the arithmetic coder that writes them, or
488+/// the counter that only prices them.
489+///
490+/// The two share one body so that a price can never drift from what the writer
491+/// would spend — the whole value of an exact rate is that it is the same code.
492+trait BinSink {
493+ /// A context-coded bin (9.3.4.1).
494+ fn bin(&mut self, ctx_idx: usize, bin: bool);
495+ /// An equiprobable bin (9.3.4.3).
496+ fn bypass_bin(&mut self, bin: bool);
497+}
498+
499+impl BinSink for CabacEnc {
500+ fn bin(&mut self, ctx_idx: usize, bin: bool) {
501+ self.decision(ctx_idx, bin);
502+ }
503+ fn bypass_bin(&mut self, bin: bool) {
504+ self.bypass(bin);
505+ }
506+}
507+
508+/// Bits, in 1/256ths, that a bin costs against each of the 64 probability
509+/// states: `[2 * pStateIdx]` for a bin equal to the MPS, `+ 1` for the LPS.
510+///
511+/// The state's LPS probability is the one clause 9.3.3.2.1 is built from,
512+/// p(sigma) = 0.5 * (0.01875 / 0.5)^(sigma / 63), so the entry is -log2 of it.
513+/// State 0 costs a whole bit either way, state 63 costs 7/256 of one for the
514+/// MPS: this spread is what makes an exact rate worth measuring at all.
515+const BIN_COST: [u16; 128] = [
516+ 256, 256, 238, 275, 221, 294, 206, 314, 192, 333, 180, 352, 168, 371, 157, 391, 148, 410, 139,
517+ 429, 130, 448, 122, 468, 115, 487, 108, 506, 102, 525, 96, 545, 90, 564, 85, 583, 80, 602, 76,
518+ 622, 72, 641, 68, 660, 64, 679, 60, 699, 57, 718, 54, 737, 51, 756, 48, 776, 46, 795, 43, 814,
519+ 41, 833, 39, 853, 37, 872, 35, 891, 33, 910, 31, 930, 29, 949, 28, 968, 26, 987, 25, 1007, 24,
520+ 1026, 22, 1045, 21, 1064, 20, 1084, 19, 1103, 18, 1122, 17, 1141, 16, 1161, 15, 1180, 15, 1199,
521+ 14, 1218, 13, 1238, 12, 1257, 12, 1276, 11, 1295, 11, 1315, 10, 1334, 10, 1353, 9, 1372, 9,
522+ 1392, 8, 1411, 8, 1430, 7, 1449, 7, 1469,
523+];
524+
525+/// A [`BinSink`] that prices bins instead of writing them, carrying its own
526+/// copy of the context state so the adaptation inside the block is priced too.
527+struct CostSink {
528+ state: [u8; NUM_CTX],
529+ /// 1/256ths of a bit.
530+ bits: u32,
531+}
532+
533+impl BinSink for CostSink {
534+ fn bin(&mut self, ctx_idx: usize, bin: bool) {
535+ let s = self.state[ctx_idx];
536+ let p = usize::from(s >> 1);
537+ let mps = s & 1 != 0;
538+ self.bits += u32::from(BIN_COST[2 * p + usize::from(bin != mps)]);
539+ self.state[ctx_idx] = if bin != mps {
540+ let mps = if p == 0 { !mps } else { mps };
541+ (crate::cabac_tables::TRANS_LPS[p] << 1) | u8::from(mps)
542+ } else {
543+ (crate::cabac_tables::TRANS_MPS[p] << 1) | u8::from(mps)
456544 };
457- let Some(last) = last else {
458- self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, false);
459- return 0;
460- };
461- self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, true);
462-
463- // Significance map. The decoder stops at the last significant position
464- // and infers the final coefficient, so nothing is written past `last`.
465- let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i];
466- let last_base = OFF_LAST + SIG_CAT_OFF[cat_i];
467- for i in 0..max - 1 {
468- let inc = sig_inc(cat, i);
469- let significant = coeff[i] != 0;
470- self.decision(sig_base + inc, significant);
471- if significant {
472- self.decision(last_base + inc, i == last);
473- if i == last {
474- break;
475- }
545+ }
546+ fn bypass_bin(&mut self, _bin: bool) {
547+ self.bits += 256;
548+ }
549+}
550+
551+/// coded_block_flag, the significance map and the levels of one residual block
552+/// (7.3.5.3.3), against a caller-derived coded_block_flag context.
553+fn residual_bins<S: BinSink>(s: &mut S, coeff: &[i32], cat: BlockCat, cbf_ctx: usize) -> u8 {
554+ let cat_i = cat.ctx_block_cat();
555+ let max = cat.max_num_coeff();
556+ let Some(last) = (0..max).rev().find(|&i| coeff[i] != 0) else {
557+ s.bin(cbf_ctx, false);
558+ return 0;
559+ };
560+ s.bin(cbf_ctx, true);
561+
562+ // Significance map. The decoder stops at the last significant position
563+ // and infers the final coefficient, so nothing is written past `last`.
564+ let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i];
565+ let last_base = OFF_LAST + SIG_CAT_OFF[cat_i];
566+ for i in 0..max - 1 {
567+ let inc = sig_inc(cat, i);
568+ let significant = coeff[i] != 0;
569+ s.bin(sig_base + inc, significant);
570+ if significant {
571+ s.bin(last_base + inc, i == last);
572+ if i == last {
573+ break;
476574 }
477575 }
576+ }
478577
479- self.encode_levels(coeff, last, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3)
578+ levels_bins(s, coeff, last, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3)
579+}
580+
581+/// The UEGk suffix of 9.3.2.3, all bypass bins.
582+fn ueg_suffix_bins<S: BinSink>(s: &mut S, value: u32, k0: u32) {
583+ let mut k = k0;
584+ let mut v = value;
585+ while v >= 1 << k {
586+ s.bypass_bin(true);
587+ v -= 1 << k;
588+ k += 1;
589+ }
590+ s.bypass_bin(false);
591+ while k > 0 {
592+ k -= 1;
593+ s.bypass_bin(v >> k & 1 != 0);
480594 }
595+}
481596
482- /// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest
483- /// scanning position first (9.3.3.1.3 counters). Returns the number of
484- /// levels written.
485- fn encode_levels(
486- &mut self,
487- coeff: &[i32],
488- last: usize,
489- abs_base: usize,
490- chroma_dc: bool,
491- ) -> u8 {
492- let mut num_eq1 = 0u32;
493- let mut num_gt1 = 0u32;
494- let mut total = 0u8;
495- for pos in (0..=last).rev() {
496- let level = coeff[pos];
497- if level == 0 {
498- continue;
499- }
500- let inc0 = if num_gt1 != 0 {
501- 0
502- } else {
503- 4.min(1 + num_eq1) as usize
504- };
505- let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize;
506- let abs_minus1 = level.unsigned_abs() - 1;
507- let mut prefix = 0u32;
508- while prefix < 14 {
509- let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };
510- if prefix < abs_minus1 {
511- self.decision(ctx_idx, true);
512- prefix += 1;
513- } else {
514- self.decision(ctx_idx, false);
515- break;
516- }
517- }
518- if abs_minus1 >= 14 {
519- self.ueg_suffix(abs_minus1 - 14, 0);
520- }
521- self.bypass(level < 0);
522- if abs_minus1 == 0 {
523- num_eq1 += 1;
597+/// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest
598+/// scanning position first (9.3.3.1.3 counters). Returns the number of
599+/// levels written.
600+fn levels_bins<S: BinSink>(
601+ s: &mut S,
602+ coeff: &[i32],
603+ last: usize,
604+ abs_base: usize,
605+ chroma_dc: bool,
606+) -> u8 {
607+ let mut num_eq1 = 0u32;
608+ let mut num_gt1 = 0u32;
609+ let mut total = 0u8;
610+ for pos in (0..=last).rev() {
611+ let level = coeff[pos];
612+ if level == 0 {
613+ continue;
614+ }
615+ let inc0 = if num_gt1 != 0 {
616+ 0
617+ } else {
618+ 4.min(1 + num_eq1) as usize
619+ };
620+ let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize;
621+ let abs_minus1 = level.unsigned_abs() - 1;
622+ let mut prefix = 0u32;
623+ while prefix < 14 {
624+ let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };
625+ if prefix < abs_minus1 {
626+ s.bin(ctx_idx, true);
627+ prefix += 1;
524628 } else {
525- num_gt1 += 1;
629+ s.bin(ctx_idx, false);
630+ break;
526631 }
527- total += 1;
528632 }
529- total
530- }
531-
532- fn dc_cbf(&self, n: Option<MbInfo>, which: u8) -> usize {
533- match n {
534- None => usize::from(self.cur_intra),
535- Some(i) if i.flags & FLAG_PCM != 0 => 1,
536- Some(i) => usize::from(i.dc_cbf & (1 << which) != 0),
633+ if abs_minus1 >= 14 {
634+ ueg_suffix_bins(s, abs_minus1 - 14, 0);
537635 }
636+ s.bypass_bin(level < 0);
637+ if abs_minus1 == 0 {
638+ num_eq1 += 1;
639+ } else {
640+ num_gt1 += 1;
641+ }
642+ total += 1;
538643 }
644+ total
539645 }
540646
541647 #[cfg(test)]
@@ -639,4 +745,44 @@ mod tests {
639745 assert!(dec.more_macroblocks().expect("terminate"), "block {i} end");
640746 }
641747 }
748+ /// The price is the thing itself: `residual_block_cost` predicts what
749+ /// `residual_block` then spends. A quantisation decision that trusts a
750+ /// wrong price picks wrong levels, and the error would be invisible in the
751+ /// stream — it only shows up as lost dB — so it is asserted here in
752+ /// 1/256ths of a bit against the arithmetic coder's own output.
753+ #[test]
754+ fn residual_cost_predicts_the_bits_spent() {
755+ let mut state = 0x1234_5678u32;
756+ let mut rand = move |m: u32| {
757+ state ^= state << 13;
758+ state ^= state >> 17;
759+ state ^= state << 5;
760+ state % m
761+ };
762+ let mut enc = CabacEnc::new(BitWriter::new(), 26, 0);
763+ let (mut predicted, mut spent) = (0i64, 0i64);
764+ for _ in 0..400 {
765+ let mut coeff = [0i32; 16];
766+ let nz = rand(8);
767+ for _ in 0..nz {
768+ let i = rand(16) as usize;
769+ let mag = 1 + rand(6) as i32 * rand(4) as i32;
770+ coeff[i] = if rand(2) == 0 { mag } else { -mag };
771+ }
772+ let (na, nb) = (Some(rand(4) as u8), Some(rand(4) as u8));
773+ let cost = enc.residual_block_cost(&coeff, BlockCat::Luma4x4, na, nb);
774+ let before = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros());
775+ enc.residual_block(&coeff, BlockCat::Luma4x4, na, nb);
776+ let after = enc.bit_len() * 256 + u64::from(enc.range.leading_zeros());
777+ predicted += i64::from(cost);
778+ spent += after as i64 - before as i64;
779+ }
780+ // Per block the arithmetic coder carries fractional bits across the
781+ // boundary, so the claim is on the total: within 1%.
782+ let err = (predicted - spent).abs();
783+ assert!(
784+ err * 100 < spent,
785+ "predicted {predicted}/256 bits, spent {spent}/256"
786+ );
787+ }
642788 }
crates/ec-h264/src/enc/entropy.rsmodified+16 -0
@@ -194,6 +194,22 @@ impl EncEntropy {
194194 }
195195 }
196196
197+ /// What [`Self::residual_block`] would spend on `coeff`, in 1/256ths of a
198+ /// bit, without writing it. `None` under CAVLC, whose cost a caller can
199+ /// only estimate.
200+ pub(crate) fn residual_block_cost(
201+ &self,
202+ coeff: &[i32],
203+ cat: BlockCat,
204+ na: Option<u8>,
205+ nb: Option<u8>,
206+ ) -> Option<u32> {
207+ match self {
208+ EncEntropy::Cavlc { .. } => None,
209+ EncEntropy::Cabac(c) => Some(c.residual_block_cost(coeff, cat, na, nb)),
210+ }
211+ }
212+
197213 pub(crate) fn is_cabac(&self) -> bool {
198214 matches!(self, EncEntropy::Cabac(_))
199215 }
crates/ec-h264/src/enc/mb.rsmodified+144 -32
@@ -17,32 +17,32 @@ use wide::i16x16;
1717
1818 use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
1919 use crate::decoder::{
20- chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors,
20+ MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors,
2121 };
22-use crate::dpb::{Picture, Plane8, BLK_SKIP};
22+use crate::dpb::{BLK_SKIP, Picture, Plane8};
2323 use crate::entropy::{
24- BlockCat, MbCtx, MbInfo, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP,
25- FLAG_TRANS8X8,
24+ BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
25+ MbCtx, MbInfo,
2626 };
27-use crate::inter::{integer_origin, mc_chroma, mc_luma, RefPlane};
28-use crate::mv::{neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd, MvCtx};
27+use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma};
28+use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
2929 use crate::pred::{
30- add_residual_4x4, add_residual_8x8, filter_nbr8, pred_16x16, pred_4x4, pred_8x8,
31- pred_chroma_8x8, PlaneWindow,
30+ PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
31+ pred_chroma_8x8,
3232 };
3333 use crate::tables::{BLK4_POS, CHROMA_QP};
3434 use crate::transform::{
35- chroma_dc_transform_420, dequant_4x4, dequant_8x8, inverse_transform_4x4,
36- inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, unzigzag_ac15, LevelScale4x4,
37- LevelScale8x8,
35+ LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,
36+ inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
37+ unzigzag_ac15,
3838 };
3939
4040 use super::quant::{
41- forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8,
42- quant_chroma_dc, quant_luma_dc,
41+ forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
42+ quant_4x4_offset, quant_8x8, quant_chroma_dc, quant_luma_dc,
4343 };
4444 use super::{
45- entropy::{sub_block_4x4, EncEntropy},
45+ entropy::{EncEntropy, sub_block_4x4},
4646 lambda_ssd,
4747 };
4848
@@ -316,7 +316,6 @@ fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
316316 (lambda * bits).round() as i32
317317 }
318318
319-
320319 /// Everything one macroblock's coding writes into the picture, kept so that a
321320 /// branch can be coded, measured and undone.
322321 struct MbState {
@@ -602,7 +601,6 @@ fn intra_pre_cost(
602601 /// below a half and falls away above it.
603602 const MV_BITS_WEIGHT: f64 = 0.5;
604603
605-
606604 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
607605 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
608606 enum PShape {
@@ -857,9 +855,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
857855
858856 /// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
859857 /// prediction already in the plane.
858+#[allow(clippy::too_many_arguments)]
860859 fn code_luma_4x4(
861860 pic: &mut Picture,
862861 e: &MbEnc<'_>,
862+ w: &EncEntropy,
863863 mb_x: usize,
864864 mb_y: usize,
865865 qp: i32,
@@ -880,7 +880,15 @@ fn code_luma_4x4(
880880 }
881881 let source = d;
882882 forward_4x4(&mut d);
883- let nz = quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]);
883+ let rdoq = !intra && w.is_cabac();
884+ let mut nz = if rdoq {
885+ quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk])
886+ } else {
887+ quant_4x4(&d, qp, intra, false, &mut lv.luma[blk])
888+ };
889+ if rdoq && nz != 0 {
890+ nz = rdoq_4x4(e, w, &source, &mut lv.luma[blk], qp);
891+ }
884892 lv.luma_nz[blk] = nz;
885893 if nz == 0 {
886894 continue;
@@ -895,7 +903,8 @@ fn code_luma_4x4(
895903 // half of rate-distortion optimised quantisation, and the half that
896904 // pays. Intra blocks are left alone: their reconstruction is what the
897905 // next block in the macroblock predicts from.
898- if !intra
906+ if !rdoq
907+ && !intra
899908 && !worth_coding(
900909 &source,
901910 &resid,
@@ -912,6 +921,118 @@ fn code_luma_4x4(
912921 }
913922 }
914923
924+/// Squared error of coding `levels`, in the pixels the block reconstructs to.
925+fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32) -> i64 {
926+ let mut raster = [0i32; 16];
927+ unzigzag(levels, &mut raster);
928+ dequant_4x4(&mut raster, &e.ls, qp, false);
929+ let mut resid = [0i32; 16];
930+ inverse_transform_4x4(&raster, &mut resid);
931+ let mut ssd = 0i64;
932+ for i in 0..16 {
933+ let d = i64::from(source[i] - resid[i]);
934+ ssd += d * d;
935+ }
936+ ssd
937+}
938+
939+/// How much of the mode-decision lambda rate-distortion quantisation uses.
940+///
941+/// The bits here are the coder's own, not an estimate, so there is no
942+/// over-estimate to correct for and the scale starts at 1. Swept over 0.5,
943+/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a
944+/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5
945+/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is
946+/// the crossing point that costs neither (-0.628 and -0.471). Table in
947+/// `lanes/h264x264-r2.report.md`.
948+const RDOQ_LAMBDA: f64 = 1.0;
949+
950+/// The dead zone rate-distortion quantisation starts from, as a divisor of the
951+/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which
952+/// has already thrown away the levels this search would weigh -- a search
953+/// bounded by the heuristic it replaces measures the heuristic. This is the
954+/// half of the change that pays: 1/6 -> 1/2 under the same search is worth
955+/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read
956+/// -0.647 and -0.677 dB where 1/2 reads -0.630.
957+const RDOQ_DEAD_ZONE: i32 = 2;
958+
959+/// The largest level the search offers a smaller magnitude to. A big level is
960+/// carrying real signal and never wins by shrinking; bounding the search is
961+/// what keeps it free. Unbounded it tripled the synthetic clip's encode time
962+/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over
963+/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and
964+/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture.
965+const RDOQ_MAX_LEVEL: i32 = 2;
966+
967+/// Rate-distortion quantisation of one inter luma block: each level is offered
968+/// the two cheaper magnitudes below it, and takes one when the squared error it
969+/// gives up costs less than the bits it saves.
970+///
971+/// The rate is the CABAC coder's own price for the whole block against the
972+/// context state as it stands, so dropping a level is priced with the
973+/// significance map that follows from it — which is where most of the saving
974+/// is. Intra blocks stay out: their reconstruction is what the next block in
975+/// the macroblock predicts from, so a level changed here would move a
976+/// prediction the decision cannot see.
977+fn rdoq_4x4(
978+ e: &MbEnc<'_>,
979+ w: &EncEntropy,
980+ source: &[i32; 16],
981+ levels: &mut [i32; 16],
982+ qp: i32,
983+) -> u8 {
984+ let Some(bits) = w.residual_block_cost(levels, BlockCat::Luma4x4, Some(1), Some(1)) else {
985+ return levels.iter().filter(|&&l| l != 0).count() as u8;
986+ };
987+ let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
988+ let mut cost = block_ssd(e, source, levels, qp) as f64 + lambda * f64::from(bits);
989+ // Highest scanning position first: dropping the last significant level is
990+ // what shortens the significance map, so it is tried while the levels
991+ // above it are still gone.
992+ for pos in (0..16).rev() {
993+ let level = levels[pos];
994+ if level == 0 {
995+ continue;
996+ }
997+ let mag = level.abs();
998+ if mag > RDOQ_MAX_LEVEL {
999+ continue;
1000+ }
1001+ let mut tried = mag;
1002+ for candidate in [mag - 1, 0] {
1003+ if candidate == tried {
1004+ continue;
1005+ }
1006+ tried = candidate;
1007+ let keep = levels[pos];
1008+ levels[pos] = candidate * level.signum();
1009+ let Some(bits) = w.residual_block_cost(levels, BlockCat::Luma4x4, Some(1), Some(1))
1010+ else {
1011+ unreachable!("CAVLC returned early");
1012+ };
1013+ let trial = block_ssd(e, source, levels, qp) as f64 + lambda * f64::from(bits);
1014+ if trial < cost {
1015+ cost = trial;
1016+ } else {
1017+ levels[pos] = keep;
1018+ }
1019+ }
1020+ }
1021+ // And the block as a whole: zeroing it drops the coded_block_pattern bit as
1022+ // well as every level, which no single-coefficient step can see. This is
1023+ // the same decision `worth_coding` makes for the paths without an exact
1024+ // rate, made here with one.
1025+ let zero_bits = w
1026+ .residual_block_cost(&[0; 16], BlockCat::Luma4x4, Some(1), Some(1))
1027+ .expect("CABAC");
1028+ let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
1029+ if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost {
1030+ *levels = [0; 16];
1031+ return 0;
1032+ }
1033+ levels.iter().filter(|&&l| l != 0).count() as u8
1034+}
1035+
9151036 /// How much of the mode-decision lambda the zero-block test uses.
9161037 ///
9171038 /// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
@@ -2162,8 +2283,7 @@ fn ssd_mb_deblocked(
21622283 for row in 0..16 {
21632284 let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
21642285 for x in 0..16 {
2165- let d =
2166- i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
2286+ let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
21672287 sum += d * d;
21682288 }
21692289 }
@@ -2173,11 +2293,7 @@ fn ssd_mb_deblocked(
21732293 /// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its
21742294 /// macroblock edges, 3 on the internal luma edges.
21752295 fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 {
2176- if edge == 0 {
2177- 4
2178- } else {
2179- 3
2180- }
2296+ if edge == 0 { 4 } else { 3 }
21812297 }
21822298
21832299 /// Rough bit cost of a macroblock's luma residual.
@@ -2216,11 +2332,7 @@ fn block_bits(b: &[i32]) -> i64 {
22162332 n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
22172333 }
22182334 }
2219- if n > 0 {
2220- n + 6
2221- } else {
2222- 2
2223- }
2335+ if n > 0 { n + 6 } else { 2 }
22242336 }
22252337
22262338 /// Rough bit cost of a macroblock's residual, for the skip decision: a level
@@ -2381,7 +2493,7 @@ fn encode_inter_mb(
23812493 let mut pred = [0u8; 256];
23822494 save_luma(pic, mb_x, mb_y, &mut pred);
23832495 let mut lv4 = chroma_lv.clone();
2384- code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv4);
2496+ code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4);
23852497 let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
23862498 let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;
23872499 let mut recon4 = [0u8; 256];
@@ -2398,7 +2510,7 @@ fn encode_inter_mb(
23982510 restore_luma(pic, mb_x, mb_y, &recon4);
23992511 }
24002512 } else {
2401- code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
2513+ code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv);
24022514 }
24032515 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
24042516 let skip = match ssd_skip {
crates/ec-h264/src/enc/quant.rsmodified+17 -1
@@ -213,10 +213,26 @@ pub(crate) fn quant_4x4(
213213 intra: bool,
214214 skip_dc: bool,
215215 out: &mut [i32; 16],
216+) -> u8 {
217+ quant_4x4_offset(coef, qp, if intra { 3 } else { 6 }, skip_dc, out)
218+}
219+
220+/// [`quant_4x4`] with the dead zone spelled out: the rounding offset is
221+/// `1 / divisor` of a quantiser step.
222+///
223+/// Rate-distortion quantisation asks for a *smaller* dead zone than the plain
224+/// path uses, because it walks levels down itself and cannot walk them up: a
225+/// level the dead zone already dropped is not a candidate any more.
226+pub(crate) fn quant_4x4_offset(
227+ coef: &[i32; 16],
228+ qp: i32,
229+ divisor: i32,
230+ skip_dc: bool,
231+ out: &mut [i32; 16],
216232 ) -> u8 {
217233 let m = (qp % 6) as usize;
218234 let qbits = 15 + (qp / 6) as u32;
219- let f = round_offset(qbits, intra);
235+ let f = (1i32 << qbits) / divisor;
220236 let start = usize::from(skip_dc);
221237 let mut nz = 0;
222238 *out = [0; 16];
crates/ec-h264/tests/encode.rsmodified+5 -1
@@ -893,7 +893,11 @@ fn real_clip_t8x8_bd_psnr() {
893893 /// clip and 0.564 on the screen capture, and takes fewer bits at every QP
894894 /// while doing it. This clip prefers a heavier rate term in that decision
895895 /// (see the sweep in `enc/mb.rs`), which the two real clips do not.
896-const BD_PSNR_VS_X264_FLOOR: f64 = -4.6;
896+///
897+/// It moved -4.523 -> -4.073 when inter luma levels started being chosen
898+/// against the CABAC coder's own price for them (0.100 dB on the film clip,
899+/// 0.029 on the screen capture).
900+const BD_PSNR_VS_X264_FLOOR: f64 = -4.15;
897901
898902 fn have_x264() -> bool {
899903 std::process::Command::new("ffmpeg")
lanes/h264x264-r2.report.mdmodified+85 -0
@@ -267,3 +267,88 @@ which inter luma allows because its reconstruction does not feed the next
267267 block's prediction the way intra's does; and it needs a term for what a
268268 reference picture's quality is worth to the pictures that predict from it,
269269 without which more search measures worse.
270+
271+## Rate-distortion quantisation, landed on the coder's own price
272+
273+The attempt above failed on an estimate. This one prices bins with the CABAC
274+engine itself and lands 0.100 dB on the film clip, 0.029 on the screen capture
275+and 0.450 on the synthetic gate, for no measurable encode time.
276+
277+### The price is the thing itself
278+
279+`CabacEnc::residual_block_cost` runs the bins `residual_block` would write --
280+the same code, through a `BinSink` the two share -- against a copy of the
281+context state, charging each bin `-log2(p)` for its state from a 128-entry
282+table and moving the state exactly as the coder would. So a level dropped is
283+priced with the significance map that follows from it, and the adaptation
284+inside the block is priced too.
285+
286+Its accuracy is asserted, not assumed: over 400 random blocks it predicts
287+2 649 288/256 bits where the arithmetic coder then spends 2 650 112/256, an
288+error of 0.03% (`residual_cost_predicts_the_bits_spent`). A wrong price would
289+be invisible in the stream -- it would only show up as lost dB -- which is why
290+it is a test and not a comment.
291+
292+### What actually moved the numbers
293+
294+Three changes, measured one at a time against film -0.728, screen -0.500,
295+synthetic -4.523:
296+
297+| change | synthetic | film | screen |
298+|-----------------------------------------------|-----------|--------|--------|
299+| levels walked down on exact cost | -4.530 | -0.732 | -0.449 |
300+| + dead zone 1/6 -> 1/2 for the walked path | -4.229 | -0.630 | -0.496 |
301+| + whole-block zero decided on exact cost | -4.087 | -0.628 | -0.469 |
302+| + search bounded to levels <= 2 | -4.073 | -0.628 | -0.471 |
303+
304+The first row is the honest answer to the previous attempt's question: an exact
305+rate on its own buys 0.05 dB on screen content and nothing on film. **The dead
306+zone was the missing half.** A search that can only walk levels *down* cannot
307+see a level the quantiser's 1/6 dead zone already threw away, so it was
308+choosing among the survivors of a decision it was meant to replace. Quantising
309+the searched path at 1/2 -- round to nearest, x264's own arrangement when
310+trellis is on -- and letting the search take the levels back down is worth
311+0.102 dB on film and 0.301 on the synthetic clip.
312+
313+The class: **a search bounded by the heuristic it replaces measures the
314+heuristic.** The dead zone constant was swept and defended (`enc/quant.rs`
315+says the inter offset is inert across 6/64 to 32/64), and that was true --
316+of a path with no search after it.
317+
318+### The constants
319+
320+| RDOQ_LAMBDA (x lambda_ssd), dead zone | synthetic | film | screen |
321+|---------------------------------------|-----------|--------|--------|
322+| 1.0, 1/6 | -4.530 | -0.732 | -0.449 |
323+| 0.5, 1/2 | -4.203 | -0.607 | -0.620 |
324+| 1.0, 1/2 | -4.229 | -0.630 | -0.496 |
325+| 1.25, 1/2 | -4.103 | -0.657 | -0.433 |
326+| 1.5, 1/2 | -4.362 | -0.680 | -0.444 |
327+| 2.0, 1/2 | -4.526 | -- | -- |
328+| 1.0, 1/3 | -4.295 | -0.647 | -0.465 |
329+| 1.0, 1/4 | -4.416 | -0.677 | -0.465 |
330+
331+The two real clips disagree about the rate term -- film wants it lighter,
332+screen capture heavier -- and 1.0 is the crossing point that costs neither.
333+The 1.25 and 1.5 rows are what a screen-only tuning would take, at 0.03 to
334+0.05 dB of the film clip.
335+
336+Bounding the search to levels of 2 or less (`RDOQ_MAX_LEVEL`) costs nothing and
337+is what makes it free: unbounded, the search tripled our encode time on the
338+synthetic clip (1.08 s -> 3.53 s); bounded, it is 1.09 s. A large level is
339+carrying real signal and never wins by shrinking. 1, 2 and 3 read
340+-4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and -4.065/-0.629/-0.477; 2 is the
341+best of the three on the clip that gains least.
342+
343+### What is not covered
344+
345+Intra blocks stay out: their reconstruction is what the next block in the
346+macroblock predicts from, so a level changed there moves a prediction the
347+decision cannot see. Inter chroma AC and the 8x8 transform path are untouched
348+and are the next place to look -- x264's trellis covers both. The
349+coded_block_flag context the price is taken against assumes both neighbours
350+carry coefficients rather than reading them, which is a constant shift across
351+candidates except for the whole-block-zero one.
352+
353+x264's own trellis is worth 0.193 dB on the film clip and 0.208 on the screen
354+capture (measured by ablation, r2 above). We now take 0.100 and 0.029 of that.