forge
Explore
Log in

Don't you dare go Hollow

Count CABAC bits by syntax class in the decoder

Browse files at this commit

0723a4914ae9ae079507e061a2a384f3acbe6b89Ahmet Kaan GümüşParent: 6deb39c
  • feat
    • count CABAC bits by syntax class in the decoder
Show full message
feat(h264): count CABAC bits by syntax class in the decoder

The rate gate says how much we overspend against x264; it cannot say on
what. BitAccount marks the arithmetic decoder's position before and after
each syntax element and attributes the difference to one of eight classes,
so any conforming stream -- ours or x264's -- is measured by one
instrument. bit_account_vs_x264 encodes both, decodes both, prints the
table.

The answer is the same on all three sources: we spend fewer bits than
x264 on skip, mb_type and mvd, and more on residual luma, cbp+qp and
intra modes. x264 buys a cheaper residual by paying more for the motion
field. That points the next lane at prediction, not at entropy coding.
crates/ec-h264/src/cabac.rsmodified+185 -14
@@ -80,6 +80,49 @@ pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10];
80 pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20];80 pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20];
81 const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35];81 const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35];
82 82
83+/// Where a slice's bits went, in 1/256ths of a bit, by syntax class. The
84+/// arithmetic decoder spends fractional bits per element, so the sub-bit
85+/// resolution is the point: a class is charged the movement of
86+/// `bit_position * 256 + log2(codIRange)` across its own reads. Both our
87+/// streams and any other encoder's are parsed by this decoder, which is what
88+/// makes the two accounts comparable.
89+#[derive(Clone, Copy, Default, Debug)]
90+pub struct BitAccount {
91+ pub skip: u64,
92+ pub mb_type: u64,
93+ pub mv: u64,
94+ pub ref_idx: u64,
95+ pub cbp_qp: u64,
96+ pub intra_mode: u64,
97+ pub residual_luma: u64,
98+ pub residual_chroma: u64,
99+}
100+
101+impl BitAccount {
102+ /// Every class summed, in 1/256ths of a bit.
103+ pub fn total(&self) -> u64 {
104+ self.skip
105+ + self.mb_type
106+ + self.mv
107+ + self.ref_idx
108+ + self.cbp_qp
109+ + self.intra_mode
110+ + self.residual_luma
111+ + self.residual_chroma
112+ }
113+
114+ pub(crate) fn add(&mut self, other: &BitAccount) {
115+ self.skip += other.skip;
116+ self.mb_type += other.mb_type;
117+ self.mv += other.mv;
118+ self.ref_idx += other.ref_idx;
119+ self.cbp_qp += other.cbp_qp;
120+ self.intra_mode += other.intra_mode;
121+ self.residual_luma += other.residual_luma;
122+ self.residual_chroma += other.residual_chroma;
123+ }
124+}
125+
83 pub(crate) struct Cabac<'a> {126 pub(crate) struct Cabac<'a> {
84 r: BitCursor<'a>,127 r: BitCursor<'a>,
85 /// codIRange (9.3.3.2).128 /// codIRange (9.3.3.2).
@@ -96,6 +139,8 @@ pub(crate) struct Cabac<'a> {
96 /// The macroblock being parsed is intra coded, which flips the139 /// The macroblock being parsed is intra coded, which flips the
97 /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9).140 /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9).
98 cur_intra: bool,141 cur_intra: bool,
142+ /// Bits spent so far, by syntax class.
143+ account: BitAccount,
99 }144 }
100 145
101 impl<'a> Cabac<'a> {146 impl<'a> Cabac<'a> {
@@ -123,6 +168,7 @@ impl<'a> Cabac<'a> {
123 ctx: MbCtx::default(),168 ctx: MbCtx::default(),
124 cbp_luma_bins: 0,169 cbp_luma_bins: 0,
125 cur_intra: true,170 cur_intra: true,
171+ account: BitAccount::default(),
126 };172 };
127 c.state = init_contexts(slice_qp, init_column.min(3));173 c.state = init_contexts(slice_qp, init_column.min(3));
128 c.init_engine()?;174 c.init_engine()?;
@@ -210,6 +256,124 @@ impl<'a> Cabac<'a> {
210 256
211 /// Declare whether the macroblock being parsed is intra coded257 /// Declare whether the macroblock being parsed is intra coded
212 /// (9.3.3.1.1.9 reads it for every coded_block_flag).258 /// (9.3.3.1.1.9 reads it for every coded_block_flag).
259+ /// The decoder's position in 1/256ths of a bit: the bits already read plus
260+ /// what the arithmetic engine's interval says it is holding.
261+ fn mark(&self) -> u64 {
262+ self.r.bit_position() * 256 + u64::from(self.range.leading_zeros())
263+ }
264+
265+ pub(crate) fn account(&self) -> BitAccount {
266+ self.account
267+ }
268+
269+ pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
270+ let m = self.mark();
271+ let out = self.mb_type_i_inner();
272+ self.account.mb_type += self.mark() - m;
273+ out
274+ }
275+
276+ pub(crate) fn mb_type_p(&mut self) -> Result<u32> {
277+ let m = self.mark();
278+ let out = self.mb_type_p_inner();
279+ self.account.mb_type += self.mark() - m;
280+ out
281+ }
282+
283+ pub(crate) fn mb_type_b(&mut self) -> Result<u32> {
284+ let m = self.mark();
285+ let out = self.mb_type_b_inner();
286+ self.account.mb_type += self.mark() - m;
287+ out
288+ }
289+
290+ pub(crate) fn sub_mb_type_p(&mut self) -> u32 {
291+ let m = self.mark();
292+ let out = self.sub_mb_type_p_inner();
293+ self.account.mb_type += self.mark() - m;
294+ out
295+ }
296+
297+ pub(crate) fn sub_mb_type_b(&mut self) -> u32 {
298+ let m = self.mark();
299+ let out = self.sub_mb_type_b_inner();
300+ self.account.mb_type += self.mark() - m;
301+ out
302+ }
303+
304+ pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool {
305+ let m = self.mark();
306+ let out = self.mb_skip_flag_inner(b_slice, inc);
307+ self.account.skip += self.mark() - m;
308+ out
309+ }
310+
311+ pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> {
312+ let m = self.mark();
313+ let out = self.ref_idx_inner(inc);
314+ self.account.ref_idx += self.mark() - m;
315+ out
316+ }
317+
318+ pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {
319+ let m = self.mark();
320+ let out = self.mvd_inner(comp, inc);
321+ self.account.mv += self.mark() - m;
322+ out
323+ }
324+
325+ pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
326+ let m = self.mark();
327+ let out = self.transform_size_8x8_flag_inner();
328+ self.account.cbp_qp += self.mark() - m;
329+ out
330+ }
331+
332+ pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> {
333+ let m = self.mark();
334+ let out = self.coded_block_pattern_inner();
335+ self.account.cbp_qp += self.mark() - m;
336+ out
337+ }
338+
339+ pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
340+ let m = self.mark();
341+ let out = self.mb_qp_delta_inner();
342+ self.account.cbp_qp += self.mark() - m;
343+ out
344+ }
345+
346+ pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
347+ let m = self.mark();
348+ let out = self.intra4x4_pred_mode_inner();
349+ self.account.intra_mode += self.mark() - m;
350+ out
351+ }
352+
353+ pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
354+ let m = self.mark();
355+ let out = self.intra_chroma_pred_mode_inner();
356+ self.account.intra_mode += self.mark() - m;
357+ out
358+ }
359+
360+ pub(crate) fn residual_block(
361+ &mut self,
362+ coeff: &mut [i32; 16],
363+ cat: BlockCat,
364+ na: Option<u8>,
365+ nb: Option<u8>,
366+ ) -> Result<u8> {
367+ let m = self.mark();
368+ let out = self.residual_block_inner(coeff, cat, na, nb);
369+ let spent = self.mark() - m;
370+ match cat {
371+ BlockCat::ChromaDc(_) | BlockCat::ChromaAc => self.account.residual_chroma += spent,
372+ _ => self.account.residual_luma += spent,
373+ }
374+ out
375+ }
376+
213 pub(crate) fn set_intra(&mut self, intra: bool) {377 pub(crate) fn set_intra(&mut self, intra: bool) {
214 self.cur_intra = intra;378 self.cur_intra = intra;
215 }379 }
@@ -227,7 +391,7 @@ impl<'a> Cabac<'a> {
227 }391 }
228 392
229 /// mb_type of an I slice (Table 9-36).393 /// mb_type of an I slice (Table 9-36).
230- pub(crate) fn mb_type_i(&mut self) -> Result<u32> {394+ fn mb_type_i_inner(&mut self) -> Result<u32> {
231 let mut ctx = I_MB_TYPE_CTX;395 let mut ctx = I_MB_TYPE_CTX;
232 ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE);396 ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE);
233 self.mb_type_intra(&ctx)397 self.mb_type_intra(&ctx)
@@ -256,14 +420,14 @@ impl<'a> Cabac<'a> {
256 }420 }
257 421
258 /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB.422 /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB.
259- pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool {423+ fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool {
260 let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P };424 let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P };
261 self.decision(off + inc)425 self.decision(off + inc)
262 }426 }
263 427
264 /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice428 /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice
265 /// mb_type for an intra macroblock.429 /// mb_type for an intra macroblock.
266- pub(crate) fn mb_type_p(&mut self) -> Result<u32> {430+ fn mb_type_p_inner(&mut self) -> Result<u32> {
267 if self.decision(OFF_MB_TYPE_P) {431 if self.decision(OFF_MB_TYPE_P) {
268 return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?);432 return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?);
269 }433 }
@@ -280,7 +444,7 @@ impl<'a> Cabac<'a> {
280 444
281 /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice445 /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice
282 /// mb_type for an intra macroblock.446 /// mb_type for an intra macroblock.
283- pub(crate) fn mb_type_b(&mut self) -> Result<u32> {447+ fn mb_type_b_inner(&mut self) -> Result<u32> {
284 if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) {448 if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) {
285 return Ok(0); // B_Direct_16x16449 return Ok(0); // B_Direct_16x16
286 }450 }
@@ -318,7 +482,7 @@ impl<'a> Cabac<'a> {
318 }482 }
319 483
320 /// sub_mb_type of a P macroblock (Table 9-38).484 /// sub_mb_type of a P macroblock (Table 9-38).
321- pub(crate) fn sub_mb_type_p(&mut self) -> u32 {485+ fn sub_mb_type_p_inner(&mut self) -> u32 {
322 if self.decision(OFF_SUB_TYPE_P) {486 if self.decision(OFF_SUB_TYPE_P) {
323 return 0;487 return 0;
324 }488 }
@@ -333,7 +497,7 @@ impl<'a> Cabac<'a> {
333 }497 }
334 498
335 /// sub_mb_type of a B macroblock (Table 9-38).499 /// sub_mb_type of a B macroblock (Table 9-38).
336- pub(crate) fn sub_mb_type_b(&mut self) -> u32 {500+ fn sub_mb_type_b_inner(&mut self) -> u32 {
337 if !self.decision(OFF_SUB_TYPE_B) {501 if !self.decision(OFF_SUB_TYPE_B) {
338 return 0; // B_Direct_8x8502 return 0; // B_Direct_8x8
339 }503 }
@@ -354,7 +518,7 @@ impl<'a> Cabac<'a> {
354 518
355 /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the519 /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the
356 /// first bin (Table 9-39 row 54).520 /// first bin (Table 9-39 row 54).
357- pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> {521+ fn ref_idx_inner(&mut self, inc: usize) -> Result<u32> {
358 if !self.decision(OFF_REF_IDX + inc) {522 if !self.decision(OFF_REF_IDX + inc) {
359 return Ok(0);523 return Ok(0);
360 }524 }
@@ -373,7 +537,7 @@ impl<'a> Cabac<'a> {
373 537
374 /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with538 /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with
375 /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7.539 /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7.
376- pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {540+ fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result<i32> {
377 let off = OFF_MVD[comp];541 let off = OFF_MVD[comp];
378 if !self.decision(off + inc) {542 if !self.decision(off + inc) {
379 return Ok(0);543 return Ok(0);
@@ -398,7 +562,7 @@ impl<'a> Cabac<'a> {
398 562
399 /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is563 /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is
400 /// available and carried the flag itself.564 /// available and carried the flag itself.
401- pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {565+ fn transform_size_8x8_flag_inner(&mut self) -> Result<bool> {
402 let cond = |n: Option<MbInfo>| match n {566 let cond = |n: Option<MbInfo>| match n {
403 None => 0,567 None => 0,
404 Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0),568 Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0),
@@ -409,7 +573,7 @@ impl<'a> Cabac<'a> {
409 573
410 /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7574 /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7
411 /// with binIdx 0 the least significant bit.575 /// with binIdx 0 the least significant bit.
412- pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {576+ fn intra4x4_pred_mode_inner(&mut self) -> Result<Option<u8>> {
413 if self.decision(OFF_PREV_I4) {577 if self.decision(OFF_PREV_I4) {
414 return Ok(None);578 return Ok(None);
415 }579 }
@@ -421,7 +585,7 @@ impl<'a> Cabac<'a> {
421 }585 }
422 586
423 /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8.587 /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8.
424- pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {588+ fn intra_chroma_pred_mode_inner(&mut self) -> Result<u8> {
425 let cond = |n: Option<MbInfo>| match n {589 let cond = |n: Option<MbInfo>| match n {
426 None => 0,590 None => 0,
427 Some(i) => usize::from(591 Some(i) => usize::from(
@@ -444,7 +608,7 @@ impl<'a> Cabac<'a> {
444 608
445 /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma609 /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma
446 /// suffix, both with the neighbour contexts of 9.3.3.1.1.4.610 /// suffix, both with the neighbour contexts of 9.3.3.1.1.4.
447- pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> {611+ fn coded_block_pattern_inner(&mut self) -> Result<(u8, u8)> {
448 for bin in 0..4u8 {612 for bin in 0..4u8 {
449 // 6.4.11.2: the 8x8 block left of / above block `bin`, which for613 // 6.4.11.2: the 8x8 block left of / above block `bin`, which for
450 // blocks 1, 2 and 3 can be inside this macroblock.614 // blocks 1, 2 and 3 can be inside this macroblock.
@@ -501,7 +665,7 @@ impl<'a> Cabac<'a> {
501 }665 }
502 666
503 /// mb_qp_delta: unary bin string of the Table 9-3 mapped value.667 /// mb_qp_delta: unary bin string of the Table 9-3 mapped value.
504- pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {668+ fn mb_qp_delta_inner(&mut self) -> Result<i32> {
505 let mut k = 0i32;669 let mut k = 0i32;
506 while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) {670 while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) {
507 k += 1;671 k += 1;
@@ -513,7 +677,7 @@ impl<'a> Cabac<'a> {
513 }677 }
514 678
515 /// residual_block_cabac (7.3.5.3.3) for one block, in scan order.679 /// residual_block_cabac (7.3.5.3.3) for one block, in scan order.
516- pub(crate) fn residual_block(680+ fn residual_block_inner(
517 &mut self,681 &mut self,
518 coeff: &mut [i32; 16],682 coeff: &mut [i32; 16],
519 cat: BlockCat,683 cat: BlockCat,
@@ -575,6 +739,13 @@ impl<'a> Cabac<'a> {
575 /// coded_block_pattern bit that selected this block is the whole signal and739 /// coded_block_pattern bit that selected this block is the whole signal and
576 /// the flag is inferred to be 1.740 /// the flag is inferred to be 1.
577 pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {741 pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
742+ let m = self.mark();
743+ let out = self.residual_block_8x8_inner(coeff);
744+ self.account.residual_luma += self.mark() - m;
745+ out
746+ }
747+
748+ fn residual_block_8x8_inner(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
578 *coeff = [0; 64];749 *coeff = [0; 64];
579 let mut sig = [false; 64];750 let mut sig = [false; 64];
580 let mut num = 64;751 let mut num = 64;
crates/ec-h264/src/decoder.rsmodified+20 -1
@@ -29,6 +29,7 @@ use ec_h264_syntax::{
29 SliceType, Sps, WeightEntry, unescape_rbsp,29 SliceType, Sps, WeightEntry, unescape_rbsp,
30 };30 };
31 31
32+use crate::cabac::BitAccount;
32 use crate::deblock::{33 use crate::deblock::{
33 chroma_qp, edge_params, filter_chroma_h_edge8, filter_chroma_line, filter_luma_h_edge16,34 chroma_qp, edge_params, filter_chroma_h_edge8, filter_chroma_line, filter_luma_h_edge16,
34 filter_luma_line,35 filter_luma_line,
@@ -132,6 +133,8 @@ pub struct Decoder {
132 last_decoded: i32,133 last_decoded: i32,
133 output_order: OutputOrder,134 output_order: OutputOrder,
134 out: VecDeque<VideoFrame>,135 out: VecDeque<VideoFrame>,
136+ /// Bits parsed so far, by syntax class (CABAC slices only).
137+ account: BitAccount,
135 /// Presentation timestamp to attach to the next picture started.138 /// Presentation timestamp to attach to the next picture started.
136 pending_pts: Option<Timestamp>,139 pending_pts: Option<Timestamp>,
137 /// `PicOrderCnt` of the random-access point most recently established by140 /// `PicOrderCnt` of the random-access point most recently established by
@@ -211,6 +214,7 @@ impl Decoder {
211 last_decoded: -1,214 last_decoded: -1,
212 output_order: OutputOrder::default(),215 output_order: OutputOrder::default(),
213 out: VecDeque::new(),216 out: VecDeque::new(),
217+ account: BitAccount::default(),
214 pending_pts: None,218 pending_pts: None,
215 recovery_poc: None,219 recovery_poc: None,
216 cur_ref_padded: false,220 cur_ref_padded: false,
@@ -242,6 +246,14 @@ impl Decoder {
242 Some((sps.width, sps.height))246 Some((sps.width, sps.height))
243 }247 }
244 248
249+ /// Where the bits of every CABAC slice parsed so far went, by syntax
250+ /// class, in 1/256ths of a bit. Any conforming stream can be measured
251+ /// this way, so an encoder's spending can be compared with another's
252+ /// through one account.
253+ pub fn bit_account(&self) -> BitAccount {
254+ self.account
255+ }
256+
245 /// Decode the first IDR picture of an Annex B stream and return it.257 /// Decode the first IDR picture of an Annex B stream and return it.
246 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {258 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
247 let mut got_slice = false;259 let mut got_slice = false;
@@ -621,6 +633,9 @@ impl Decoder {
621 more = r.more_macroblocks()?;633 more = r.more_macroblocks()?;
622 mb_addr += 1;634 mb_addr += 1;
623 }635 }
636+ if let Entropy::Cabac(c) = &r {
637+ self.account.add(&c.account());
638+ }
624 Ok(NalOutcome::SliceDecoded)639 Ok(NalOutcome::SliceDecoded)
625 }640 }
626 641
@@ -2734,6 +2749,10 @@ fn boundary_strength(
2734 } else {2749 } else {
2735 (mb_x * 4 + seg, mb_y * 4 + edge)2750 (mb_x * 4 + seg, mb_y * 4 + edge)
2736 };2751 };
2737- let (pbx, pby) = if vertical { (qbx - 1, qby) } else { (qbx, qby - 1) };2752+ let (pbx, pby) = if vertical {
2753+ (qbx - 1, qby)
2754+ } else {
2755+ (qbx, qby - 1)
2756+ };
2738 bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0)2757 bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0)
2739 }2758 }
crates/ec-h264/src/lib.rsmodified+1 -0
@@ -49,6 +49,7 @@ mod pred;
49 mod tables;49 mod tables;
50 mod transform;50 mod transform;
51 51
52+pub use cabac::BitAccount;
52 pub use codec::H264Decoder;53 pub use codec::H264Decoder;
53 pub use decoder::{Decoder, NalOutcome, OutputOrder};54 pub use decoder::{Decoder, NalOutcome, OutputOrder};
54 pub use ec_core::error::{Error, Result};55 pub use ec_core::error::{Error, Result};
crates/ec-h264/tests/encode.rsmodified+85 -0
@@ -1100,3 +1100,88 @@ fn bd_psnr_vs_x264() {
1100 );1100 );
1101 }1101 }
1102 }1102 }
1103+
1104+/// Where our bits go against where x264's go, class by class, on the same
1105+/// sources at the same QP. Both streams are parsed by this crate's decoder, so
1106+/// the two accounts are the same measurement; the BD-PSNR gate says how much
1107+/// we overspend, this says on what.
1108+///
1109+/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture
1110+/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1111+/// bit_account_vs_x264 -- --nocapture
1112+#[test]
1113+fn bit_account_vs_x264() {
1114+ if !have_ffmpeg() || !have_x264() {
1115+ eprintln!("SKIP bit_account_vs_x264: no ffmpeg with libx264 on PATH");
1116+ return;
1117+ }
1118+ let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1119+ Some(path) => clip_sources(&path, 12),
1120+ None => {
1121+ let (w, h, frames) = (352, 288, 12);
1122+ let mut clip = Clip::new(w, h);
1123+ let mut sources = Vec::with_capacity(frames);
1124+ for t in 0..frames {
1125+ clip.render_smooth(t);
1126+ sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1127+ }
1128+ eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1129+ (w, h, sources)
1130+ }
1131+ };
1132+ let gop: u32 = 10;
1133+ let account = |stream: &[u8]| {
1134+ let mut dec = Decoder::new();
1135+ dec.set_output_order(OutputOrder::Decode);
1136+ for nal in ec_h264_syntax::AnnexBIter::new(stream) {
1137+ if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1138+ dec.end_picture().expect("end of picture");
1139+ dec.push_nal(nal).expect("decoder accepts the NAL");
1140+ }
1141+ while dec.next_frame().is_some() {}
1142+ }
1143+ dec.flush().expect("flush");
1144+ while dec.next_frame().is_some() {}
1145+ dec.bit_account()
1146+ };
1147+ for qp in [26, 34] {
1148+ let mut cfg = EncoderConfig::new(w as u32, h as u32);
1149+ cfg.qp = qp;
1150+ cfg.gop_size = gop;
1151+ cfg.cabac = true;
1152+ cfg.framerate = 1.0;
1153+ cfg.threads = 0;
1154+ let mut enc = Encoder::new(cfg).expect("encoder");
1155+ let mut ours = Vec::new();
1156+ for (y, u, v) in &sources {
1157+ let view = PictureView::i420(w as u32, h as u32, y, u, v);
1158+ ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
1159+ }
1160+ let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1161+ let (a, b) = (account(&ours), account(&theirs));
1162+ eprintln!(
1163+ "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
1164+ sources.len(),
1165+ ours.len(),
1166+ theirs.len()
1167+ );
1168+ let row = |name: &str, ours: u64, theirs: u64| {
1169+ let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0);
1170+ let delta = if t > 0.0 {
1171+ format!("{:+.1}%", (o - t) / t * 100.0)
1172+ } else {
1173+ "--".to_string()
1174+ };
1175+ eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}");
1176+ };
1177+ row("skip", a.skip, b.skip);
1178+ row("mb_type", a.mb_type, b.mb_type);
1179+ row("mv", a.mv, b.mv);
1180+ row("ref_idx", a.ref_idx, b.ref_idx);
1181+ row("cbp+qp", a.cbp_qp, b.cbp_qp);
1182+ row("intra modes", a.intra_mode, b.intra_mode);
1183+ row("residual luma", a.residual_luma, b.residual_luma);
1184+ row("residual chroma", a.residual_chroma, b.residual_chroma);
1185+ row("total accounted", a.total(), b.total());
1186+ }
1187+}
lanes/h264x264-r2.report.mdmodified+54 -0
@@ -436,3 +436,57 @@ Recorded so the constant is not re-swept a third time: the remaining gap is
436 not an operating-point tilt. It is bits -- we spend 13% more than x264 at436 not an operating-point tilt. It is bits -- we spend 13% more than x264 at
437 0.45 dB higher PSNR on the film clip -- so the places left to look are the437 0.45 dB higher PSNR on the film clip -- so the places left to look are the
438 ones that decide what to spend them on.438 ones that decide what to spend them on.
439+
440+## Where the bits actually go
441+
442+The BD-PSNR gate says how much we overspend. It cannot say on what. So the decoder
443+now counts, per syntax class, the CABAC bits a stream spends: `BitAccount` marks the
444+arithmetic decoder's position (`bit_position() * 256 + range.leading_zeros()`) before
445+and after each syntax element and attributes the difference to one of eight classes.
446+Because the counting lives in the decoder, our stream and x264's stream are measured
447+by the same instrument on the same sources at the same QP -- `bit_account_vs_x264`
448+in `tests/encode.rs` encodes both, decodes both, and prints the table.
449+
450+Twelve consecutive pictures, GOP 10, CABAC, our defaults against the matched x264
451+feature set. Percentages are ours relative to x264.
452+
453+3840x1608 film clip:
454+
455+| class | qp 26 | qp 34 |
456+| --- | --- | --- |
457+| skip | -1.3% | +6.1% |
458+| mb_type | -11.2% | +3.7% |
459+| mv | -14.7% | +14.0% |
460+| cbp+qp | +6.6% | +25.5% |
461+| intra modes | +11.2% | +12.5% |
462+| residual luma | +19.8% | +23.9% |
463+| residual chroma | +7.8% | +6.9% |
464+| total accounted | +10.9% | +13.4% |
465+
466+2560x1440 screen capture:
467+
468+| class | qp 26 | qp 34 |
469+| --- | --- | --- |
470+| skip | -21.9% | -17.4% |
471+| mb_type | -12.2% | +0.8% |
472+| mv | -24.8% | -31.2% |
473+| cbp+qp | +8.4% | +13.0% |
474+| intra modes | +28.9% | +12.6% |
475+| residual luma | +15.4% | +11.0% |
476+| residual chroma | +3.8% | -14.1% |
477+| total accounted | +10.9% | +6.6% |
478+
479+352x288 synthetic, where the gap is largest, reads the same way only louder:
480+residual luma +64.9% at qp 26 and +82.1% at qp 34, mv -20.0% and -25.7%.
481+
482+One shape in all three sources. We spend *less* than x264 on describing motion --
483+fewer skip bits, fewer mb_type bits, fewer mvd bits -- and more on everything that
484+follows from the prediction those choices produce: residual luma first, then the
485+coded-block-pattern and QP deltas that carry it, then the intra modes we fall back
486+to when inter prediction is not good enough. x264 buys a cheaper residual by paying
487+more for the motion field, and comes out ahead on the sum.
488+
489+That is a prediction result, not an entropy-coding one. The residual coder is now
490+priced exactly and quantised against that price; the next thing to look at is what
491+we hand it -- how the motion search chooses, and how the partition and mode decision
492+weighs a more expensive motion field against the residual it saves.