diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index d9df4165..0e642dec 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -45,7 +45,7 @@ pub(crate) const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39]; pub(crate) const OFF_MB_TYPE: usize = 3; pub(crate) const OFF_SKIP_P: usize = 11; pub(crate) const OFF_MB_TYPE_P: usize = 14; -const OFF_SUB_TYPE_P: usize = 21; +pub(crate) const OFF_SUB_TYPE_P: usize = 21; const OFF_SKIP_B: usize = 24; const OFF_MB_TYPE_B: usize = 27; const OFF_SUB_TYPE_B: usize = 36; diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index d11f4cf6..c57e2531 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -135,6 +135,7 @@ pub struct Decoder { out: VecDeque, /// Bits parsed so far, by syntax class (CABAC slices only). account: BitAccount, + shapes: MbShapes, /// Presentation timestamp to attach to the next picture started. pending_pts: Option, /// `PicOrderCnt` of the random-access point most recently established by @@ -215,6 +216,7 @@ impl Decoder { output_order: OutputOrder::default(), out: VecDeque::new(), account: BitAccount::default(), + shapes: MbShapes::default(), pending_pts: None, recovery_poc: None, cur_ref_padded: false, @@ -254,6 +256,12 @@ impl Decoder { self.account } + /// How many macroblocks of each shape this decoder has read, which is what + /// a stream's partitioning looks like from the outside. + pub fn mb_shapes(&self) -> MbShapes { + self.shapes + } + /// Decode the first IDR picture of an Annex B stream and return it. pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result { let mut got_slice = false; @@ -538,6 +546,7 @@ impl Decoder { }; let mut ctx = SliceCtx { + shapes: MbShapes::default(), slice_id, slice_type: sh.slice_type, qp: sh.slice_qp, @@ -633,6 +642,7 @@ impl Decoder { more = r.more_macroblocks()?; mb_addr += 1; } + self.shapes.add(&ctx.shapes); if let Entropy::Cabac(c) = &r { self.account.add(&c.account()); } @@ -820,6 +830,39 @@ fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> { } /// Mutable per-slice decode state. +/// How many macroblocks of each shape a stream codes: the partitioning the +/// encoder chose, counted from the outside. +/// +/// P macroblocks only; a B macroblock's own shapes are not split out. +#[derive(Debug, Default, Clone, Copy)] +pub struct MbShapes { + pub skip: u64, + pub p16x16: u64, + pub p16x8: u64, + pub p8x16: u64, + /// P_8x8 and P_8x8ref0, whatever the sub_mb_types inside are. + pub p8x8: u64, + pub bidir: u64, + pub intra: u64, +} + +impl MbShapes { + /// Add another count into this one. + pub fn add_public(&mut self, o: &MbShapes) { + self.add(o); + } + + pub(crate) fn add(&mut self, o: &MbShapes) { + self.skip += o.skip; + self.p16x16 += o.p16x16; + self.p16x8 += o.p16x8; + self.p8x16 += o.p8x16; + self.p8x8 += o.p8x8; + self.bidir += o.bidir; + self.intra += o.intra; + } +} + struct SliceCtx { slice_id: u16, slice_type: SliceType, @@ -841,6 +884,8 @@ struct SliceCtx { weights: Option, /// `PicOrderCnt( CurrPic )`. poc: i32, + /// How many macroblocks of each shape this slice decoded. + shapes: MbShapes, } impl SliceCtx { @@ -1081,6 +1126,22 @@ fn decode_macroblock( r.mb_type_i()? }; + if skipped { + ctx.shapes.skip += 1; + } else if ctx.slice_type == SliceType::P { + match mb_type { + 0 => ctx.shapes.p16x16 += 1, + 1 => ctx.shapes.p16x8 += 1, + 2 => ctx.shapes.p8x16 += 1, + 3 | 4 => ctx.shapes.p8x8 += 1, + _ => ctx.shapes.intra += 1, + } + } else if ctx.is_b() { + ctx.shapes.bidir += 1; + } else { + ctx.shapes.intra += 1; + } + // Split the P/B numbering into an inter shape or an intra mb_type. let (shape, intra_type) = if skipped { let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] }; diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index ab63ac9d..800cf396 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -23,7 +23,8 @@ use crate::cabac::{ ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_ABS_8X8, OFF_CBF, OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_LAST_8X8, OFF_MB_TYPE, OFF_MB_TYPE_P, OFF_MVD, OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SIG_8X8, - OFF_SKIP_P, OFF_TRANSFORM_8X8, SIG_CAT_OFF, init_contexts, qp_delta_inc, sig_inc, + OFF_SKIP_P, OFF_SUB_TYPE_P, OFF_TRANSFORM_8X8, SIG_CAT_OFF, init_contexts, qp_delta_inc, + sig_inc, }; use crate::cabac_tables::{LAST_8X8, SIG_8X8_FRAME}; use crate::entropy::{ @@ -233,6 +234,22 @@ impl CabacEnc { self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }, b2); } + /// `sub_mb_type` of a P macroblock (Table 9-38): the mirror of + /// [`crate::cabac::Cabac::sub_mb_type_p_inner`]. + pub(crate) fn sub_mb_type_p(&mut self, value: u32) { + if value == 0 { + self.decision(OFF_SUB_TYPE_P, true); // P_L0_8x8 + return; + } + self.decision(OFF_SUB_TYPE_P, false); + if value == 1 { + self.decision(OFF_SUB_TYPE_P + 1, false); // P_L0_8x4 + return; + } + self.decision(OFF_SUB_TYPE_P + 1, true); + self.decision(OFF_SUB_TYPE_P + 2, value == 2); // P_L0_4x8 or P_L0_4x4 + } + /// The Intra part of an mb_type bin string; `value` is the I-slice type. fn mb_type_intra(&mut self, ctx: &[usize; 6], value: u32) { if value == 0 { diff --git a/crates/ec-h264/src/enc/entropy.rs b/crates/ec-h264/src/enc/entropy.rs index 4044f61f..25e00969 100644 --- a/crates/ec-h264/src/enc/entropy.rs +++ b/crates/ec-h264/src/enc/entropy.rs @@ -102,6 +102,14 @@ impl EncEntropy { } } + /// One `sub_mb_type` of a P macroblock (Table 7-17). + pub(crate) fn sub_mb_type_p(&mut self, value: u32) { + match self { + EncEntropy::Cavlc { w, .. } => w.write_ue(value), + EncEntropy::Cabac(c) => c.sub_mb_type_p(value), + } + } + /// One 4x4 intra prediction mode: `None` selects the predicted mode. pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option) { match self { diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index ae53987a..e0f20213 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -601,6 +601,18 @@ fn intra_pre_cost( /// below a half and falls away above it. const MV_BITS_WEIGHT: f64 = 0.5; +/// What the search charges P_8x8 for its own signalling, against the six bits +/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four +/// sub_mb_type bins, before the four predictors' own mvd. +/// +/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all +/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read +/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and +/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the +/// optimum at twelve, and quarters are worth 0.005 dB on camera content and +/// 0.016 on screen capture. +const QUAD_BITS: f64 = 12.0; + /// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13. #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum PShape { @@ -610,6 +622,8 @@ enum PShape { Horizontal, /// P_L0_L0_8x16: a left and a right half. Vertical, + /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each. + Quad, } impl PShape { @@ -619,11 +633,16 @@ impl PShape { PShape::Whole => 0, PShape::Horizontal => 1, PShape::Vertical => 2, + PShape::Quad => 3, } } fn parts(self) -> usize { - usize::from(self != PShape::Whole) + 1 + match self { + PShape::Whole => 1, + PShape::Horizontal | PShape::Vertical => 2, + PShape::Quad => 4, + } } /// Partition `part`'s origin in 4x4 blocks and its size in luma samples. @@ -632,6 +651,7 @@ impl PShape { PShape::Whole => ((0, 0), (16, 16)), PShape::Horizontal => ((0, part * 2), (16, 8)), PShape::Vertical => ((part * 2, 0), (8, 16)), + PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)), } } @@ -642,6 +662,7 @@ impl PShape { PShape::Whole => (4, 4), PShape::Horizontal => (4, 2), PShape::Vertical => (2, 4), + PShape::Quad => (2, 2), } } } @@ -650,7 +671,7 @@ impl PShape { struct InterChoice { shape: PShape, /// One motion vector per partition. - mv: [[i16; 2]; 2], + mv: [[i16; 2]; 4], /// The P_Skip motion vector of 8.4.1.1. skip_mv: [i16; 2], /// 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 satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 2.0) }; - let mut best = (PShape::Whole, [mv16, mv16], cost16); + let mut best = (PShape::Whole, [mv16; 4], cost16); // Halves, seeded with the whole-macroblock winner. The predictor used here // is the whole-macroblock one rather than each half's own: the real // 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 // searched. It stays as a guard for content flat enough to make the two // extra searches pure cost. if e.preset == Preset::Balanced && cost16 > 16 * 16 { - for shape in [PShape::Horizontal, PShape::Vertical] { - let mut total = motion_rate(e, 6.0); // the partition's own signalling - let mut mvs = [[0i16; 2]; 2]; - for part in 0..2 { + for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] { + // What the shape itself costs to signal: its mb_type, plus one + // sub_mb_type per quarter when it is P_8x8. + let mut total = motion_rate( + e, + if shape == PShape::Quad { + QUAD_BITS + } else { + 6.0 + }, + ); + let mut mvs = [[0i16; 2]; 4]; + for part in 0..shape.parts() { let ((bx, by), (w, h)) = shape.geometry(part); let seeds = [mv16, mvp, skip_mv, [0, 0]]; 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 } } + // How often each shape actually wins. Behind an environment switch because + // it answers a question the rate gate cannot: a partition sweep that reads + // flat is either a flat knob or a path nothing enters, and only a count + // tells the two apart. It found the second -- at `Preset::Fast`, which is + // what the x264 comparison runs by default, no macroblock is ever split. + if std::env::var_os("EC_H264_SHAPE_STATS").is_some() { + static N: [std::sync::atomic::AtomicUsize; 4] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + ]; + let i = match best.0 { + PShape::Whole => 0, + PShape::Horizontal => 1, + PShape::Vertical => 2, + PShape::Quad => 3, + }; + let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let tot: usize = N + .iter() + .map(|n| n.load(std::sync::atomic::Ordering::Relaxed)) + .sum(); + if tot.is_multiple_of(20000) { + eprintln!( + "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})", + N[0].load(std::sync::atomic::Ordering::Relaxed), + N[1].load(std::sync::atomic::Ordering::Relaxed), + N[2].load(std::sync::atomic::Ordering::Relaxed), + N[3].load(std::sync::atomic::Ordering::Relaxed), + ); + } + } InterChoice { shape: best.0, mv: best.1, @@ -2067,8 +2130,8 @@ fn inter_mb_bits( mb_addr: usize, nbr: &MbNeighbors, shape: PShape, - mvd: &[[i16; 2]; 2], - inc: &[[usize; 2]; 2], + mvd: &[[i16; 2]; 4], + inc: &[[usize; 2]; 4], lv: &Levels, ) -> i64 { entropy_bits(w, |cw| { @@ -2076,6 +2139,11 @@ fn inter_mb_bits( cw.coded_mb(true, e.skip_inc); cw.set_intra(false); cw.mb_type(true, shape.mb_type()); + if shape == PShape::Quad { + for _ in 0..4 { + cw.sub_mb_type_p(0); // P_L0_8x8 + } + } for part in 0..shape.parts() { for comp in 0..2 { cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); @@ -2549,7 +2617,8 @@ fn compensate_part( } } -/// Code a P macroblock: skip, one 16x16 partition, or two halves. +/// Code a P macroblock: skip, one 16x16 partition, two halves or four +/// quarters. fn encode_inter_mb( pic: &mut Picture, e: &mut MbEnc<'_>, @@ -2579,8 +2648,8 @@ fn encode_inter_mb( written: 0, }; let (part_w, part_h) = shape.part_blocks(); - let mut mvd = [[0i16; 2]; 2]; - let mut inc = [[0usize; 2]; 2]; + let mut mvd = [[0i16; 2]; 4]; + let mut inc = [[0usize; 2]; 4]; for part in 0..shape.parts() { let ((bx, by), (pw, ph)) = shape.geometry(part); let mv = if choice.prefer_skip { @@ -2718,6 +2787,11 @@ fn encode_inter_mb( w.coded_mb(true, e.skip_inc); w.set_intra(false); w.mb_type(true, shape.mb_type()); + if shape == PShape::Quad { + for _ in 0..4 { + w.sub_mb_type_p(0); // P_L0_8x8 + } + } // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded. for part in 0..shape.parts() { for comp in 0..2 { diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index 2e8f143a..aaca2275 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -51,6 +51,6 @@ mod transform; pub use cabac::BitAccount; pub use codec::H264Decoder; -pub use decoder::{Decoder, NalOutcome, OutputOrder}; +pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder}; pub use ec_core::error::{Error, Result}; pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index 5a3af2b5..36c9cd43 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -1142,7 +1142,7 @@ fn bit_account_vs_x264() { } dec.flush().expect("flush"); while dec.next_frame().is_some() {} - dec.bit_account() + (dec.bit_account(), dec.mb_shapes()) }; for qp in [26, 34] { let mut cfg = EncoderConfig::new(w as u32, h as u32); @@ -1151,6 +1151,9 @@ fn bit_account_vs_x264() { cfg.cabac = true; cfg.framerate = 1.0; cfg.threads = 0; + if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { + cfg.preset = ec_h264::Preset::Balanced; + } let mut enc = Encoder::new(cfg).expect("encoder"); let mut ours = Vec::new(); for (y, u, v) in &sources { @@ -1158,7 +1161,7 @@ fn bit_account_vs_x264() { ours.extend_from_slice(&enc.encode(&view).expect("encode").au); } let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); - let (a, b) = (account(&ours), account(&theirs)); + let ((a, sa), (b, sb)) = (account(&ours), account(&theirs)); eprintln!( "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes", sources.len(), @@ -1183,5 +1186,63 @@ fn bit_account_vs_x264() { row("residual luma", a.residual_luma, b.residual_luma); row("residual chroma", a.residual_chroma, b.residual_chroma); row("total accounted", a.total(), b.total()); + let mix = |n: &str, s: &ec_h264::MbShapes| { + eprintln!( + " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", + s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra + ); + }; + mix("shapes ours", &sa); + mix("shapes x264", &sb); + } +} + +/// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. +/// +/// The default preset codes every P macroblock as one 16x16 partition, so the +/// bit-exactness sweeps above never put a 16x8, an 8x16 or a P_8x8 -- and so +/// never a `sub_mb_type` -- in front of another decoder. This does. +#[test] +fn balanced_partitions_decode_bit_exactly() { + if !have_ffmpeg() { + eprintln!("SKIP balanced_partitions_decode_bit_exactly: no ffmpeg on PATH"); + return; + } + let (w, h) = (176, 144); + let mut shapes = ec_h264::MbShapes::default(); + for qp in [16, 26, 36] { + let cavlc = qp == 26; // both entropy coders write sub_mb_type + let (stream, recons, _) = encode_clip(w, h, 8, |cfg| { + cfg.qp = qp; + cfg.cabac = !cavlc; + cfg.preset = ec_h264::Preset::Balanced; + }); + let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); + assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count"); + for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { + assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}"); + assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}"); + assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}"); + } + let mut dec = Decoder::new(); + dec.set_output_order(OutputOrder::Decode); + for nal in ec_h264_syntax::AnnexBIter::new(&stream) { + if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { + dec.end_picture().expect("end of picture"); + dec.push_nal(nal).expect("decoder accepts the NAL"); + } + while dec.next_frame().is_some() {} + } + dec.flush().expect("flush"); + while dec.next_frame().is_some() {} + shapes.add_public(&dec.mb_shapes()); } + eprintln!( + "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", + shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra + ); + assert!( + shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0, + "the sweep has to code every shape, or it proves nothing about them" + ); } diff --git a/lanes/h264x264-r2.report.md b/lanes/h264x264-r2.report.md index ff2bc4af..92c53c4e 100644 --- a/lanes/h264x264-r2.report.md +++ b/lanes/h264x264-r2.report.md @@ -520,3 +520,54 @@ Small numbers, and that is the finding: the search's stopping rules are not what holds the motion field back. What we do not have is the shape -- the encoder codes 16x16, 16x8 and 8x16 and nothing smaller, while x264 has the 8x8 sub- partitions. That is the next slice. + +## P_8x8, and the preset that hid it + +The encoder coded 16x16, 16x8 and 8x16 and nothing smaller. It now codes P_8x8 +with four P_L0_8x8 sub-partitions: `PShape::Quad`, a `sub_mb_type` writer on +both entropy coders, and four searches seeded from the whole-macroblock winner. + +Landing it exposed a defect in the comparison itself. The first measurement of +P_8x8 moved neither clip by a thousandth of a decibel, and neither had the split +gate swept just before it. A temporary shape histogram said why: over 1,200,000 +macroblocks of the screen capture, `whole=1200000 horiz=0 vert=0 quad=0`. The +partition search runs only at `Preset::Balanced`, and `bd_psnr_vs_x264` runs +`Preset::Fast` unless told otherwise -- so every partition number taken through +the default gate was flat by construction. The histogram stays in the encoder +behind `EC_H264_SHAPE_STATS`, because a flat sweep and a dead code path read +the same from a rate curve and only a count separates them. + +Measured where the shapes are actually searched (`EC_H264_PRESET_BALANCED=1`, +consecutive pictures, GOP 10, BD-PSNR against x264): + +| P_8x8 charged | film | screen capture | +| --- | --- | --- | +| not coded | -0.382 | -0.369 | +| 6 bits | -0.379 | -0.364 | +| 12 bits | **-0.377** | **-0.353** | +| 20 bits | -0.378 | -0.356 | + +Both contents put the optimum at twelve bits, which is about what P_8x8 signals: +an mb_type one bin longer than 16x8's plus four sub_mb_type bins. Quarters are +worth 0.005 dB on camera content and 0.016 on screen capture. + +`balanced_partitions_decode_bit_exactly` now encodes at Balanced under both +entropy coders and requires ffmpeg to reproduce our reconstruction sample for +sample, and requires the sweep to have coded at least one of every shape -- the +existing bit-exactness sweeps run the default preset, so no `sub_mb_type` had +ever been put in front of another decoder before this. + +The decoder counts shapes as well as bits now, so the mix is comparable too. +Screen capture at qp 26, twelve pictures, both encoders at their fullest search: + +| | skip | 16x16 | 16x8 | 8x16 | 8x8 | intra | +| --- | --- | --- | --- | --- | --- | --- | +| ours | 134847 | 4792 | 488 | 226 | 103 | 32344 | +| x264 | 132159 | 6410 | 920 | 355 | 294 | 32662 | + +We still split about half as often as x264 at every size, and residual luma is +still +10.9%. The gain from charging P_8x8 *more* rather than less says where +that comes from: each sub-partition is searched against the whole macroblock's +motion predictor, not its own, so the search misjudges what a split costs to +signal and picks the wrong ones. Deriving the real predictor inside the search +is the next slice.