diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index 348bb70d..d9df4165 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -80,6 +80,49 @@ pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35]; +/// Where a slice's bits went, in 1/256ths of a bit, by syntax class. The +/// arithmetic decoder spends fractional bits per element, so the sub-bit +/// resolution is the point: a class is charged the movement of +/// `bit_position * 256 + log2(codIRange)` across its own reads. Both our +/// streams and any other encoder's are parsed by this decoder, which is what +/// makes the two accounts comparable. +#[derive(Clone, Copy, Default, Debug)] +pub struct BitAccount { + pub skip: u64, + pub mb_type: u64, + pub mv: u64, + pub ref_idx: u64, + pub cbp_qp: u64, + pub intra_mode: u64, + pub residual_luma: u64, + pub residual_chroma: u64, +} + +impl BitAccount { + /// Every class summed, in 1/256ths of a bit. + pub fn total(&self) -> u64 { + self.skip + + self.mb_type + + self.mv + + self.ref_idx + + self.cbp_qp + + self.intra_mode + + self.residual_luma + + self.residual_chroma + } + + pub(crate) fn add(&mut self, other: &BitAccount) { + self.skip += other.skip; + self.mb_type += other.mb_type; + self.mv += other.mv; + self.ref_idx += other.ref_idx; + self.cbp_qp += other.cbp_qp; + self.intra_mode += other.intra_mode; + self.residual_luma += other.residual_luma; + self.residual_chroma += other.residual_chroma; + } +} + pub(crate) struct Cabac<'a> { r: BitCursor<'a>, /// codIRange (9.3.3.2). @@ -96,6 +139,8 @@ pub(crate) struct Cabac<'a> { /// The macroblock being parsed is intra coded, which flips the /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9). cur_intra: bool, + /// Bits spent so far, by syntax class. + account: BitAccount, } impl<'a> Cabac<'a> { @@ -123,6 +168,7 @@ impl<'a> Cabac<'a> { ctx: MbCtx::default(), cbp_luma_bins: 0, cur_intra: true, + account: BitAccount::default(), }; c.state = init_contexts(slice_qp, init_column.min(3)); c.init_engine()?; @@ -210,6 +256,124 @@ impl<'a> Cabac<'a> { /// Declare whether the macroblock being parsed is intra coded /// (9.3.3.1.1.9 reads it for every coded_block_flag). + /// The decoder's position in 1/256ths of a bit: the bits already read plus + /// what the arithmetic engine's interval says it is holding. + fn mark(&self) -> u64 { + self.r.bit_position() * 256 + u64::from(self.range.leading_zeros()) + } + + pub(crate) fn account(&self) -> BitAccount { + self.account + } + + pub(crate) fn mb_type_i(&mut self) -> Result { + let m = self.mark(); + let out = self.mb_type_i_inner(); + self.account.mb_type += self.mark() - m; + out + } + + pub(crate) fn mb_type_p(&mut self) -> Result { + let m = self.mark(); + let out = self.mb_type_p_inner(); + self.account.mb_type += self.mark() - m; + out + } + + pub(crate) fn mb_type_b(&mut self) -> Result { + let m = self.mark(); + let out = self.mb_type_b_inner(); + self.account.mb_type += self.mark() - m; + out + } + + pub(crate) fn sub_mb_type_p(&mut self) -> u32 { + let m = self.mark(); + let out = self.sub_mb_type_p_inner(); + self.account.mb_type += self.mark() - m; + out + } + + pub(crate) fn sub_mb_type_b(&mut self) -> u32 { + let m = self.mark(); + let out = self.sub_mb_type_b_inner(); + self.account.mb_type += self.mark() - m; + out + } + + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { + let m = self.mark(); + let out = self.mb_skip_flag_inner(b_slice, inc); + self.account.skip += self.mark() - m; + out + } + + pub(crate) fn ref_idx(&mut self, inc: usize) -> Result { + let m = self.mark(); + let out = self.ref_idx_inner(inc); + self.account.ref_idx += self.mark() - m; + out + } + + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { + let m = self.mark(); + let out = self.mvd_inner(comp, inc); + self.account.mv += self.mark() - m; + out + } + + pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { + let m = self.mark(); + let out = self.transform_size_8x8_flag_inner(); + self.account.cbp_qp += self.mark() - m; + out + } + + pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> { + let m = self.mark(); + let out = self.coded_block_pattern_inner(); + self.account.cbp_qp += self.mark() - m; + out + } + + pub(crate) fn mb_qp_delta(&mut self) -> Result { + let m = self.mark(); + let out = self.mb_qp_delta_inner(); + self.account.cbp_qp += self.mark() - m; + out + } + + pub(crate) fn intra4x4_pred_mode(&mut self) -> Result> { + let m = self.mark(); + let out = self.intra4x4_pred_mode_inner(); + self.account.intra_mode += self.mark() - m; + out + } + + pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result { + let m = self.mark(); + let out = self.intra_chroma_pred_mode_inner(); + self.account.intra_mode += self.mark() - m; + out + } + + pub(crate) fn residual_block( + &mut self, + coeff: &mut [i32; 16], + cat: BlockCat, + na: Option, + nb: Option, + ) -> Result { + let m = self.mark(); + let out = self.residual_block_inner(coeff, cat, na, nb); + let spent = self.mark() - m; + match cat { + BlockCat::ChromaDc(_) | BlockCat::ChromaAc => self.account.residual_chroma += spent, + _ => self.account.residual_luma += spent, + } + out + } + pub(crate) fn set_intra(&mut self, intra: bool) { self.cur_intra = intra; } @@ -227,7 +391,7 @@ impl<'a> Cabac<'a> { } /// mb_type of an I slice (Table 9-36). - pub(crate) fn mb_type_i(&mut self) -> Result { + fn mb_type_i_inner(&mut self) -> Result { let mut ctx = I_MB_TYPE_CTX; ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE); self.mb_type_intra(&ctx) @@ -256,14 +420,14 @@ impl<'a> Cabac<'a> { } /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB. - pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { + fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool { let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P }; self.decision(off + inc) } /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice /// mb_type for an intra macroblock. - pub(crate) fn mb_type_p(&mut self) -> Result { + fn mb_type_p_inner(&mut self) -> Result { if self.decision(OFF_MB_TYPE_P) { return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?); } @@ -280,7 +444,7 @@ impl<'a> Cabac<'a> { /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice /// mb_type for an intra macroblock. - pub(crate) fn mb_type_b(&mut self) -> Result { + fn mb_type_b_inner(&mut self) -> Result { if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) { return Ok(0); // B_Direct_16x16 } @@ -318,7 +482,7 @@ impl<'a> Cabac<'a> { } /// sub_mb_type of a P macroblock (Table 9-38). - pub(crate) fn sub_mb_type_p(&mut self) -> u32 { + fn sub_mb_type_p_inner(&mut self) -> u32 { if self.decision(OFF_SUB_TYPE_P) { return 0; } @@ -333,7 +497,7 @@ impl<'a> Cabac<'a> { } /// sub_mb_type of a B macroblock (Table 9-38). - pub(crate) fn sub_mb_type_b(&mut self) -> u32 { + fn sub_mb_type_b_inner(&mut self) -> u32 { if !self.decision(OFF_SUB_TYPE_B) { return 0; // B_Direct_8x8 } @@ -354,7 +518,7 @@ impl<'a> Cabac<'a> { /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the /// first bin (Table 9-39 row 54). - pub(crate) fn ref_idx(&mut self, inc: usize) -> Result { + fn ref_idx_inner(&mut self, inc: usize) -> Result { if !self.decision(OFF_REF_IDX + inc) { return Ok(0); } @@ -373,7 +537,7 @@ impl<'a> Cabac<'a> { /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7. - pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { + fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result { let off = OFF_MVD[comp]; if !self.decision(off + inc) { return Ok(0); @@ -398,7 +562,7 @@ impl<'a> Cabac<'a> { /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is /// available and carried the flag itself. - pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { + fn transform_size_8x8_flag_inner(&mut self) -> Result { let cond = |n: Option| match n { None => 0, Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0), @@ -409,7 +573,7 @@ impl<'a> Cabac<'a> { /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7 /// with binIdx 0 the least significant bit. - pub(crate) fn intra4x4_pred_mode(&mut self) -> Result> { + fn intra4x4_pred_mode_inner(&mut self) -> Result> { if self.decision(OFF_PREV_I4) { return Ok(None); } @@ -421,7 +585,7 @@ impl<'a> Cabac<'a> { } /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8. - pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result { + fn intra_chroma_pred_mode_inner(&mut self) -> Result { let cond = |n: Option| match n { None => 0, Some(i) => usize::from( @@ -444,7 +608,7 @@ impl<'a> Cabac<'a> { /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma /// suffix, both with the neighbour contexts of 9.3.3.1.1.4. - pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> { + fn coded_block_pattern_inner(&mut self) -> Result<(u8, u8)> { for bin in 0..4u8 { // 6.4.11.2: the 8x8 block left of / above block `bin`, which for // blocks 1, 2 and 3 can be inside this macroblock. @@ -501,7 +665,7 @@ impl<'a> Cabac<'a> { } /// mb_qp_delta: unary bin string of the Table 9-3 mapped value. - pub(crate) fn mb_qp_delta(&mut self) -> Result { + fn mb_qp_delta_inner(&mut self) -> Result { let mut k = 0i32; while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) { k += 1; @@ -513,7 +677,7 @@ impl<'a> Cabac<'a> { } /// residual_block_cabac (7.3.5.3.3) for one block, in scan order. - pub(crate) fn residual_block( + fn residual_block_inner( &mut self, coeff: &mut [i32; 16], cat: BlockCat, @@ -575,6 +739,13 @@ impl<'a> Cabac<'a> { /// coded_block_pattern bit that selected this block is the whole signal and /// the flag is inferred to be 1. pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result { + let m = self.mark(); + let out = self.residual_block_8x8_inner(coeff); + self.account.residual_luma += self.mark() - m; + out + } + + fn residual_block_8x8_inner(&mut self, coeff: &mut [i32; 64]) -> Result { *coeff = [0; 64]; let mut sig = [false; 64]; let mut num = 64; diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 2aaa66e8..d11f4cf6 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -29,6 +29,7 @@ use ec_h264_syntax::{ SliceType, Sps, WeightEntry, unescape_rbsp, }; +use crate::cabac::BitAccount; use crate::deblock::{ chroma_qp, edge_params, filter_chroma_h_edge8, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, @@ -132,6 +133,8 @@ pub struct Decoder { last_decoded: i32, output_order: OutputOrder, out: VecDeque, + /// Bits parsed so far, by syntax class (CABAC slices only). + account: BitAccount, /// Presentation timestamp to attach to the next picture started. pending_pts: Option, /// `PicOrderCnt` of the random-access point most recently established by @@ -211,6 +214,7 @@ impl Decoder { last_decoded: -1, output_order: OutputOrder::default(), out: VecDeque::new(), + account: BitAccount::default(), pending_pts: None, recovery_poc: None, cur_ref_padded: false, @@ -242,6 +246,14 @@ impl Decoder { Some((sps.width, sps.height)) } + /// Where the bits of every CABAC slice parsed so far went, by syntax + /// class, in 1/256ths of a bit. Any conforming stream can be measured + /// this way, so an encoder's spending can be compared with another's + /// through one account. + pub fn bit_account(&self) -> BitAccount { + self.account + } + /// 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; @@ -621,6 +633,9 @@ impl Decoder { more = r.more_macroblocks()?; mb_addr += 1; } + if let Entropy::Cabac(c) = &r { + self.account.add(&c.account()); + } Ok(NalOutcome::SliceDecoded) } @@ -2734,6 +2749,10 @@ fn boundary_strength( } else { (mb_x * 4 + seg, mb_y * 4 + edge) }; - let (pbx, pby) = if vertical { (qbx - 1, qby) } else { (qbx, qby - 1) }; + let (pbx, pby) = if vertical { + (qbx - 1, qby) + } else { + (qbx, qby - 1) + }; bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0) } diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index 13d96255..2e8f143a 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -49,6 +49,7 @@ mod pred; mod tables; mod transform; +pub use cabac::BitAccount; pub use codec::H264Decoder; pub use decoder::{Decoder, NalOutcome, OutputOrder}; pub use ec_core::error::{Error, Result}; diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index b790f2a0..5a3af2b5 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -1100,3 +1100,88 @@ fn bd_psnr_vs_x264() { ); } } + +/// Where our bits go against where x264's go, class by class, on the same +/// sources at the same QP. Both streams are parsed by this crate's decoder, so +/// the two accounts are the same measurement; the BD-PSNR gate says how much +/// we overspend, this says on what. +/// +/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture +/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ +/// bit_account_vs_x264 -- --nocapture +#[test] +fn bit_account_vs_x264() { + if !have_ffmpeg() || !have_x264() { + eprintln!("SKIP bit_account_vs_x264: no ffmpeg with libx264 on PATH"); + return; + } + let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { + Some(path) => clip_sources(&path, 12), + None => { + let (w, h, frames) = (352, 288, 12); + let mut clip = Clip::new(w, h); + let mut sources = Vec::with_capacity(frames); + for t in 0..frames { + clip.render_smooth(t); + sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); + } + eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); + (w, h, sources) + } + }; + let gop: u32 = 10; + let account = |stream: &[u8]| { + 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() {} + dec.bit_account() + }; + for qp in [26, 34] { + let mut cfg = EncoderConfig::new(w as u32, h as u32); + cfg.qp = qp; + cfg.gop_size = gop; + cfg.cabac = true; + cfg.framerate = 1.0; + cfg.threads = 0; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut ours = Vec::new(); + for (y, u, v) in &sources { + let view = PictureView::i420(w as u32, h as u32, y, u, v); + 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)); + eprintln!( + "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes", + sources.len(), + ours.len(), + theirs.len() + ); + let row = |name: &str, ours: u64, theirs: u64| { + let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0); + let delta = if t > 0.0 { + format!("{:+.1}%", (o - t) / t * 100.0) + } else { + "--".to_string() + }; + eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}"); + }; + row("skip", a.skip, b.skip); + row("mb_type", a.mb_type, b.mb_type); + row("mv", a.mv, b.mv); + row("ref_idx", a.ref_idx, b.ref_idx); + row("cbp+qp", a.cbp_qp, b.cbp_qp); + row("intra modes", a.intra_mode, b.intra_mode); + 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()); + } +} diff --git a/lanes/h264x264-r2.report.md b/lanes/h264x264-r2.report.md index 8f3d9526..40de5fa1 100644 --- a/lanes/h264x264-r2.report.md +++ b/lanes/h264x264-r2.report.md @@ -436,3 +436,57 @@ Recorded so the constant is not re-swept a third time: the remaining gap is not an operating-point tilt. It is bits -- we spend 13% more than x264 at 0.45 dB higher PSNR on the film clip -- so the places left to look are the ones that decide what to spend them on. + +## Where the bits actually go + +The BD-PSNR gate says how much we overspend. It cannot say on what. So the decoder +now counts, per syntax class, the CABAC bits a stream spends: `BitAccount` marks the +arithmetic decoder's position (`bit_position() * 256 + range.leading_zeros()`) before +and after each syntax element and attributes the difference to one of eight classes. +Because the counting lives in the decoder, our stream and x264's stream are measured +by the same instrument on the same sources at the same QP -- `bit_account_vs_x264` +in `tests/encode.rs` encodes both, decodes both, and prints the table. + +Twelve consecutive pictures, GOP 10, CABAC, our defaults against the matched x264 +feature set. Percentages are ours relative to x264. + +3840x1608 film clip: + +| class | qp 26 | qp 34 | +| --- | --- | --- | +| skip | -1.3% | +6.1% | +| mb_type | -11.2% | +3.7% | +| mv | -14.7% | +14.0% | +| cbp+qp | +6.6% | +25.5% | +| intra modes | +11.2% | +12.5% | +| residual luma | +19.8% | +23.9% | +| residual chroma | +7.8% | +6.9% | +| total accounted | +10.9% | +13.4% | + +2560x1440 screen capture: + +| class | qp 26 | qp 34 | +| --- | --- | --- | +| skip | -21.9% | -17.4% | +| mb_type | -12.2% | +0.8% | +| mv | -24.8% | -31.2% | +| cbp+qp | +8.4% | +13.0% | +| intra modes | +28.9% | +12.6% | +| residual luma | +15.4% | +11.0% | +| residual chroma | +3.8% | -14.1% | +| total accounted | +10.9% | +6.6% | + +352x288 synthetic, where the gap is largest, reads the same way only louder: +residual luma +64.9% at qp 26 and +82.1% at qp 34, mv -20.0% and -25.7%. + +One shape in all three sources. We spend *less* than x264 on describing motion -- +fewer skip bits, fewer mb_type bits, fewer mvd bits -- and more on everything that +follows from the prediction those choices produce: residual luma first, then the +coded-block-pattern and QP deltas that carry it, then the intra modes we fall back +to when inter prediction is not good enough. x264 buys a cheaper residual by paying +more for the motion field, and comes out ahead on the sum. + +That is a prediction result, not an entropy-coding one. The residual coder is now +priced exactly and quantised against that price; the next thing to look at is what +we hand it -- how the motion search chooses, and how the partition and mode decision +weighs a more expensive motion field against the residual it saves.