forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

c2b11121f01009438887abca8f2c9ebd5ada480dAhmet Kaan GümüşParent: 83f55a3
crates/ec-h264/src/cabac.rsmodified+14 -210
@@ -107,49 +107,6 @@ pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10];
107 pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20];107 pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20];
108 const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35];108 const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35];
109 109
110-/// Where a slice's bits went, in 1/256ths of a bit, by syntax class. The
111-/// arithmetic decoder spends fractional bits per element, so the sub-bit
112-/// resolution is the point: a class is charged the movement of
113-/// `bit_position * 256 + log2(codIRange)` across its own reads. Both our
114-/// streams and any other encoder's are parsed by this decoder, which is what
115-/// makes the two accounts comparable.
116-#[derive(Clone, Copy, Default, Debug)]
117-pub struct BitAccount {
118- pub skip: u64,
119- pub mb_type: u64,
120- pub mv: u64,
121- pub ref_idx: u64,
122- pub cbp_qp: u64,
123- pub intra_mode: u64,
124- pub residual_luma: u64,
125- pub residual_chroma: u64,
126-}
127-
128-impl BitAccount {
129- /// Every class summed, in 1/256ths of a bit.
130- pub fn total(&self) -> u64 {
131- self.skip
132- + self.mb_type
133- + self.mv
134- + self.ref_idx
135- + self.cbp_qp
136- + self.intra_mode
137- + self.residual_luma
138- + self.residual_chroma
139- }
140-
141- pub(crate) fn add(&mut self, other: &BitAccount) {
142- self.skip += other.skip;
143- self.mb_type += other.mb_type;
144- self.mv += other.mv;
145- self.ref_idx += other.ref_idx;
146- self.cbp_qp += other.cbp_qp;
147- self.intra_mode += other.intra_mode;
148- self.residual_luma += other.residual_luma;
149- self.residual_chroma += other.residual_chroma;
150- }
151-}
152-
153 pub(crate) struct Cabac<'a> {110 pub(crate) struct Cabac<'a> {
154 r: BitCursor<'a>,111 r: BitCursor<'a>,
155 /// codIRange (9.3.3.2).112 /// codIRange (9.3.3.2).
@@ -166,8 +123,6 @@ pub(crate) struct Cabac<'a> {
166 /// The macroblock being parsed is intra coded, which flips the123 /// The macroblock being parsed is intra coded, which flips the
167 /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9).124 /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9).
168 cur_intra: bool,125 cur_intra: bool,
169- /// Bits spent so far, by syntax class.
170- account: BitAccount,
171 }126 }
172 127
173 impl<'a> Cabac<'a> {128 impl<'a> Cabac<'a> {
@@ -195,7 +150,6 @@ impl<'a> Cabac<'a> {
195 ctx: MbCtx::default(),150 ctx: MbCtx::default(),
196 cbp_luma_bins: 0,151 cbp_luma_bins: 0,
197 cur_intra: true,152 cur_intra: true,
198- account: BitAccount::default(),
199 };153 };
200 c.state = init_contexts_full(slice_qp, init_column.min(3));154 c.state = init_contexts_full(slice_qp, init_column.min(3));
201 c.init_engine()?;155 c.init_engine()?;
@@ -293,128 +247,6 @@ impl<'a> Cabac<'a> {
293 247
294 /// Declare whether the macroblock being parsed is intra coded248 /// Declare whether the macroblock being parsed is intra coded
295 /// (9.3.3.1.1.9 reads it for every coded_block_flag).249 /// (9.3.3.1.1.9 reads it for every coded_block_flag).
296- /// The decoder's position in 1/256ths of a bit: the bits already read plus
297- /// what the arithmetic engine's interval says it is holding.
298- fn mark(&self) -> u64 {
299- self.r.bit_position() * 256 + u64::from(self.range.leading_zeros())
300- }
301-
302- pub(crate) fn account(&self) -> BitAccount {
303- self.account
304- }
305-
306- pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
307- let m = self.mark();
308- let out = self.mb_type_i_inner();
309- self.account.mb_type += self.mark() - m;
310- out
311- }
312-
313- pub(crate) fn mb_type_p(&mut self) -> Result<u32> {
314- let m = self.mark();
315- let out = self.mb_type_p_inner();
316- self.account.mb_type += self.mark() - m;
317- out
318- }
319-
320- pub(crate) fn mb_type_b(&mut self) -> Result<u32> {
321- let m = self.mark();
322- let out = self.mb_type_b_inner();
323- self.account.mb_type += self.mark() - m;
324- out
325- }
326-
327- pub(crate) fn sub_mb_type_p(&mut self) -> u32 {
328- let m = self.mark();
329- let out = self.sub_mb_type_p_inner();
330- self.account.mb_type += self.mark() - m;
331- out
332- }
333-
334- pub(crate) fn sub_mb_type_b(&mut self) -> u32 {
335- let m = self.mark();
336- let out = self.sub_mb_type_b_inner();
337- self.account.mb_type += self.mark() - m;
338- out
339- }
340-
341- pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool {
342- let m = self.mark();
343- let out = self.mb_skip_flag_inner(b_slice, inc);
344- self.account.skip += self.mark() - m;
345- out
346- }
347-
348- pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> {
349- let m = self.mark();
350- let out = self.ref_idx_inner(inc);
351- self.account.ref_idx += self.mark() - m;
352- out
353- }
354-
355- pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {
356- let m = self.mark();
357- let out = self.mvd_inner(comp, inc);
358- self.account.mv += self.mark() - m;
359- out
360- }
361-
362- pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
363- let m = self.mark();
364- let out = self.transform_size_8x8_flag_inner();
365- self.account.cbp_qp += self.mark() - m;
366- out
367- }
368-
369- pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> {
370- let m = self.mark();
371- let out = self.coded_block_pattern_inner(has_chroma);
372- self.account.cbp_qp += self.mark() - m;
373- out
374- }
375-
376- pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
377- let m = self.mark();
378- let out = self.mb_qp_delta_inner();
379- self.account.cbp_qp += self.mark() - m;
380- out
381- }
382-
383- pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
384- let m = self.mark();
385- let out = self.intra4x4_pred_mode_inner();
386- self.account.intra_mode += self.mark() - m;
387- out
388- }
389-
390- pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
391- let m = self.mark();
392- let out = self.intra_chroma_pred_mode_inner();
393- self.account.intra_mode += self.mark() - m;
394- out
395- }
396-
397- pub(crate) fn residual_block(
398- &mut self,
399- coeff: &mut [i32; 16],
400- cat: BlockCat,
401- comp: u8,
402- na: Option<u8>,
403- nb: Option<u8>,
404- ) -> Result<u8> {
405- let m = self.mark();
406- let out = self.residual_block_inner(coeff, cat, comp, na, nb);
407- let spent = self.mark() - m;
408- match cat {
409- BlockCat::ChromaDc(_) | BlockCat::ChromaDc422(_) | BlockCat::ChromaAc => {
410- self.account.residual_chroma += spent
411- }
412- _ if comp != 0 => self.account.residual_chroma += spent,
413- _ => self.account.residual_luma += spent,
414- }
415- out
416- }
417-
418 pub(crate) fn set_intra(&mut self, intra: bool) {250 pub(crate) fn set_intra(&mut self, intra: bool) {
419 self.cur_intra = intra;251 self.cur_intra = intra;
420 }252 }
@@ -432,7 +264,7 @@ impl<'a> Cabac<'a> {
432 }264 }
433 265
434 /// mb_type of an I slice (Table 9-36).266 /// mb_type of an I slice (Table 9-36).
435- fn mb_type_i_inner(&mut self) -> Result<u32> {267+ pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
436 let mut ctx = I_MB_TYPE_CTX;268 let mut ctx = I_MB_TYPE_CTX;
437 ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE);269 ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE);
438 self.mb_type_intra(&ctx)270 self.mb_type_intra(&ctx)
@@ -461,14 +293,14 @@ impl<'a> Cabac<'a> {
461 }293 }
462 294
463 /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB.295 /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB.
464- fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool {296+ pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool {
465 let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P };297 let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P };
466 self.decision(off + inc)298 self.decision(off + inc)
467 }299 }
468 300
469 /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice301 /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice
470 /// mb_type for an intra macroblock.302 /// mb_type for an intra macroblock.
471- fn mb_type_p_inner(&mut self) -> Result<u32> {303+ pub(crate) fn mb_type_p(&mut self) -> Result<u32> {
472 if self.decision(OFF_MB_TYPE_P) {304 if self.decision(OFF_MB_TYPE_P) {
473 return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?);305 return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?);
474 }306 }
@@ -485,7 +317,7 @@ impl<'a> Cabac<'a> {
485 317
486 /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice318 /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice
487 /// mb_type for an intra macroblock.319 /// mb_type for an intra macroblock.
488- fn mb_type_b_inner(&mut self) -> Result<u32> {320+ pub(crate) fn mb_type_b(&mut self) -> Result<u32> {
489 if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) {321 if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) {
490 return Ok(0); // B_Direct_16x16322 return Ok(0); // B_Direct_16x16
491 }323 }
@@ -523,7 +355,7 @@ impl<'a> Cabac<'a> {
523 }355 }
524 356
525 /// sub_mb_type of a P macroblock (Table 9-38).357 /// sub_mb_type of a P macroblock (Table 9-38).
526- fn sub_mb_type_p_inner(&mut self) -> u32 {358+ pub(crate) fn sub_mb_type_p(&mut self) -> u32 {
527 if self.decision(OFF_SUB_TYPE_P) {359 if self.decision(OFF_SUB_TYPE_P) {
528 return 0;360 return 0;
529 }361 }
@@ -538,7 +370,7 @@ impl<'a> Cabac<'a> {
538 }370 }
539 371
540 /// sub_mb_type of a B macroblock (Table 9-38).372 /// sub_mb_type of a B macroblock (Table 9-38).
541- fn sub_mb_type_b_inner(&mut self) -> u32 {373+ pub(crate) fn sub_mb_type_b(&mut self) -> u32 {
542 if !self.decision(OFF_SUB_TYPE_B) {374 if !self.decision(OFF_SUB_TYPE_B) {
543 return 0; // B_Direct_8x8375 return 0; // B_Direct_8x8
544 }376 }
@@ -559,7 +391,7 @@ impl<'a> Cabac<'a> {
559 391
560 /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the392 /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the
561 /// first bin (Table 9-39 row 54).393 /// first bin (Table 9-39 row 54).
562- fn ref_idx_inner(&mut self, inc: usize) -> Result<u32> {394+ pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> {
563 if !self.decision(OFF_REF_IDX + inc) {395 if !self.decision(OFF_REF_IDX + inc) {
564 return Ok(0);396 return Ok(0);
565 }397 }
@@ -578,7 +410,7 @@ impl<'a> Cabac<'a> {
578 410
579 /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with411 /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with
580 /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7.412 /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7.
581- fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result<i32> {413+ pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {
582 let off = OFF_MVD[comp];414 let off = OFF_MVD[comp];
583 if !self.decision(off + inc) {415 if !self.decision(off + inc) {
584 return Ok(0);416 return Ok(0);
@@ -603,7 +435,7 @@ impl<'a> Cabac<'a> {
603 435
604 /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is436 /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is
605 /// available and carried the flag itself.437 /// available and carried the flag itself.
606- fn transform_size_8x8_flag_inner(&mut self) -> Result<bool> {438+ pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
607 let cond = |n: Option<MbInfo>| match n {439 let cond = |n: Option<MbInfo>| match n {
608 None => 0,440 None => 0,
609 Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0),441 Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0),
@@ -614,7 +446,7 @@ impl<'a> Cabac<'a> {
614 446
615 /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7447 /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7
616 /// with binIdx 0 the least significant bit.448 /// with binIdx 0 the least significant bit.
617- fn intra4x4_pred_mode_inner(&mut self) -> Result<Option<u8>> {449+ pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
618 if self.decision(OFF_PREV_I4) {450 if self.decision(OFF_PREV_I4) {
619 return Ok(None);451 return Ok(None);
620 }452 }
@@ -626,7 +458,7 @@ impl<'a> Cabac<'a> {
626 }458 }
627 459
628 /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8.460 /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8.
629- fn intra_chroma_pred_mode_inner(&mut self) -> Result<u8> {461+ pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
630 let cond = |n: Option<MbInfo>| match n {462 let cond = |n: Option<MbInfo>| match n {
631 None => 0,463 None => 0,
632 Some(i) => usize::from(464 Some(i) => usize::from(
@@ -649,7 +481,7 @@ impl<'a> Cabac<'a> {
649 481
650 /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma482 /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma
651 /// suffix, both with the neighbour contexts of 9.3.3.1.1.4.483 /// suffix, both with the neighbour contexts of 9.3.3.1.1.4.
652- fn coded_block_pattern_inner(&mut self, has_chroma: bool) -> Result<(u8, u8)> {484+ pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> {
653 let (a_lower, a_blk) = match self.ctx.mbaff_a {485 let (a_lower, a_blk) = match self.ctx.mbaff_a {
654 None => (self.ctx.a, [1u8, 3]),486 None => (self.ctx.a, [1u8, 3]),
655 Some(m) => (m.lower, m.blk),487 Some(m) => (m.lower, m.blk),
@@ -717,7 +549,7 @@ impl<'a> Cabac<'a> {
717 }549 }
718 550
719 /// mb_qp_delta: unary bin string of the Table 9-3 mapped value.551 /// mb_qp_delta: unary bin string of the Table 9-3 mapped value.
720- fn mb_qp_delta_inner(&mut self) -> Result<i32> {552+ pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
721 let mut k = 0i32;553 let mut k = 0i32;
722 while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) {554 while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) {
723 k += 1;555 k += 1;
@@ -729,7 +561,7 @@ impl<'a> Cabac<'a> {
729 }561 }
730 562
731 /// residual_block_cabac (7.3.5.3.3) for one block, in scan order.563 /// residual_block_cabac (7.3.5.3.3) for one block, in scan order.
732- fn residual_block_inner(564+ pub(crate) fn residual_block(
733 &mut self,565 &mut self,
734 coeff: &mut [i32; 16],566 coeff: &mut [i32; 16],
735 cat: BlockCat,567 cat: BlockCat,
@@ -827,22 +659,6 @@ impl<'a> Cabac<'a> {
827 coeff: &mut [i32; 64],659 coeff: &mut [i32; 64],
828 comp: u8,660 comp: u8,
829 cbf: Option<(Option<u8>, Option<u8>)>,661 cbf: Option<(Option<u8>, Option<u8>)>,
830- ) -> Result<u8> {
831- let m = self.mark();
832- let out = self.residual_block_8x8_inner(coeff, comp, cbf);
833- if comp == 0 {
834- self.account.residual_luma += self.mark() - m;
835- } else {
836- self.account.residual_chroma += self.mark() - m;
837- }
838- out
839- }
840-
841- fn residual_block_8x8_inner(
842- &mut self,
843- coeff: &mut [i32; 64],
844- comp: u8,
845- cbf: Option<(Option<u8>, Option<u8>)>,
846 ) -> Result<u8> {662 ) -> Result<u8> {
847 *coeff = [0; 64];663 *coeff = [0; 64];
848 if let Some((na, nb)) = cbf {664 if let Some((na, nb)) = cbf {
@@ -989,18 +805,6 @@ impl<'a> Cabac<'a> {
989 Ok(bytes)805 Ok(bytes)
990 }806 }
991 807
992- /// The raw engine, for the encoder's round-trip test.
993- #[cfg(test)]
994- pub(crate) fn decision_for_test(&mut self, ctx_idx: usize) -> bool {
995- self.decision(ctx_idx)
996- }
997-
998- /// The raw bypass engine, for the encoder's round-trip test.
999- #[cfg(test)]
1000- pub(crate) fn bypass_for_test(&mut self) -> bool {
1001- self.bypass()
1002- }
1003-
1004 /// end_of_slice_flag (ctxIdx 276, DecodeTerminate).808 /// end_of_slice_flag (ctxIdx 276, DecodeTerminate).
1005 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {809 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
1006 debug_assert_eq!(CTX_TERMINATE, 276);810 debug_assert_eq!(CTX_TERMINATE, 276);
crates/ec-h264/src/decoder.rsmodified+1 -101
@@ -29,7 +29,6 @@ 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;
33 use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line};32 use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line};
34 use crate::dpb::{33 use crate::dpb::{
35 BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE,34 BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE,
@@ -141,9 +140,6 @@ pub(crate) struct Core<S: Sample> {
141 last_decoded: i32,140 last_decoded: i32,
142 output_order: OutputOrder,141 output_order: OutputOrder,
143 out: VecDeque<VideoFrame>,142 out: VecDeque<VideoFrame>,
144- /// Bits parsed so far, by syntax class (CABAC slices only).
145- account: BitAccount,
146- shapes: MbShapes,
147 /// Presentation timestamp to attach to the next picture started.143 /// Presentation timestamp to attach to the next picture started.
148 pending_pts: Option<Timestamp>,144 pending_pts: Option<Timestamp>,
149 /// `PicOrderCnt` of the random-access point most recently established by145 /// `PicOrderCnt` of the random-access point most recently established by
@@ -278,25 +274,6 @@ impl Decoder {
278 })274 })
279 }275 }
280 276
281- /// Where the bits of every CABAC slice parsed so far went, by syntax
282- /// class, in 1/256ths of a bit.
283- pub fn bit_account(&self) -> BitAccount {
284- if self.hbd {
285- self.c16.bit_account()
286- } else {
287- self.c8.bit_account()
288- }
289- }
290-
291- /// How many macroblocks of each shape this decoder has read.
292- pub fn mb_shapes(&self) -> MbShapes {
293- if self.hbd {
294- self.c16.mb_shapes()
295- } else {
296- self.c8.mb_shapes()
297- }
298- }
299-
300 /// Decode the first IDR picture of an Annex B stream and return it.277 /// Decode the first IDR picture of an Annex B stream and return it.
301 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {278 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
302 let mut got_slice = false;279 let mut got_slice = false;
@@ -612,8 +589,6 @@ impl<S: Sample> Core<S> {
612 last_decoded: -1,589 last_decoded: -1,
613 output_order: OutputOrder::default(),590 output_order: OutputOrder::default(),
614 out: VecDeque::new(),591 out: VecDeque::new(),
615- account: BitAccount::default(),
616- shapes: MbShapes::default(),
617 pending_pts: None,592 pending_pts: None,
618 recovery_poc: None,593 recovery_poc: None,
619 cur_ref_padded: false,594 cur_ref_padded: false,
@@ -645,20 +620,6 @@ impl<S: Sample> Core<S> {
645 Some((sps.width, sps.height))620 Some((sps.width, sps.height))
646 }621 }
647 622
648- /// Where the bits of every CABAC slice parsed so far went, by syntax
649- /// class, in 1/256ths of a bit. Any conforming stream can be measured
650- /// this way, so an encoder's spending can be compared with another's
651- /// through one account.
652- pub(crate) fn bit_account(&self) -> BitAccount {
653- self.account
654- }
655-
656- /// How many macroblocks of each shape this decoder has read, which is what
657- /// a stream's partitioning looks like from the outside.
658- pub(crate) fn mb_shapes(&self) -> MbShapes {
659- self.shapes
660- }
661-
662 /// Feed one NAL unit (header byte first, no start code).623 /// Feed one NAL unit (header byte first, no start code).
663 pub(crate) fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {624 pub(crate) fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {
664 let Some((&header_byte, payload)) = nal.split_first() else {625 let Some((&header_byte, payload)) = nal.split_first() else {
@@ -1030,7 +991,6 @@ impl<S: Sample> Core<S> {
1030 };991 };
1031 992
1032 let mut ctx = SliceCtx {993 let mut ctx = SliceCtx {
1033- shapes: MbShapes::default(),
1034 slice_id,994 slice_id,
1035 slice_type: sh.slice_type,995 slice_type: sh.slice_type,
1036 qp: sh.slice_qp,996 qp: sh.slice_qp,
@@ -1071,10 +1031,6 @@ impl<S: Sample> Core<S> {
1071 first_mb as usize * 2,1031 first_mb as usize * 2,
1072 pps.entropy_coding_mode,1032 pps.entropy_coding_mode,
1073 )?;1033 )?;
1074- self.shapes.add(&ctx.shapes);
1075- if let Entropy::Cabac(c) = &r {
1076- self.account.add(&c.account());
1077- }
1078 return Ok(NalOutcome::SliceDecoded);1034 return Ok(NalOutcome::SliceDecoded);
1079 }1035 }
1080 let groups = if pps.num_slice_groups > 1 {1036 let groups = if pps.num_slice_groups > 1 {
@@ -1154,10 +1110,6 @@ impl<S: Sample> Core<S> {
1154 more = r.more_macroblocks()?;1110 more = r.more_macroblocks()?;
1155 mb_addr = step(mb_addr);1111 mb_addr = step(mb_addr);
1156 }1112 }
1157- self.shapes.add(&ctx.shapes);
1158- if let Entropy::Cabac(c) = &r {
1159- self.account.add(&c.account());
1160- }
1161 Ok(NalOutcome::SliceDecoded)1113 Ok(NalOutcome::SliceDecoded)
1162 }1114 }
1163 1115
@@ -1606,40 +1558,6 @@ fn check_supported<S: Sample>(
1606 Ok(())1558 Ok(())
1607 }1559 }
1608 1560
1609-/// Mutable per-slice decode state.
1610-/// How many macroblocks of each shape a stream codes: the partitioning the
1611-/// encoder chose, counted from the outside.
1612-///
1613-/// P macroblocks only; a B macroblock's own shapes are not split out.
1614-#[derive(Debug, Default, Clone, Copy)]
1615-pub struct MbShapes {
1616- pub skip: u64,
1617- pub p16x16: u64,
1618- pub p16x8: u64,
1619- pub p8x16: u64,
1620- /// P_8x8 and P_8x8ref0, whatever the sub_mb_types inside are.
1621- pub p8x8: u64,
1622- pub bidir: u64,
1623- pub intra: u64,
1624-}
1625-
1626-impl MbShapes {
1627- /// Add another count into this one.
1628- pub fn add_public(&mut self, o: &MbShapes) {
1629- self.add(o);
1630- }
1631-
1632- pub(crate) fn add(&mut self, o: &MbShapes) {
1633- self.skip += o.skip;
1634- self.p16x16 += o.p16x16;
1635- self.p16x8 += o.p16x8;
1636- self.p8x16 += o.p8x16;
1637- self.p8x8 += o.p8x8;
1638- self.bidir += o.bidir;
1639- self.intra += o.intra;
1640- }
1641-}
1642-
1643 /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value.1561 /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value.
1644 #[derive(Clone, Copy)]1562 #[derive(Clone, Copy)]
1645 struct Geo {1563 struct Geo {
@@ -1663,6 +1581,7 @@ impl Geo {
1663 }1581 }
1664 }1582 }
1665 1583
1584+/// Mutable per-slice decode state.
1666 pub(crate) struct SliceCtx {1585 pub(crate) struct SliceCtx {
1667 slice_id: u16,1586 slice_id: u16,
1668 slice_type: SliceType,1587 slice_type: SliceType,
@@ -1699,8 +1618,6 @@ pub(crate) struct SliceCtx {
1699 /// Where the macroblock being decoded sits when the picture is an MBAFF1618 /// Where the macroblock being decoded sits when the picture is an MBAFF
1700 /// frame (`pos.active`); inert otherwise.1619 /// frame (`pos.active`); inert otherwise.
1701 pos: MbPos,1620 pos: MbPos,
1702- /// How many macroblocks of each shape this slice decoded.
1703- shapes: MbShapes,
1704 }1621 }
1705 1622
1706 impl SliceCtx {1623 impl SliceCtx {
@@ -2241,22 +2158,6 @@ fn decode_macroblock<S: Sample>(
2241 r.mb_type_i()?2158 r.mb_type_i()?
2242 };2159 };
2243 2160
2244- if skipped {
2245- ctx.shapes.skip += 1;
2246- } else if ctx.slice_type == SliceType::P {
2247- match mb_type {
2248- 0 => ctx.shapes.p16x16 += 1,
2249- 1 => ctx.shapes.p16x8 += 1,
2250- 2 => ctx.shapes.p8x16 += 1,
2251- 3 | 4 => ctx.shapes.p8x8 += 1,
2252- _ => ctx.shapes.intra += 1,
2253- }
2254- } else if ctx.is_b() {
2255- ctx.shapes.bidir += 1;
2256- } else {
2257- ctx.shapes.intra += 1;
2258- }
2259-
2260 // Split the P/B numbering into an inter shape or an intra mb_type.2161 // Split the P/B numbering into an inter shape or an intra mb_type.
2261 let (shape, intra_type) = if skipped {2162 let (shape, intra_type) = if skipped {
2262 let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] };2163 let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] };
@@ -5006,7 +4907,6 @@ mod tests {
5006 }),4907 }),
5007 poc: 4,4908 poc: 4,
5008 fpoc: [4, 4],4909 fpoc: [4, 4],
5009- shapes: MbShapes::default(),
5010 };4910 };
5011 let mut pic = ramp_picture(|_, _| 0);4911 let mut pic = ramp_picture(|_, _| 0);
5012 4912
crates/ec-h264/src/enc/cabac_enc.rsmodified+0 -38
@@ -730,44 +730,6 @@ mod tests {
730 use super::*;730 use super::*;
731 use crate::cabac::Cabac;731 use crate::cabac::Cabac;
732 732
733- /// The engine round-trips: a pseudo-random bin string written against a
734- /// spread of contexts, with bypass and terminate bins mixed in, decodes
735- /// back identically. This is the property every syntax element rests on.
736- #[test]
737- fn engine_round_trips() {
738- let mut state = 0x2545_F491u32;
739- let mut rand = move |m: u32| {
740- state ^= state << 13;
741- state ^= state >> 17;
742- state ^= state << 5;
743- state % m
744- };
745- let mut plan: Vec<(usize, bool, u8)> = Vec::new(); // (ctx, bin, kind)
746- for _ in 0..4000 {
747- let kind = if rand(10) == 0 { 1 } else { 0 };
748- plan.push((rand(NUM_CTX as u32) as usize, rand(2) == 1, kind));
749- }
750- let mut enc = CabacEnc::new(BitWriter::new(), 26, 0);
751- for &(ctx, bin, kind) in &plan {
752- match kind {
753- 0 => enc.decision(ctx, bin),
754- _ => enc.bypass(bin),
755- }
756- enc.not_end_of_slice();
757- }
758- let bytes = enc.finish().into_bytes();
759-
760- let mut dec = Cabac::new(&bytes, 0, 26, 0).expect("decoder starts");
761- for (i, &(ctx, bin, kind)) in plan.iter().enumerate() {
762- let got = match kind {
763- 0 => dec.decision_for_test(ctx),
764- _ => dec.bypass_for_test(),
765- };
766- assert_eq!(got, bin, "bin {i}");
767- assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end");
768- }
769- }
770-
771 /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat733 /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat
772 /// 5 blocks over a spread of densities and magnitudes all decode back734 /// 5 blocks over a spread of densities and magnitudes all decode back
773 /// through the decoder's own syntax readers.735 /// through the decoder's own syntax readers.
crates/ec-h264/src/lib.rsmodified+1 -2
@@ -57,8 +57,7 @@ mod sample;
57 mod tables;57 mod tables;
58 mod transform;58 mod transform;
59 59
60-pub use cabac::BitAccount;
61 pub use codec::H264Decoder;60 pub use codec::H264Decoder;
62-pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder};61+pub use decoder::{Decoder, NalOutcome, OutputOrder};
63 pub use ec_core::error::{Error, Result};62 pub use ec_core::error::{Error, Result};
64 pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset};63 pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset};
crates/ec-h264/tests/it/encode.rsmodified+0 -114
@@ -1385,99 +1385,6 @@ fn bd_psnr_vs_x264() {
1385 }1385 }
1386 }1386 }
1387 1387
1388-/// Where our bits go against where x264's go, class by class, on the same
1389-/// sources at the same QP. Both streams are parsed by this crate's decoder, so
1390-/// the two accounts are the same measurement; the BD-PSNR gate says how much
1391-/// we overspend, this says on what.
1392-///
1393-/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture
1394-/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1395-/// bit_account_vs_x264 -- --nocapture
1396-#[test]
1397-fn bit_account_vs_x264() {
1398- assert!(have_x264(), "the pinned ffmpeg has no libx264");
1399- let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1400- Some(path) => clip_sources(&path, 12),
1401- None => {
1402- let (w, h, frames) = (352, 288, 12);
1403- let mut clip = Clip::new(w, h);
1404- let mut sources = Vec::with_capacity(frames);
1405- for t in 0..frames {
1406- clip.render_smooth(t);
1407- sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1408- }
1409- eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1410- (w, h, sources)
1411- }
1412- };
1413- let gop: u32 = 10;
1414- let account = |stream: &[u8]| {
1415- let mut dec = Decoder::new();
1416- dec.set_output_order(OutputOrder::Decode);
1417- for nal in ec_h264_syntax::AnnexBIter::new(stream) {
1418- if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1419- dec.end_picture().expect("end of picture");
1420- dec.push_nal(nal).expect("decoder accepts the NAL");
1421- }
1422- while dec.next_frame().is_some() {}
1423- }
1424- dec.flush().expect("flush");
1425- while dec.next_frame().is_some() {}
1426- (dec.bit_account(), dec.mb_shapes())
1427- };
1428- for qp in [26, 34] {
1429- let mut cfg = EncoderConfig::new(w as u32, h as u32);
1430- cfg.qp = qp;
1431- cfg.gop_size = gop;
1432- cfg.cabac = true;
1433- cfg.framerate = 1.0;
1434- cfg.threads = 0;
1435- if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1436- cfg.preset = ec_h264::Preset::Balanced;
1437- }
1438- let mut enc = Encoder::new(cfg).expect("encoder");
1439- let mut ours = Vec::new();
1440- for (y, u, v) in &sources {
1441- let view = PictureView::i420(w as u32, h as u32, y, u, v);
1442- ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
1443- }
1444- let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1445- let ((a, sa), (b, sb)) = (account(&ours), account(&theirs));
1446- eprintln!(
1447- "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
1448- sources.len(),
1449- ours.len(),
1450- theirs.len()
1451- );
1452- let row = |name: &str, ours: u64, theirs: u64| {
1453- let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0);
1454- let delta = if t > 0.0 {
1455- format!("{:+.1}%", (o - t) / t * 100.0)
1456- } else {
1457- "--".to_string()
1458- };
1459- eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}");
1460- };
1461- row("skip", a.skip, b.skip);
1462- row("mb_type", a.mb_type, b.mb_type);
1463- row("mv", a.mv, b.mv);
1464- row("ref_idx", a.ref_idx, b.ref_idx);
1465- row("cbp+qp", a.cbp_qp, b.cbp_qp);
1466- row("intra modes", a.intra_mode, b.intra_mode);
1467- row("residual luma", a.residual_luma, b.residual_luma);
1468- row("residual chroma", a.residual_chroma, b.residual_chroma);
1469- row("total accounted", a.total(), b.total());
1470- let mix = |n: &str, s: &ec_h264::MbShapes| {
1471- eprintln!(
1472- " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1473- s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra
1474- );
1475- };
1476- mix("shapes ours", &sa);
1477- mix("shapes x264", &sb);
1478- }
1479-}
1480-
1481 /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg.1388 /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg.
1482 ///1389 ///
1483 /// The default preset codes every P macroblock as one 16x16 partition, so the1390 /// The default preset codes every P macroblock as one 16x16 partition, so the
@@ -1486,7 +1393,6 @@ fn bit_account_vs_x264() {
1486 #[test]1393 #[test]
1487 fn balanced_partitions_decode_bit_exactly() {1394 fn balanced_partitions_decode_bit_exactly() {
1488 let (w, h) = (176, 144);1395 let (w, h) = (176, 144);
1489- let mut shapes = ec_h264::MbShapes::default();
1490 for qp in [16, 26, 36] {1396 for qp in [16, 26, 36] {
1491 let cavlc = qp == 26; // both entropy coders write sub_mb_type1397 let cavlc = qp == 26; // both entropy coders write sub_mb_type
1492 let (stream, recons, _) = encode_clip(w, h, 8, |cfg| {1398 let (stream, recons, _) = encode_clip(w, h, 8, |cfg| {
@@ -1501,27 +1407,7 @@ fn balanced_partitions_decode_bit_exactly() {
1501 assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}");1407 assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}");
1502 assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}");1408 assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}");
1503 }1409 }
1504- let mut dec = Decoder::new();
1505- dec.set_output_order(OutputOrder::Decode);
1506- for nal in ec_h264_syntax::AnnexBIter::new(&stream) {
1507- if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1508- dec.end_picture().expect("end of picture");
1509- dec.push_nal(nal).expect("decoder accepts the NAL");
1510- }
1511- while dec.next_frame().is_some() {}
1512- }
1513- dec.flush().expect("flush");
1514- while dec.next_frame().is_some() {}
1515- shapes.add_public(&dec.mb_shapes());
1516 }1410 }
1517- eprintln!(
1518- "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1519- shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra
1520- );
1521- assert!(
1522- shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0,
1523- "the sweep has to code every shape, or it proves nothing about them"
1524- );
1525 }1411 }
1526 1412
1527 #[test]1413 #[test]