From c2b11121f01009438887abca8f2c9ebd5ada480d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:35:13 +0300 Subject: [PATCH] U6: ec-h264 delete BitAccount, MbShapes, mark() and the _inner wrappers (inner renamed to the public name), the *_for_test cabac hooks and their engine round-trip test (cat5 round-trip still drives the engines); bit-account and shape measurement tests removed, balanced test keeps its ffmpeg bit-exact check --- crates/ec-h264/src/cabac.rs | 224 ++-------------------------- crates/ec-h264/src/decoder.rs | 102 +------------ crates/ec-h264/src/enc/cabac_enc.rs | 38 ----- crates/ec-h264/src/lib.rs | 3 +- crates/ec-h264/tests/it/encode.rs | 114 -------------- 5 files changed, 16 insertions(+), 465 deletions(-) diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index f6d5e5be..f520c2f6 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -107,49 +107,6 @@ 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). @@ -166,8 +123,6 @@ 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> { @@ -195,7 +150,6 @@ impl<'a> Cabac<'a> { ctx: MbCtx::default(), cbp_luma_bins: 0, cur_intra: true, - account: BitAccount::default(), }; c.state = init_contexts_full(slice_qp, init_column.min(3)); c.init_engine()?; @@ -293,128 +247,6 @@ 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, has_chroma: bool) -> Result<(u8, u8)> { - let m = self.mark(); - let out = self.coded_block_pattern_inner(has_chroma); - 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, - comp: u8, - na: Option, - nb: Option, - ) -> Result { - let m = self.mark(); - let out = self.residual_block_inner(coeff, cat, comp, na, nb); - let spent = self.mark() - m; - match cat { - BlockCat::ChromaDc(_) | BlockCat::ChromaDc422(_) | BlockCat::ChromaAc => { - self.account.residual_chroma += spent - } - _ if comp != 0 => self.account.residual_chroma += spent, - _ => self.account.residual_luma += spent, - } - out - } - pub(crate) fn set_intra(&mut self, intra: bool) { self.cur_intra = intra; } @@ -432,7 +264,7 @@ impl<'a> Cabac<'a> { } /// mb_type of an I slice (Table 9-36). - fn mb_type_i_inner(&mut self) -> Result { + pub(crate) fn mb_type_i(&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) @@ -461,14 +293,14 @@ impl<'a> Cabac<'a> { } /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB. - fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool { + pub(crate) fn mb_skip_flag(&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. - fn mb_type_p_inner(&mut self) -> Result { + pub(crate) fn mb_type_p(&mut self) -> Result { if self.decision(OFF_MB_TYPE_P) { return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?); } @@ -485,7 +317,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. - fn mb_type_b_inner(&mut self) -> Result { + pub(crate) fn mb_type_b(&mut self) -> Result { if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) { return Ok(0); // B_Direct_16x16 } @@ -523,7 +355,7 @@ impl<'a> Cabac<'a> { } /// sub_mb_type of a P macroblock (Table 9-38). - fn sub_mb_type_p_inner(&mut self) -> u32 { + pub(crate) fn sub_mb_type_p(&mut self) -> u32 { if self.decision(OFF_SUB_TYPE_P) { return 0; } @@ -538,7 +370,7 @@ impl<'a> Cabac<'a> { } /// sub_mb_type of a B macroblock (Table 9-38). - fn sub_mb_type_b_inner(&mut self) -> u32 { + pub(crate) fn sub_mb_type_b(&mut self) -> u32 { if !self.decision(OFF_SUB_TYPE_B) { return 0; // B_Direct_8x8 } @@ -559,7 +391,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). - fn ref_idx_inner(&mut self, inc: usize) -> Result { + pub(crate) fn ref_idx(&mut self, inc: usize) -> Result { if !self.decision(OFF_REF_IDX + inc) { return Ok(0); } @@ -578,7 +410,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. - fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result { + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { let off = OFF_MVD[comp]; if !self.decision(off + inc) { return Ok(0); @@ -603,7 +435,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. - fn transform_size_8x8_flag_inner(&mut self) -> Result { + pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { let cond = |n: Option| match n { None => 0, Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0), @@ -614,7 +446,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. - fn intra4x4_pred_mode_inner(&mut self) -> Result> { + pub(crate) fn intra4x4_pred_mode(&mut self) -> Result> { if self.decision(OFF_PREV_I4) { return Ok(None); } @@ -626,7 +458,7 @@ impl<'a> Cabac<'a> { } /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8. - fn intra_chroma_pred_mode_inner(&mut self) -> Result { + pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result { let cond = |n: Option| match n { None => 0, Some(i) => usize::from( @@ -649,7 +481,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. - fn coded_block_pattern_inner(&mut self, has_chroma: bool) -> Result<(u8, u8)> { + pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> { let (a_lower, a_blk) = match self.ctx.mbaff_a { None => (self.ctx.a, [1u8, 3]), Some(m) => (m.lower, m.blk), @@ -717,7 +549,7 @@ impl<'a> Cabac<'a> { } /// mb_qp_delta: unary bin string of the Table 9-3 mapped value. - fn mb_qp_delta_inner(&mut self) -> Result { + pub(crate) fn mb_qp_delta(&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; @@ -729,7 +561,7 @@ impl<'a> Cabac<'a> { } /// residual_block_cabac (7.3.5.3.3) for one block, in scan order. - fn residual_block_inner( + pub(crate) fn residual_block( &mut self, coeff: &mut [i32; 16], cat: BlockCat, @@ -827,22 +659,6 @@ impl<'a> Cabac<'a> { coeff: &mut [i32; 64], comp: u8, cbf: Option<(Option, Option)>, - ) -> Result { - let m = self.mark(); - let out = self.residual_block_8x8_inner(coeff, comp, cbf); - if comp == 0 { - self.account.residual_luma += self.mark() - m; - } else { - self.account.residual_chroma += self.mark() - m; - } - out - } - - fn residual_block_8x8_inner( - &mut self, - coeff: &mut [i32; 64], - comp: u8, - cbf: Option<(Option, Option)>, ) -> Result { *coeff = [0; 64]; if let Some((na, nb)) = cbf { @@ -989,18 +805,6 @@ impl<'a> Cabac<'a> { Ok(bytes) } - /// The raw engine, for the encoder's round-trip test. - #[cfg(test)] - pub(crate) fn decision_for_test(&mut self, ctx_idx: usize) -> bool { - self.decision(ctx_idx) - } - - /// The raw bypass engine, for the encoder's round-trip test. - #[cfg(test)] - pub(crate) fn bypass_for_test(&mut self) -> bool { - self.bypass() - } - /// end_of_slice_flag (ctxIdx 276, DecodeTerminate). pub(crate) fn more_macroblocks(&mut self) -> Result { debug_assert_eq!(CTX_TERMINATE, 276); diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index e2af71a9..be578999 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -29,7 +29,6 @@ use ec_h264_syntax::{ SliceType, Sps, WeightEntry, unescape_rbsp, }; -use crate::cabac::BitAccount; use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line}; use crate::dpb::{ BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE, @@ -141,9 +140,6 @@ pub(crate) struct Core { last_decoded: i32, output_order: OutputOrder, 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 @@ -278,25 +274,6 @@ impl Decoder { }) } - /// Where the bits of every CABAC slice parsed so far went, by syntax - /// class, in 1/256ths of a bit. - pub fn bit_account(&self) -> BitAccount { - if self.hbd { - self.c16.bit_account() - } else { - self.c8.bit_account() - } - } - - /// How many macroblocks of each shape this decoder has read. - pub fn mb_shapes(&self) -> MbShapes { - if self.hbd { - self.c16.mb_shapes() - } else { - self.c8.mb_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; @@ -612,8 +589,6 @@ impl Core { last_decoded: -1, output_order: OutputOrder::default(), out: VecDeque::new(), - account: BitAccount::default(), - shapes: MbShapes::default(), pending_pts: None, recovery_poc: None, cur_ref_padded: false, @@ -645,20 +620,6 @@ impl Core { 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(crate) fn bit_account(&self) -> BitAccount { - 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(crate) fn mb_shapes(&self) -> MbShapes { - self.shapes - } - /// Feed one NAL unit (header byte first, no start code). pub(crate) fn push_nal(&mut self, nal: &[u8]) -> Result { let Some((&header_byte, payload)) = nal.split_first() else { @@ -1030,7 +991,6 @@ impl Core { }; let mut ctx = SliceCtx { - shapes: MbShapes::default(), slice_id, slice_type: sh.slice_type, qp: sh.slice_qp, @@ -1071,10 +1031,6 @@ impl Core { first_mb as usize * 2, pps.entropy_coding_mode, )?; - self.shapes.add(&ctx.shapes); - if let Entropy::Cabac(c) = &r { - self.account.add(&c.account()); - } return Ok(NalOutcome::SliceDecoded); } let groups = if pps.num_slice_groups > 1 { @@ -1154,10 +1110,6 @@ impl Core { more = r.more_macroblocks()?; mb_addr = step(mb_addr); } - self.shapes.add(&ctx.shapes); - if let Entropy::Cabac(c) = &r { - self.account.add(&c.account()); - } Ok(NalOutcome::SliceDecoded) } @@ -1606,40 +1558,6 @@ fn check_supported( Ok(()) } -/// 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; - } -} - /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value. #[derive(Clone, Copy)] struct Geo { @@ -1663,6 +1581,7 @@ impl Geo { } } +/// Mutable per-slice decode state. pub(crate) struct SliceCtx { slice_id: u16, slice_type: SliceType, @@ -1699,8 +1618,6 @@ pub(crate) struct SliceCtx { /// Where the macroblock being decoded sits when the picture is an MBAFF /// frame (`pos.active`); inert otherwise. pos: MbPos, - /// How many macroblocks of each shape this slice decoded. - shapes: MbShapes, } impl SliceCtx { @@ -2241,22 +2158,6 @@ 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] }; @@ -5006,7 +4907,6 @@ mod tests { }), poc: 4, fpoc: [4, 4], - shapes: MbShapes::default(), }; let mut pic = ramp_picture(|_, _| 0); diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index 7406ec7a..7a9996fd 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -730,44 +730,6 @@ mod tests { use super::*; use crate::cabac::Cabac; - /// The engine round-trips: a pseudo-random bin string written against a - /// spread of contexts, with bypass and terminate bins mixed in, decodes - /// back identically. This is the property every syntax element rests on. - #[test] - fn engine_round_trips() { - let mut state = 0x2545_F491u32; - let mut rand = move |m: u32| { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state % m - }; - let mut plan: Vec<(usize, bool, u8)> = Vec::new(); // (ctx, bin, kind) - for _ in 0..4000 { - let kind = if rand(10) == 0 { 1 } else { 0 }; - plan.push((rand(NUM_CTX as u32) as usize, rand(2) == 1, kind)); - } - let mut enc = CabacEnc::new(BitWriter::new(), 26, 0); - for &(ctx, bin, kind) in &plan { - match kind { - 0 => enc.decision(ctx, bin), - _ => enc.bypass(bin), - } - enc.not_end_of_slice(); - } - let bytes = enc.finish().into_bytes(); - - let mut dec = Cabac::new(&bytes, 0, 26, 0).expect("decoder starts"); - for (i, &(ctx, bin, kind)) in plan.iter().enumerate() { - let got = match kind { - 0 => dec.decision_for_test(ctx), - _ => dec.bypass_for_test(), - }; - assert_eq!(got, bin, "bin {i}"); - assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end"); - } - } - /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat /// 5 blocks over a spread of densities and magnitudes all decode back /// through the decoder's own syntax readers. diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index 8b28f6b4..5d5ae4cb 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -57,8 +57,7 @@ mod sample; mod tables; mod transform; -pub use cabac::BitAccount; pub use codec::H264Decoder; -pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder}; +pub use decoder::{Decoder, NalOutcome, OutputOrder}; pub use ec_core::error::{Error, Result}; pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; diff --git a/crates/ec-h264/tests/it/encode.rs b/crates/ec-h264/tests/it/encode.rs index 36cffd42..9a3ee3e4 100644 --- a/crates/ec-h264/tests/it/encode.rs +++ b/crates/ec-h264/tests/it/encode.rs @@ -1385,99 +1385,6 @@ 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() { - assert!(have_x264(), "the pinned ffmpeg has no libx264"); - 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(), dec.mb_shapes()) - }; - 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; - 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 { - 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, sa), (b, sb)) = (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()); - 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 @@ -1486,7 +1393,6 @@ fn bit_account_vs_x264() { #[test] fn balanced_partitions_decode_bit_exactly() { 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| { @@ -1501,27 +1407,7 @@ fn balanced_partitions_decode_bit_exactly() { 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" - ); } #[test]