forge
Explore
Log in

Don't you dare go Hollow

Code P_8x8, and count shapes as well as bits

Browse files at this commit

2b1c4a3e88f2b8554bc0f6a333dae69f900ff694Ahmet Kaan GümüşParent: 338bd3f
  • feat
    • code P_8x8, and count shapes as well as bits
Show full message
feat(h264): code P_8x8, and count shapes as well as bits

The encoder had no partition smaller than 8x16. It now codes P_8x8 with
four P_L0_8x8 sub-partitions, including the sub_mb_type writer both
entropy coders were missing.

The first measurement of it read flat, as had the split-gate sweep before
it, and a shape histogram said why: the partition search runs only at
Preset::Balanced, and the x264 comparison runs Preset::Fast by default,
so 1,200,000 macroblocks were coded whole and nothing was ever split.
Measured where the shapes are searched, P_8x8 is worth 0.005 dB BD-PSNR
on the film clip and 0.016 on the screen capture, with the optimum at
twelve bits of signalling on both.

The bit-exactness sweeps ran the default preset too, so no sub_mb_type
had ever faced another decoder: balanced_partitions_decode_bit_exactly
encodes at Balanced under CABAC and CAVLC, requires ffmpeg to reproduce
the reconstruction sample for sample, and requires every shape to appear.
The decoder now reports MbShapes alongside BitAccount, which puts our
partition mix next to x264's: we still split about half as often.
crates/ec-h264/src/cabac.rsmodified+1 -1
@@ -45,7 +45,7 @@ pub(crate) const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39];
4545 pub(crate) const OFF_MB_TYPE: usize = 3;
4646 pub(crate) const OFF_SKIP_P: usize = 11;
4747 pub(crate) const OFF_MB_TYPE_P: usize = 14;
48-const OFF_SUB_TYPE_P: usize = 21;
48+pub(crate) const OFF_SUB_TYPE_P: usize = 21;
4949 const OFF_SKIP_B: usize = 24;
5050 const OFF_MB_TYPE_B: usize = 27;
5151 const OFF_SUB_TYPE_B: usize = 36;
crates/ec-h264/src/decoder.rsmodified+61 -0
@@ -135,6 +135,7 @@ pub struct Decoder {
135135 out: VecDeque<VideoFrame>,
136136 /// Bits parsed so far, by syntax class (CABAC slices only).
137137 account: BitAccount,
138+ shapes: MbShapes,
138139 /// Presentation timestamp to attach to the next picture started.
139140 pending_pts: Option<Timestamp>,
140141 /// `PicOrderCnt` of the random-access point most recently established by
@@ -215,6 +216,7 @@ impl Decoder {
215216 output_order: OutputOrder::default(),
216217 out: VecDeque::new(),
217218 account: BitAccount::default(),
219+ shapes: MbShapes::default(),
218220 pending_pts: None,
219221 recovery_poc: None,
220222 cur_ref_padded: false,
@@ -254,6 +256,12 @@ impl Decoder {
254256 self.account
255257 }
256258
259+ /// How many macroblocks of each shape this decoder has read, which is what
260+ /// a stream's partitioning looks like from the outside.
261+ pub fn mb_shapes(&self) -> MbShapes {
262+ self.shapes
263+ }
264+
257265 /// Decode the first IDR picture of an Annex B stream and return it.
258266 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
259267 let mut got_slice = false;
@@ -538,6 +546,7 @@ impl Decoder {
538546 };
539547
540548 let mut ctx = SliceCtx {
549+ shapes: MbShapes::default(),
541550 slice_id,
542551 slice_type: sh.slice_type,
543552 qp: sh.slice_qp,
@@ -633,6 +642,7 @@ impl Decoder {
633642 more = r.more_macroblocks()?;
634643 mb_addr += 1;
635644 }
645+ self.shapes.add(&ctx.shapes);
636646 if let Entropy::Cabac(c) = &r {
637647 self.account.add(&c.account());
638648 }
@@ -820,6 +830,39 @@ fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {
820830 }
821831
822832 /// Mutable per-slice decode state.
833+/// How many macroblocks of each shape a stream codes: the partitioning the
834+/// encoder chose, counted from the outside.
835+///
836+/// P macroblocks only; a B macroblock's own shapes are not split out.
837+#[derive(Debug, Default, Clone, Copy)]
838+pub struct MbShapes {
839+ pub skip: u64,
840+ pub p16x16: u64,
841+ pub p16x8: u64,
842+ pub p8x16: u64,
843+ /// P_8x8 and P_8x8ref0, whatever the sub_mb_types inside are.
844+ pub p8x8: u64,
845+ pub bidir: u64,
846+ pub intra: u64,
847+}
848+
849+impl MbShapes {
850+ /// Add another count into this one.
851+ pub fn add_public(&mut self, o: &MbShapes) {
852+ self.add(o);
853+ }
854+
855+ pub(crate) fn add(&mut self, o: &MbShapes) {
856+ self.skip += o.skip;
857+ self.p16x16 += o.p16x16;
858+ self.p16x8 += o.p16x8;
859+ self.p8x16 += o.p8x16;
860+ self.p8x8 += o.p8x8;
861+ self.bidir += o.bidir;
862+ self.intra += o.intra;
863+ }
864+}
865+
823866 struct SliceCtx {
824867 slice_id: u16,
825868 slice_type: SliceType,
@@ -841,6 +884,8 @@ struct SliceCtx {
841884 weights: Option<PredWeightTable>,
842885 /// `PicOrderCnt( CurrPic )`.
843886 poc: i32,
887+ /// How many macroblocks of each shape this slice decoded.
888+ shapes: MbShapes,
844889 }
845890
846891 impl SliceCtx {
@@ -1081,6 +1126,22 @@ fn decode_macroblock(
10811126 r.mb_type_i()?
10821127 };
10831128
1129+ if skipped {
1130+ ctx.shapes.skip += 1;
1131+ } else if ctx.slice_type == SliceType::P {
1132+ match mb_type {
1133+ 0 => ctx.shapes.p16x16 += 1,
1134+ 1 => ctx.shapes.p16x8 += 1,
1135+ 2 => ctx.shapes.p8x16 += 1,
1136+ 3 | 4 => ctx.shapes.p8x8 += 1,
1137+ _ => ctx.shapes.intra += 1,
1138+ }
1139+ } else if ctx.is_b() {
1140+ ctx.shapes.bidir += 1;
1141+ } else {
1142+ ctx.shapes.intra += 1;
1143+ }
1144+
10841145 // Split the P/B numbering into an inter shape or an intra mb_type.
10851146 let (shape, intra_type) = if skipped {
10861147 let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] };
crates/ec-h264/src/enc/cabac_enc.rsmodified+18 -1
@@ -23,7 +23,8 @@ use crate::cabac::{
2323 ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_ABS_8X8,
2424 OFF_CBF, OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_LAST_8X8, OFF_MB_TYPE,
2525 OFF_MB_TYPE_P, OFF_MVD, OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SIG_8X8,
26- OFF_SKIP_P, OFF_TRANSFORM_8X8, SIG_CAT_OFF, init_contexts, qp_delta_inc, sig_inc,
26+ OFF_SKIP_P, OFF_SUB_TYPE_P, OFF_TRANSFORM_8X8, SIG_CAT_OFF, init_contexts, qp_delta_inc,
27+ sig_inc,
2728 };
2829 use crate::cabac_tables::{LAST_8X8, SIG_8X8_FRAME};
2930 use crate::entropy::{
@@ -233,6 +234,22 @@ impl CabacEnc {
233234 self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }, b2);
234235 }
235236
237+ /// `sub_mb_type` of a P macroblock (Table 9-38): the mirror of
238+ /// [`crate::cabac::Cabac::sub_mb_type_p_inner`].
239+ pub(crate) fn sub_mb_type_p(&mut self, value: u32) {
240+ if value == 0 {
241+ self.decision(OFF_SUB_TYPE_P, true); // P_L0_8x8
242+ return;
243+ }
244+ self.decision(OFF_SUB_TYPE_P, false);
245+ if value == 1 {
246+ self.decision(OFF_SUB_TYPE_P + 1, false); // P_L0_8x4
247+ return;
248+ }
249+ self.decision(OFF_SUB_TYPE_P + 1, true);
250+ self.decision(OFF_SUB_TYPE_P + 2, value == 2); // P_L0_4x8 or P_L0_4x4
251+ }
252+
236253 /// The Intra part of an mb_type bin string; `value` is the I-slice type.
237254 fn mb_type_intra(&mut self, ctx: &[usize; 6], value: u32) {
238255 if value == 0 {
crates/ec-h264/src/enc/entropy.rsmodified+8 -0
@@ -102,6 +102,14 @@ impl EncEntropy {
102102 }
103103 }
104104
105+ /// One `sub_mb_type` of a P macroblock (Table 7-17).
106+ pub(crate) fn sub_mb_type_p(&mut self, value: u32) {
107+ match self {
108+ EncEntropy::Cavlc { w, .. } => w.write_ue(value),
109+ EncEntropy::Cabac(c) => c.sub_mb_type_p(value),
110+ }
111+ }
112+
105113 /// One 4x4 intra prediction mode: `None` selects the predicted mode.
106114 pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option<u8>) {
107115 match self {
crates/ec-h264/src/enc/mb.rsmodified+86 -12
@@ -601,6 +601,18 @@ fn intra_pre_cost(
601601 /// below a half and falls away above it.
602602 const MV_BITS_WEIGHT: f64 = 0.5;
603603
604+/// What the search charges P_8x8 for its own signalling, against the six bits
605+/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four
606+/// sub_mb_type bins, before the four predictors' own mvd.
607+///
608+/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all
609+/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read
610+/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and
611+/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the
612+/// optimum at twelve, and quarters are worth 0.005 dB on camera content and
613+/// 0.016 on screen capture.
614+const QUAD_BITS: f64 = 12.0;
615+
604616 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
605617 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
606618 enum PShape {
@@ -610,6 +622,8 @@ enum PShape {
610622 Horizontal,
611623 /// P_L0_L0_8x16: a left and a right half.
612624 Vertical,
625+ /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
626+ Quad,
613627 }
614628
615629 impl PShape {
@@ -619,11 +633,16 @@ impl PShape {
619633 PShape::Whole => 0,
620634 PShape::Horizontal => 1,
621635 PShape::Vertical => 2,
636+ PShape::Quad => 3,
622637 }
623638 }
624639
625640 fn parts(self) -> usize {
626- usize::from(self != PShape::Whole) + 1
641+ match self {
642+ PShape::Whole => 1,
643+ PShape::Horizontal | PShape::Vertical => 2,
644+ PShape::Quad => 4,
645+ }
627646 }
628647
629648 /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
@@ -632,6 +651,7 @@ impl PShape {
632651 PShape::Whole => ((0, 0), (16, 16)),
633652 PShape::Horizontal => ((0, part * 2), (16, 8)),
634653 PShape::Vertical => ((part * 2, 0), (8, 16)),
654+ PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
635655 }
636656 }
637657
@@ -642,6 +662,7 @@ impl PShape {
642662 PShape::Whole => (4, 4),
643663 PShape::Horizontal => (4, 2),
644664 PShape::Vertical => (2, 4),
665+ PShape::Quad => (2, 2),
645666 }
646667 }
647668 }
@@ -650,7 +671,7 @@ impl PShape {
650671 struct InterChoice {
651672 shape: PShape,
652673 /// One motion vector per partition.
653- mv: [[i16; 2]; 2],
674+ mv: [[i16; 2]; 4],
654675 /// The P_Skip motion vector of 8.4.1.1.
655676 skip_mv: [i16; 2],
656677 /// The skip candidate is at least as good as the searched one.
@@ -822,7 +843,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
822843 satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 2.0)
823844 };
824845
825- let mut best = (PShape::Whole, [mv16, mv16], cost16);
846+ let mut best = (PShape::Whole, [mv16; 4], cost16);
826847 // Halves, seeded with the whole-macroblock winner. The predictor used here
827848 // is the whole-macroblock one rather than each half's own: the real
828849 // predictors are derived in coding order when the choice is made, and this
@@ -838,10 +859,19 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
838859 // searched. It stays as a guard for content flat enough to make the two
839860 // extra searches pure cost.
840861 if e.preset == Preset::Balanced && cost16 > 16 * 16 {
841- for shape in [PShape::Horizontal, PShape::Vertical] {
842- let mut total = motion_rate(e, 6.0); // the partition's own signalling
843- let mut mvs = [[0i16; 2]; 2];
844- for part in 0..2 {
862+ for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
863+ // What the shape itself costs to signal: its mb_type, plus one
864+ // sub_mb_type per quarter when it is P_8x8.
865+ let mut total = motion_rate(
866+ e,
867+ if shape == PShape::Quad {
868+ QUAD_BITS
869+ } else {
870+ 6.0
871+ },
872+ );
873+ let mut mvs = [[0i16; 2]; 4];
874+ for part in 0..shape.parts() {
845875 let ((bx, by), (w, h)) = shape.geometry(part);
846876 let seeds = [mv16, mvp, skip_mv, [0, 0]];
847877 let (mv, cost) = search(bx * 4, by * 4, w, h, mvp, &seeds);
@@ -854,6 +884,39 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
854884 }
855885 }
856886
887+ // How often each shape actually wins. Behind an environment switch because
888+ // it answers a question the rate gate cannot: a partition sweep that reads
889+ // flat is either a flat knob or a path nothing enters, and only a count
890+ // tells the two apart. It found the second -- at `Preset::Fast`, which is
891+ // what the x264 comparison runs by default, no macroblock is ever split.
892+ if std::env::var_os("EC_H264_SHAPE_STATS").is_some() {
893+ static N: [std::sync::atomic::AtomicUsize; 4] = [
894+ std::sync::atomic::AtomicUsize::new(0),
895+ std::sync::atomic::AtomicUsize::new(0),
896+ std::sync::atomic::AtomicUsize::new(0),
897+ std::sync::atomic::AtomicUsize::new(0),
898+ ];
899+ let i = match best.0 {
900+ PShape::Whole => 0,
901+ PShape::Horizontal => 1,
902+ PShape::Vertical => 2,
903+ PShape::Quad => 3,
904+ };
905+ let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
906+ let tot: usize = N
907+ .iter()
908+ .map(|n| n.load(std::sync::atomic::Ordering::Relaxed))
909+ .sum();
910+ if tot.is_multiple_of(20000) {
911+ eprintln!(
912+ "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})",
913+ N[0].load(std::sync::atomic::Ordering::Relaxed),
914+ N[1].load(std::sync::atomic::Ordering::Relaxed),
915+ N[2].load(std::sync::atomic::Ordering::Relaxed),
916+ N[3].load(std::sync::atomic::Ordering::Relaxed),
917+ );
918+ }
919+ }
857920 InterChoice {
858921 shape: best.0,
859922 mv: best.1,
@@ -2067,8 +2130,8 @@ fn inter_mb_bits(
20672130 mb_addr: usize,
20682131 nbr: &MbNeighbors,
20692132 shape: PShape,
2070- mvd: &[[i16; 2]; 2],
2071- inc: &[[usize; 2]; 2],
2133+ mvd: &[[i16; 2]; 4],
2134+ inc: &[[usize; 2]; 4],
20722135 lv: &Levels,
20732136 ) -> i64 {
20742137 entropy_bits(w, |cw| {
@@ -2076,6 +2139,11 @@ fn inter_mb_bits(
20762139 cw.coded_mb(true, e.skip_inc);
20772140 cw.set_intra(false);
20782141 cw.mb_type(true, shape.mb_type());
2142+ if shape == PShape::Quad {
2143+ for _ in 0..4 {
2144+ cw.sub_mb_type_p(0); // P_L0_8x8
2145+ }
2146+ }
20792147 for part in 0..shape.parts() {
20802148 for comp in 0..2 {
20812149 cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
@@ -2549,7 +2617,8 @@ fn compensate_part(
25492617 }
25502618 }
25512619
2552-/// Code a P macroblock: skip, one 16x16 partition, or two halves.
2620+/// Code a P macroblock: skip, one 16x16 partition, two halves or four
2621+/// quarters.
25532622 fn encode_inter_mb(
25542623 pic: &mut Picture,
25552624 e: &mut MbEnc<'_>,
@@ -2579,8 +2648,8 @@ fn encode_inter_mb(
25792648 written: 0,
25802649 };
25812650 let (part_w, part_h) = shape.part_blocks();
2582- let mut mvd = [[0i16; 2]; 2];
2583- let mut inc = [[0usize; 2]; 2];
2651+ let mut mvd = [[0i16; 2]; 4];
2652+ let mut inc = [[0usize; 2]; 4];
25842653 for part in 0..shape.parts() {
25852654 let ((bx, by), (pw, ph)) = shape.geometry(part);
25862655 let mv = if choice.prefer_skip {
@@ -2718,6 +2787,11 @@ fn encode_inter_mb(
27182787 w.coded_mb(true, e.skip_inc);
27192788 w.set_intra(false);
27202789 w.mb_type(true, shape.mb_type());
2790+ if shape == PShape::Quad {
2791+ for _ in 0..4 {
2792+ w.sub_mb_type_p(0); // P_L0_8x8
2793+ }
2794+ }
27212795 // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded.
27222796 for part in 0..shape.parts() {
27232797 for comp in 0..2 {
crates/ec-h264/src/lib.rsmodified+1 -1
@@ -51,6 +51,6 @@ mod transform;
5151
5252 pub use cabac::BitAccount;
5353 pub use codec::H264Decoder;
54-pub use decoder::{Decoder, NalOutcome, OutputOrder};
54+pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder};
5555 pub use ec_core::error::{Error, Result};
5656 pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset};
crates/ec-h264/tests/encode.rsmodified+63 -2
@@ -1142,7 +1142,7 @@ fn bit_account_vs_x264() {
11421142 }
11431143 dec.flush().expect("flush");
11441144 while dec.next_frame().is_some() {}
1145- dec.bit_account()
1145+ (dec.bit_account(), dec.mb_shapes())
11461146 };
11471147 for qp in [26, 34] {
11481148 let mut cfg = EncoderConfig::new(w as u32, h as u32);
@@ -1151,6 +1151,9 @@ fn bit_account_vs_x264() {
11511151 cfg.cabac = true;
11521152 cfg.framerate = 1.0;
11531153 cfg.threads = 0;
1154+ if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1155+ cfg.preset = ec_h264::Preset::Balanced;
1156+ }
11541157 let mut enc = Encoder::new(cfg).expect("encoder");
11551158 let mut ours = Vec::new();
11561159 for (y, u, v) in &sources {
@@ -1158,7 +1161,7 @@ fn bit_account_vs_x264() {
11581161 ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
11591162 }
11601163 let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1161- let (a, b) = (account(&ours), account(&theirs));
1164+ let ((a, sa), (b, sb)) = (account(&ours), account(&theirs));
11621165 eprintln!(
11631166 "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
11641167 sources.len(),
@@ -1183,5 +1186,63 @@ fn bit_account_vs_x264() {
11831186 row("residual luma", a.residual_luma, b.residual_luma);
11841187 row("residual chroma", a.residual_chroma, b.residual_chroma);
11851188 row("total accounted", a.total(), b.total());
1189+ let mix = |n: &str, s: &ec_h264::MbShapes| {
1190+ eprintln!(
1191+ " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1192+ s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra
1193+ );
1194+ };
1195+ mix("shapes ours", &sa);
1196+ mix("shapes x264", &sb);
1197+ }
1198+}
1199+
1200+/// The partitions only `Preset::Balanced` searches, decoded by ffmpeg.
1201+///
1202+/// The default preset codes every P macroblock as one 16x16 partition, so the
1203+/// bit-exactness sweeps above never put a 16x8, an 8x16 or a P_8x8 -- and so
1204+/// never a `sub_mb_type` -- in front of another decoder. This does.
1205+#[test]
1206+fn balanced_partitions_decode_bit_exactly() {
1207+ if !have_ffmpeg() {
1208+ eprintln!("SKIP balanced_partitions_decode_bit_exactly: no ffmpeg on PATH");
1209+ return;
1210+ }
1211+ let (w, h) = (176, 144);
1212+ let mut shapes = ec_h264::MbShapes::default();
1213+ for qp in [16, 26, 36] {
1214+ let cavlc = qp == 26; // both entropy coders write sub_mb_type
1215+ let (stream, recons, _) = encode_clip(w, h, 8, |cfg| {
1216+ cfg.qp = qp;
1217+ cfg.cabac = !cavlc;
1218+ cfg.preset = ec_h264::Preset::Balanced;
1219+ });
1220+ let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
1221+ assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count");
1222+ for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
1223+ assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}");
1224+ assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}");
1225+ assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}");
1226+ }
1227+ let mut dec = Decoder::new();
1228+ dec.set_output_order(OutputOrder::Decode);
1229+ for nal in ec_h264_syntax::AnnexBIter::new(&stream) {
1230+ if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1231+ dec.end_picture().expect("end of picture");
1232+ dec.push_nal(nal).expect("decoder accepts the NAL");
1233+ }
1234+ while dec.next_frame().is_some() {}
1235+ }
1236+ dec.flush().expect("flush");
1237+ while dec.next_frame().is_some() {}
1238+ shapes.add_public(&dec.mb_shapes());
11861239 }
1240+ eprintln!(
1241+ "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1242+ shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra
1243+ );
1244+ assert!(
1245+ shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0,
1246+ "the sweep has to code every shape, or it proves nothing about them"
1247+ );
11871248 }
lanes/h264x264-r2.report.mdmodified+51 -0
@@ -520,3 +520,54 @@ Small numbers, and that is the finding: the search's stopping rules are not what
520520 holds the motion field back. What we do not have is the shape -- the encoder
521521 codes 16x16, 16x8 and 8x16 and nothing smaller, while x264 has the 8x8 sub-
522522 partitions. That is the next slice.
523+
524+## P_8x8, and the preset that hid it
525+
526+The encoder coded 16x16, 16x8 and 8x16 and nothing smaller. It now codes P_8x8
527+with four P_L0_8x8 sub-partitions: `PShape::Quad`, a `sub_mb_type` writer on
528+both entropy coders, and four searches seeded from the whole-macroblock winner.
529+
530+Landing it exposed a defect in the comparison itself. The first measurement of
531+P_8x8 moved neither clip by a thousandth of a decibel, and neither had the split
532+gate swept just before it. A temporary shape histogram said why: over 1,200,000
533+macroblocks of the screen capture, `whole=1200000 horiz=0 vert=0 quad=0`. The
534+partition search runs only at `Preset::Balanced`, and `bd_psnr_vs_x264` runs
535+`Preset::Fast` unless told otherwise -- so every partition number taken through
536+the default gate was flat by construction. The histogram stays in the encoder
537+behind `EC_H264_SHAPE_STATS`, because a flat sweep and a dead code path read
538+the same from a rate curve and only a count separates them.
539+
540+Measured where the shapes are actually searched (`EC_H264_PRESET_BALANCED=1`,
541+consecutive pictures, GOP 10, BD-PSNR against x264):
542+
543+| P_8x8 charged | film | screen capture |
544+| --- | --- | --- |
545+| not coded | -0.382 | -0.369 |
546+| 6 bits | -0.379 | -0.364 |
547+| 12 bits | **-0.377** | **-0.353** |
548+| 20 bits | -0.378 | -0.356 |
549+
550+Both contents put the optimum at twelve bits, which is about what P_8x8 signals:
551+an mb_type one bin longer than 16x8's plus four sub_mb_type bins. Quarters are
552+worth 0.005 dB on camera content and 0.016 on screen capture.
553+
554+`balanced_partitions_decode_bit_exactly` now encodes at Balanced under both
555+entropy coders and requires ffmpeg to reproduce our reconstruction sample for
556+sample, and requires the sweep to have coded at least one of every shape -- the
557+existing bit-exactness sweeps run the default preset, so no `sub_mb_type` had
558+ever been put in front of another decoder before this.
559+
560+The decoder counts shapes as well as bits now, so the mix is comparable too.
561+Screen capture at qp 26, twelve pictures, both encoders at their fullest search:
562+
563+| | skip | 16x16 | 16x8 | 8x16 | 8x8 | intra |
564+| --- | --- | --- | --- | --- | --- | --- |
565+| ours | 134847 | 4792 | 488 | 226 | 103 | 32344 |
566+| x264 | 132159 | 6410 | 920 | 355 | 294 | 32662 |
567+
568+We still split about half as often as x264 at every size, and residual luma is
569+still +10.9%. The gain from charging P_8x8 *more* rather than less says where
570+that comes from: each sub-partition is searched against the whole macroblock's
571+motion predictor, not its own, so the search misjudges what a split costs to
572+signal and picks the wrong ones. Deriving the real predictor inside the search
573+is the next slice.