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];
45 pub(crate) const OFF_MB_TYPE: usize = 3;45 pub(crate) const OFF_MB_TYPE: usize = 3;
46 pub(crate) const OFF_SKIP_P: usize = 11;46 pub(crate) const OFF_SKIP_P: usize = 11;
47 pub(crate) const OFF_MB_TYPE_P: usize = 14;47 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;
49 const OFF_SKIP_B: usize = 24;49 const OFF_SKIP_B: usize = 24;
50 const OFF_MB_TYPE_B: usize = 27;50 const OFF_MB_TYPE_B: usize = 27;
51 const OFF_SUB_TYPE_B: usize = 36;51 const OFF_SUB_TYPE_B: usize = 36;
crates/ec-h264/src/decoder.rsmodified+61 -0
@@ -135,6 +135,7 @@ pub struct Decoder {
135 out: VecDeque<VideoFrame>,135 out: VecDeque<VideoFrame>,
136 /// Bits parsed so far, by syntax class (CABAC slices only).136 /// Bits parsed so far, by syntax class (CABAC slices only).
137 account: BitAccount,137 account: BitAccount,
138+ shapes: MbShapes,
138 /// Presentation timestamp to attach to the next picture started.139 /// Presentation timestamp to attach to the next picture started.
139 pending_pts: Option<Timestamp>,140 pending_pts: Option<Timestamp>,
140 /// `PicOrderCnt` of the random-access point most recently established by141 /// `PicOrderCnt` of the random-access point most recently established by
@@ -215,6 +216,7 @@ impl Decoder {
215 output_order: OutputOrder::default(),216 output_order: OutputOrder::default(),
216 out: VecDeque::new(),217 out: VecDeque::new(),
217 account: BitAccount::default(),218 account: BitAccount::default(),
219+ shapes: MbShapes::default(),
218 pending_pts: None,220 pending_pts: None,
219 recovery_poc: None,221 recovery_poc: None,
220 cur_ref_padded: false,222 cur_ref_padded: false,
@@ -254,6 +256,12 @@ impl Decoder {
254 self.account256 self.account
255 }257 }
256 258
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+
257 /// Decode the first IDR picture of an Annex B stream and return it.265 /// Decode the first IDR picture of an Annex B stream and return it.
258 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {266 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
259 let mut got_slice = false;267 let mut got_slice = false;
@@ -538,6 +546,7 @@ impl Decoder {
538 };546 };
539 547
540 let mut ctx = SliceCtx {548 let mut ctx = SliceCtx {
549+ shapes: MbShapes::default(),
541 slice_id,550 slice_id,
542 slice_type: sh.slice_type,551 slice_type: sh.slice_type,
543 qp: sh.slice_qp,552 qp: sh.slice_qp,
@@ -633,6 +642,7 @@ impl Decoder {
633 more = r.more_macroblocks()?;642 more = r.more_macroblocks()?;
634 mb_addr += 1;643 mb_addr += 1;
635 }644 }
645+ self.shapes.add(&ctx.shapes);
636 if let Entropy::Cabac(c) = &r {646 if let Entropy::Cabac(c) = &r {
637 self.account.add(&c.account());647 self.account.add(&c.account());
638 }648 }
@@ -820,6 +830,39 @@ fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {
820 }830 }
821 831
822 /// Mutable per-slice decode state.832 /// 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+
823 struct SliceCtx {866 struct SliceCtx {
824 slice_id: u16,867 slice_id: u16,
825 slice_type: SliceType,868 slice_type: SliceType,
@@ -841,6 +884,8 @@ struct SliceCtx {
841 weights: Option<PredWeightTable>,884 weights: Option<PredWeightTable>,
842 /// `PicOrderCnt( CurrPic )`.885 /// `PicOrderCnt( CurrPic )`.
843 poc: i32,886 poc: i32,
887+ /// How many macroblocks of each shape this slice decoded.
888+ shapes: MbShapes,
844 }889 }
845 890
846 impl SliceCtx {891 impl SliceCtx {
@@ -1081,6 +1126,22 @@ fn decode_macroblock(
1081 r.mb_type_i()?1126 r.mb_type_i()?
1082 };1127 };
1083 1128
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+
1084 // Split the P/B numbering into an inter shape or an intra mb_type.1145 // Split the P/B numbering into an inter shape or an intra mb_type.
1085 let (shape, intra_type) = if skipped {1146 let (shape, intra_type) = if skipped {
1086 let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] };1147 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::{
23 ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_ABS_8X8,23 ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_ABS_8X8,
24 OFF_CBF, OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_LAST_8X8, OFF_MB_TYPE,24 OFF_CBF, OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_LAST_8X8, OFF_MB_TYPE,
25 OFF_MB_TYPE_P, OFF_MVD, OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SIG_8X8,25 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,
27 };28 };
28 use crate::cabac_tables::{LAST_8X8, SIG_8X8_FRAME};29 use crate::cabac_tables::{LAST_8X8, SIG_8X8_FRAME};
29 use crate::entropy::{30 use crate::entropy::{
@@ -233,6 +234,22 @@ impl CabacEnc {
233 self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }, b2);234 self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }, b2);
234 }235 }
235 236
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+
236 /// The Intra part of an mb_type bin string; `value` is the I-slice type.253 /// The Intra part of an mb_type bin string; `value` is the I-slice type.
237 fn mb_type_intra(&mut self, ctx: &[usize; 6], value: u32) {254 fn mb_type_intra(&mut self, ctx: &[usize; 6], value: u32) {
238 if value == 0 {255 if value == 0 {
crates/ec-h264/src/enc/entropy.rsmodified+8 -0
@@ -102,6 +102,14 @@ impl EncEntropy {
102 }102 }
103 }103 }
104 104
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+
105 /// One 4x4 intra prediction mode: `None` selects the predicted mode.113 /// One 4x4 intra prediction mode: `None` selects the predicted mode.
106 pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option<u8>) {114 pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option<u8>) {
107 match self {115 match self {
crates/ec-h264/src/enc/mb.rsmodified+86 -12
@@ -601,6 +601,18 @@ fn intra_pre_cost(
601 /// below a half and falls away above it.601 /// below a half and falls away above it.
602 const MV_BITS_WEIGHT: f64 = 0.5;602 const MV_BITS_WEIGHT: f64 = 0.5;
603 603
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+
604 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.616 /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
605 #[derive(Clone, Copy, PartialEq, Eq, Debug)]617 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
606 enum PShape {618 enum PShape {
@@ -610,6 +622,8 @@ enum PShape {
610 Horizontal,622 Horizontal,
611 /// P_L0_L0_8x16: a left and a right half.623 /// P_L0_L0_8x16: a left and a right half.
612 Vertical,624 Vertical,
625+ /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
626+ Quad,
613 }627 }
614 628
615 impl PShape {629 impl PShape {
@@ -619,11 +633,16 @@ impl PShape {
619 PShape::Whole => 0,633 PShape::Whole => 0,
620 PShape::Horizontal => 1,634 PShape::Horizontal => 1,
621 PShape::Vertical => 2,635 PShape::Vertical => 2,
636+ PShape::Quad => 3,
622 }637 }
623 }638 }
624 639
625 fn parts(self) -> usize {640 fn parts(self) -> usize {
626- usize::from(self != PShape::Whole) + 1641+ match self {
642+ PShape::Whole => 1,
643+ PShape::Horizontal | PShape::Vertical => 2,
644+ PShape::Quad => 4,
645+ }
627 }646 }
628 647
629 /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.648 /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
@@ -632,6 +651,7 @@ impl PShape {
632 PShape::Whole => ((0, 0), (16, 16)),651 PShape::Whole => ((0, 0), (16, 16)),
633 PShape::Horizontal => ((0, part * 2), (16, 8)),652 PShape::Horizontal => ((0, part * 2), (16, 8)),
634 PShape::Vertical => ((part * 2, 0), (8, 16)),653 PShape::Vertical => ((part * 2, 0), (8, 16)),
654+ PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
635 }655 }
636 }656 }
637 657
@@ -642,6 +662,7 @@ impl PShape {
642 PShape::Whole => (4, 4),662 PShape::Whole => (4, 4),
643 PShape::Horizontal => (4, 2),663 PShape::Horizontal => (4, 2),
644 PShape::Vertical => (2, 4),664 PShape::Vertical => (2, 4),
665+ PShape::Quad => (2, 2),
645 }666 }
646 }667 }
647 }668 }
@@ -650,7 +671,7 @@ impl PShape {
650 struct InterChoice {671 struct InterChoice {
651 shape: PShape,672 shape: PShape,
652 /// One motion vector per partition.673 /// One motion vector per partition.
653- mv: [[i16; 2]; 2],674+ mv: [[i16; 2]; 4],
654 /// The P_Skip motion vector of 8.4.1.1.675 /// The P_Skip motion vector of 8.4.1.1.
655 skip_mv: [i16; 2],676 skip_mv: [i16; 2],
656 /// The skip candidate is at least as good as the searched one.677 /// 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
822 satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 2.0)843 satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 2.0)
823 };844 };
824 845
825- let mut best = (PShape::Whole, [mv16, mv16], cost16);846+ let mut best = (PShape::Whole, [mv16; 4], cost16);
826 // Halves, seeded with the whole-macroblock winner. The predictor used here847 // Halves, seeded with the whole-macroblock winner. The predictor used here
827 // is the whole-macroblock one rather than each half's own: the real848 // is the whole-macroblock one rather than each half's own: the real
828 // predictors are derived in coding order when the choice is made, and this849 // 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
838 // searched. It stays as a guard for content flat enough to make the two859 // searched. It stays as a guard for content flat enough to make the two
839 // extra searches pure cost.860 // extra searches pure cost.
840 if e.preset == Preset::Balanced && cost16 > 16 * 16 {861 if e.preset == Preset::Balanced && cost16 > 16 * 16 {
841- for shape in [PShape::Horizontal, PShape::Vertical] {862+ for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
842- let mut total = motion_rate(e, 6.0); // the partition's own signalling863+ // What the shape itself costs to signal: its mb_type, plus one
843- let mut mvs = [[0i16; 2]; 2];864+ // sub_mb_type per quarter when it is P_8x8.
844- for part in 0..2 {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() {
845 let ((bx, by), (w, h)) = shape.geometry(part);875 let ((bx, by), (w, h)) = shape.geometry(part);
846 let seeds = [mv16, mvp, skip_mv, [0, 0]];876 let seeds = [mv16, mvp, skip_mv, [0, 0]];
847 let (mv, cost) = search(bx * 4, by * 4, w, h, mvp, &seeds);877 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
854 }884 }
855 }885 }
856 886
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+ }
857 InterChoice {920 InterChoice {
858 shape: best.0,921 shape: best.0,
859 mv: best.1,922 mv: best.1,
@@ -2067,8 +2130,8 @@ fn inter_mb_bits(
2067 mb_addr: usize,2130 mb_addr: usize,
2068 nbr: &MbNeighbors,2131 nbr: &MbNeighbors,
2069 shape: PShape,2132 shape: PShape,
2070- mvd: &[[i16; 2]; 2],2133+ mvd: &[[i16; 2]; 4],
2071- inc: &[[usize; 2]; 2],2134+ inc: &[[usize; 2]; 4],
2072 lv: &Levels,2135 lv: &Levels,
2073 ) -> i64 {2136 ) -> i64 {
2074 entropy_bits(w, |cw| {2137 entropy_bits(w, |cw| {
@@ -2076,6 +2139,11 @@ fn inter_mb_bits(
2076 cw.coded_mb(true, e.skip_inc);2139 cw.coded_mb(true, e.skip_inc);
2077 cw.set_intra(false);2140 cw.set_intra(false);
2078 cw.mb_type(true, shape.mb_type());2141 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+ }
2079 for part in 0..shape.parts() {2147 for part in 0..shape.parts() {
2080 for comp in 0..2 {2148 for comp in 0..2 {
2081 cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));2149 cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
@@ -2549,7 +2617,8 @@ fn compensate_part(
2549 }2617 }
2550 }2618 }
2551 2619
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.
2553 fn encode_inter_mb(2622 fn encode_inter_mb(
2554 pic: &mut Picture,2623 pic: &mut Picture,
2555 e: &mut MbEnc<'_>,2624 e: &mut MbEnc<'_>,
@@ -2579,8 +2648,8 @@ fn encode_inter_mb(
2579 written: 0,2648 written: 0,
2580 };2649 };
2581 let (part_w, part_h) = shape.part_blocks();2650 let (part_w, part_h) = shape.part_blocks();
2582- let mut mvd = [[0i16; 2]; 2];2651+ let mut mvd = [[0i16; 2]; 4];
2583- let mut inc = [[0usize; 2]; 2];2652+ let mut inc = [[0usize; 2]; 4];
2584 for part in 0..shape.parts() {2653 for part in 0..shape.parts() {
2585 let ((bx, by), (pw, ph)) = shape.geometry(part);2654 let ((bx, by), (pw, ph)) = shape.geometry(part);
2586 let mv = if choice.prefer_skip {2655 let mv = if choice.prefer_skip {
@@ -2718,6 +2787,11 @@ fn encode_inter_mb(
2718 w.coded_mb(true, e.skip_inc);2787 w.coded_mb(true, e.skip_inc);
2719 w.set_intra(false);2788 w.set_intra(false);
2720 w.mb_type(true, shape.mb_type());2789 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+ }
2721 // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded.2795 // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded.
2722 for part in 0..shape.parts() {2796 for part in 0..shape.parts() {
2723 for comp in 0..2 {2797 for comp in 0..2 {
crates/ec-h264/src/lib.rsmodified+1 -1
@@ -51,6 +51,6 @@ mod transform;
51 51
52 pub use cabac::BitAccount;52 pub use cabac::BitAccount;
53 pub use codec::H264Decoder;53 pub use codec::H264Decoder;
54-pub use decoder::{Decoder, NalOutcome, OutputOrder};54+pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder};
55 pub use ec_core::error::{Error, Result};55 pub use ec_core::error::{Error, Result};
56 pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset};56 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() {
1142 }1142 }
1143 dec.flush().expect("flush");1143 dec.flush().expect("flush");
1144 while dec.next_frame().is_some() {}1144 while dec.next_frame().is_some() {}
1145- dec.bit_account()1145+ (dec.bit_account(), dec.mb_shapes())
1146 };1146 };
1147 for qp in [26, 34] {1147 for qp in [26, 34] {
1148 let mut cfg = EncoderConfig::new(w as u32, h as u32);1148 let mut cfg = EncoderConfig::new(w as u32, h as u32);
@@ -1151,6 +1151,9 @@ fn bit_account_vs_x264() {
1151 cfg.cabac = true;1151 cfg.cabac = true;
1152 cfg.framerate = 1.0;1152 cfg.framerate = 1.0;
1153 cfg.threads = 0;1153 cfg.threads = 0;
1154+ if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1155+ cfg.preset = ec_h264::Preset::Balanced;
1156+ }
1154 let mut enc = Encoder::new(cfg).expect("encoder");1157 let mut enc = Encoder::new(cfg).expect("encoder");
1155 let mut ours = Vec::new();1158 let mut ours = Vec::new();
1156 for (y, u, v) in &sources {1159 for (y, u, v) in &sources {
@@ -1158,7 +1161,7 @@ fn bit_account_vs_x264() {
1158 ours.extend_from_slice(&enc.encode(&view).expect("encode").au);1161 ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
1159 }1162 }
1160 let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");1163 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));
1162 eprintln!(1165 eprintln!(
1163 "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",1166 "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
1164 sources.len(),1167 sources.len(),
@@ -1183,5 +1186,63 @@ fn bit_account_vs_x264() {
1183 row("residual luma", a.residual_luma, b.residual_luma);1186 row("residual luma", a.residual_luma, b.residual_luma);
1184 row("residual chroma", a.residual_chroma, b.residual_chroma);1187 row("residual chroma", a.residual_chroma, b.residual_chroma);
1185 row("total accounted", a.total(), b.total());1188 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());
1186 }1239 }
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+ );
1187 }1248 }
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
520 holds the motion field back. What we do not have is the shape -- the encoder520 holds the motion field back. What we do not have is the shape -- the encoder
521 codes 16x16, 16x8 and 8x16 and nothing smaller, while x264 has the 8x8 sub-521 codes 16x16, 16x8 and 8x16 and nothing smaller, while x264 has the 8x8 sub-
522 partitions. That is the next slice.522 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.