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+183 -37
@@ -375,18 +375,7 @@ impl CabacEnc {
375 375
376 /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string.376 /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string.
377 fn ueg_suffix(&mut self, value: u32, k0: u32) {377 fn ueg_suffix(&mut self, value: u32, k0: u32) {
378- let mut k = k0;378+ ueg_suffix_bins(self, value, 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- }
390 }379 }
391 380
392 /// transform_size_8x8_flag (9.3.3.1.1.10), mirroring the decoder's381 /// transform_size_8x8_flag (9.3.3.1.1.10), mirroring the decoder's
@@ -418,7 +407,7 @@ impl CabacEnc {
418 }407 }
419 }408 }
420 }409 }
421- self.encode_levels(coeff, last, OFF_ABS_8X8, false)410+ levels_bins(self, coeff, last, OFF_ABS_8X8, false)
422 }411 }
423 412
424 /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the413 /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the
@@ -438,27 +427,137 @@ impl CabacEnc {
438 "cat 5 goes through residual_block_8x8"427 "cat 5 goes through residual_block_8x8"
439 );428 );
440 let cat_i = cat.ctx_block_cat();429 let cat_i = cat.ctx_block_cat();
441- let max = cat.max_num_coeff();430+ let (a, b) = self.cbf_neighbours(cat, na, nb);
442- let last = (0..max).rev().find(|&i| coeff[i] != 0);431+ residual_bins(self, coeff, cat, OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b)
432+ }
443 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+ }
459+
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) {
444 let intra = self.cur_intra;463 let intra = self.cur_intra;
445 let cond = |n: Option<u8>| match n {464 let cond = |n: Option<u8>| match n {
446 None => usize::from(intra),465 None => usize::from(intra),
447 Some(v) => usize::from(v != 0),466 Some(v) => usize::from(v != 0),
448 };467 };
449- let (a, b) = match cat {468+ match cat {
450 BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)),469 BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)),
451 BlockCat::ChromaDc(c) => (470 BlockCat::ChromaDc(c) => (
452 self.dc_cbf(self.ctx.a, 1 + c),471 self.dc_cbf(self.ctx.a, 1 + c),
453 self.dc_cbf(self.ctx.b, 1 + c),472 self.dc_cbf(self.ctx.b, 1 + c),
454 ),473 ),
455 _ => (cond(na), cond(nb)),474 _ => (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)
456 };544 };
457- let Some(last) = last else {545+ }
458- self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, false);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);
459 return 0;558 return 0;
460 };559 };
461- self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b, true);560+ s.bin(cbf_ctx, true);
462 561
463 // Significance map. The decoder stops at the last significant position562 // Significance map. The decoder stops at the last significant position
464 // and infers the final coefficient, so nothing is written past `last`.563 // and infers the final coefficient, so nothing is written past `last`.
@@ -467,23 +566,39 @@ impl CabacEnc {
467 for i in 0..max - 1 {566 for i in 0..max - 1 {
468 let inc = sig_inc(cat, i);567 let inc = sig_inc(cat, i);
469 let significant = coeff[i] != 0;568 let significant = coeff[i] != 0;
470- self.decision(sig_base + inc, significant);569+ s.bin(sig_base + inc, significant);
471 if significant {570 if significant {
472- self.decision(last_base + inc, i == last);571+ s.bin(last_base + inc, i == last);
473 if i == last {572 if i == last {
474 break;573 break;
475 }574 }
476 }575 }
477 }576 }
478 577
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);
594+ }
480 }595 }
481 596
482 /// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest597 /// 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 of598 /// scanning position first (9.3.3.1.3 counters). Returns the number of
484 /// levels written.599 /// levels written.
485- fn encode_levels(600+fn levels_bins<S: BinSink>(
486- &mut self,601+ s: &mut S,
487 coeff: &[i32],602 coeff: &[i32],
488 last: usize,603 last: usize,
489 abs_base: usize,604 abs_base: usize,
@@ -508,17 +623,17 @@ impl CabacEnc {
508 while prefix < 14 {623 while prefix < 14 {
509 let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };624 let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };
510 if prefix < abs_minus1 {625 if prefix < abs_minus1 {
511- self.decision(ctx_idx, true);626+ s.bin(ctx_idx, true);
512 prefix += 1;627 prefix += 1;
513 } else {628 } else {
514- self.decision(ctx_idx, false);629+ s.bin(ctx_idx, false);
515 break;630 break;
516 }631 }
517 }632 }
518 if abs_minus1 >= 14 {633 if abs_minus1 >= 14 {
519- self.ueg_suffix(abs_minus1 - 14, 0);634+ ueg_suffix_bins(s, abs_minus1 - 14, 0);
520 }635 }
521- self.bypass(level < 0);636+ s.bypass_bin(level < 0);
522 if abs_minus1 == 0 {637 if abs_minus1 == 0 {
523 num_eq1 += 1;638 num_eq1 += 1;
524 } else {639 } else {
@@ -529,15 +644,6 @@ impl CabacEnc {
529 total644 total
530 }645 }
531 646
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),
537- }
538- }
539-}
540-
541 #[cfg(test)]647 #[cfg(test)]
542 mod tests {648 mod tests {
543 use super::*;649 use super::*;
@@ -639,4 +745,44 @@ mod tests {
639 assert!(dec.more_macroblocks().expect("terminate"), "block {i} end");745 assert!(dec.more_macroblocks().expect("terminate"), "block {i} end");
640 }746 }
641 }747 }
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+ }
642 }788 }
crates/ec-h264/src/enc/entropy.rsmodified+16 -0
@@ -194,6 +194,22 @@ impl EncEntropy {
194 }194 }
195 }195 }
196 196
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+
197 pub(crate) fn is_cabac(&self) -> bool {213 pub(crate) fn is_cabac(&self) -> bool {
198 matches!(self, EncEntropy::Cabac(_))214 matches!(self, EncEntropy::Cabac(_))
199 }215 }
crates/ec-h264/src/enc/mb.rsmodified+144 -32
@@ -17,32 +17,32 @@ use wide::i16x16;
17 17
18 use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};18 use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
19 use crate::decoder::{19 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,
21 };21 };
22-use crate::dpb::{Picture, Plane8, BLK_SKIP};22+use crate::dpb::{BLK_SKIP, Picture, Plane8};
23 use crate::entropy::{23 use crate::entropy::{
24- BlockCat, MbCtx, MbInfo, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP,24+ BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
25- FLAG_TRANS8X8,25+ MbCtx, MbInfo,
26 };26 };
27-use crate::inter::{integer_origin, mc_chroma, mc_luma, RefPlane};27+use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma};
28-use crate::mv::{neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd, MvCtx};28+use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
29 use crate::pred::{29 use crate::pred::{
30- add_residual_4x4, add_residual_8x8, filter_nbr8, pred_16x16, pred_4x4, pred_8x8,30+ PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
31- pred_chroma_8x8, PlaneWindow,31+ pred_chroma_8x8,
32 };32 };
33 use crate::tables::{BLK4_POS, CHROMA_QP};33 use crate::tables::{BLK4_POS, CHROMA_QP};
34 use crate::transform::{34 use crate::transform::{
35- chroma_dc_transform_420, dequant_4x4, dequant_8x8, inverse_transform_4x4,35+ LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,
36- inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, unzigzag_ac15, LevelScale4x4,36+ inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
37- LevelScale8x8,37+ unzigzag_ac15,
38 };38 };
39 39
40 use super::quant::{40 use super::quant::{
41- forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8,41+ forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
42- quant_chroma_dc, quant_luma_dc,42+ quant_4x4_offset, quant_8x8, quant_chroma_dc, quant_luma_dc,
43 };43 };
44 use super::{44 use super::{
45- entropy::{sub_block_4x4, EncEntropy},45+ entropy::{EncEntropy, sub_block_4x4},
46 lambda_ssd,46 lambda_ssd,
47 };47 };
48 48
@@ -316,7 +316,6 @@ fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
316 (lambda * bits).round() as i32316 (lambda * bits).round() as i32
317 }317 }
318 318
319-
320 /// Everything one macroblock's coding writes into the picture, kept so that a319 /// Everything one macroblock's coding writes into the picture, kept so that a
321 /// branch can be coded, measured and undone.320 /// branch can be coded, measured and undone.
322 struct MbState {321 struct MbState {
@@ -602,7 +601,6 @@ fn intra_pre_cost(
602 /// below a half and falls away above it.601 /// below a half and falls away above it.
603 const MV_BITS_WEIGHT: f64 = 0.5;602 const MV_BITS_WEIGHT: f64 = 0.5;
604 603
605-
606 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.604 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
607 #[derive(Clone, Copy, PartialEq, Eq, Debug)]605 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
608 enum PShape {606 enum PShape {
@@ -857,9 +855,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
857 855
858 /// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,856 /// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
859 /// prediction already in the plane.857 /// prediction already in the plane.
858+#[allow(clippy::too_many_arguments)]
860 fn code_luma_4x4(859 fn code_luma_4x4(
861 pic: &mut Picture,860 pic: &mut Picture,
862 e: &MbEnc<'_>,861 e: &MbEnc<'_>,
862+ w: &EncEntropy,
863 mb_x: usize,863 mb_x: usize,
864 mb_y: usize,864 mb_y: usize,
865 qp: i32,865 qp: i32,
@@ -880,7 +880,15 @@ fn code_luma_4x4(
880 }880 }
881 let source = d;881 let source = d;
882 forward_4x4(&mut d);882 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+ }
884 lv.luma_nz[blk] = nz;892 lv.luma_nz[blk] = nz;
885 if nz == 0 {893 if nz == 0 {
886 continue;894 continue;
@@ -895,7 +903,8 @@ fn code_luma_4x4(
895 // half of rate-distortion optimised quantisation, and the half that903 // half of rate-distortion optimised quantisation, and the half that
896 // pays. Intra blocks are left alone: their reconstruction is what the904 // pays. Intra blocks are left alone: their reconstruction is what the
897 // next block in the macroblock predicts from.905 // next block in the macroblock predicts from.
898- if !intra906+ if !rdoq
907+ && !intra
899 && !worth_coding(908 && !worth_coding(
900 &source,909 &source,
901 &resid,910 &resid,
@@ -912,6 +921,118 @@ fn code_luma_4x4(
912 }921 }
913 }922 }
914 923
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+
915 /// How much of the mode-decision lambda the zero-block test uses.1036 /// How much of the mode-decision lambda the zero-block test uses.
916 ///1037 ///
917 /// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what1038 /// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
@@ -2162,8 +2283,7 @@ fn ssd_mb_deblocked(
2162 for row in 0..16 {2283 for row in 0..16 {
2163 let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;2284 let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
2164 for x in 0..16 {2285 for x in 0..16 {
2165- let d =2286+ let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
2166- i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
2167 sum += d * d;2287 sum += d * d;
2168 }2288 }
2169 }2289 }
@@ -2173,11 +2293,7 @@ fn ssd_mb_deblocked(
2173 /// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its2293 /// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its
2174 /// macroblock edges, 3 on the internal luma edges.2294 /// macroblock edges, 3 on the internal luma edges.
2175 fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 {2295 fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 {
2176- if edge == 0 {2296+ if edge == 0 { 4 } else { 3 }
2177- 4
2178- } else {
2179- 3
2180- }
2181 }2297 }
2182 2298
2183 /// Rough bit cost of a macroblock's luma residual.2299 /// Rough bit cost of a macroblock's luma residual.
@@ -2216,11 +2332,7 @@ fn block_bits(b: &[i32]) -> i64 {
2216 n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;2332 n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
2217 }2333 }
2218 }2334 }
2219- if n > 0 {2335+ if n > 0 { n + 6 } else { 2 }
2220- n + 6
2221- } else {
2222- 2
2223- }
2224 }2336 }
2225 2337
2226 /// Rough bit cost of a macroblock's residual, for the skip decision: a level2338 /// Rough bit cost of a macroblock's residual, for the skip decision: a level
@@ -2381,7 +2493,7 @@ fn encode_inter_mb(
2381 let mut pred = [0u8; 256];2493 let mut pred = [0u8; 256];
2382 save_luma(pic, mb_x, mb_y, &mut pred);2494 save_luma(pic, mb_x, mb_y, &mut pred);
2383 let mut lv4 = chroma_lv.clone();2495 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);
2385 let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);2497 let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
2386 let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;2498 let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;
2387 let mut recon4 = [0u8; 256];2499 let mut recon4 = [0u8; 256];
@@ -2398,7 +2510,7 @@ fn encode_inter_mb(
2398 restore_luma(pic, mb_x, mb_y, &recon4);2510 restore_luma(pic, mb_x, mb_y, &recon4);
2399 }2511 }
2400 } else {2512 } 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);
2402 }2514 }
2403 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;2515 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
2404 let skip = match ssd_skip {2516 let skip = match ssd_skip {
crates/ec-h264/src/enc/quant.rsmodified+17 -1
@@ -213,10 +213,26 @@ pub(crate) fn quant_4x4(
213 intra: bool,213 intra: bool,
214 skip_dc: bool,214 skip_dc: bool,
215 out: &mut [i32; 16],215 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],
216 ) -> u8 {232 ) -> u8 {
217 let m = (qp % 6) as usize;233 let m = (qp % 6) as usize;
218 let qbits = 15 + (qp / 6) as u32;234 let qbits = 15 + (qp / 6) as u32;
219- let f = round_offset(qbits, intra);235+ let f = (1i32 << qbits) / divisor;
220 let start = usize::from(skip_dc);236 let start = usize::from(skip_dc);
221 let mut nz = 0;237 let mut nz = 0;
222 *out = [0; 16];238 *out = [0; 16];
crates/ec-h264/tests/encode.rsmodified+5 -1
@@ -893,7 +893,11 @@ fn real_clip_t8x8_bd_psnr() {
893 /// clip and 0.564 on the screen capture, and takes fewer bits at every QP893 /// clip and 0.564 on the screen capture, and takes fewer bits at every QP
894 /// while doing it. This clip prefers a heavier rate term in that decision894 /// while doing it. This clip prefers a heavier rate term in that decision
895 /// (see the sweep in `enc/mb.rs`), which the two real clips do not.895 /// (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;
897 901
898 fn have_x264() -> bool {902 fn have_x264() -> bool {
899 std::process::Command::new("ffmpeg")903 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
267 block's prediction the way intra's does; and it needs a term for what a267 block's prediction the way intra's does; and it needs a term for what a
268 reference picture's quality is worth to the pictures that predict from it,268 reference picture's quality is worth to the pictures that predict from it,
269 without which more search measures worse.269 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.