forge
Explore
Log in

Don't you dare go Hollow

CABAC entropy decoding for I slices

Browse files at this commit

7cdaf348ac7949adecef7fbf02c17dfb801844cdAhmet Kaan GümüşParent: 6480b8e
  • feat
    • CABAC entropy decoding for I slices
Show full message
feat(h264): CABAC entropy decoding for I slices

Clause 9.3, transcribed from Rec. ITU-T H.264 (V15):

- arithmetic decoding engine (9.3.3.2) with the spec's exact integer steps —
  DecodeDecision over rangeTabLPS, DecodeBypass, DecodeTerminate, RenormD;
- context variable initialisation (9.3.1.1) from SliceQPY, and the engine
  restart after I_PCM samples (9.3.1.2);
- binarizations: the I-slice mb_type tree (Table 9-36), TU, FL and the UEG0
  suffix of coeff_abs_level_minus1 (9.3.2.1 to 9.3.2.7);
- context selection including the neighbour-derived increments of 9.3.3.1.1
  for mb_type, intra_chroma_pred_mode, coded_block_pattern, mb_qp_delta and
  coded_block_flag, plus the significance-map positions of 9.3.3.1.3;
- the CABAC slice-data loop: cabac_alignment_one_bit, then a macroblock and an
  end_of_slice_flag per iteration.

The picture state grows the two neighbour facts CABAC needs and CAVLC did not:
the coded block pattern per macroblock, and the DC coded_block_flags. The
macroblock loop is otherwise untouched — parse and reconstruction stay fused.

Only the values an I slice of a frame-coded 4:2:0 8-bit stream reads are
transcribed. The cabac_init_idc columns, the field-coded significance
contexts and the 8x8 transform block categories belong to slices this decoder
still refuses by name; a later release adds them against its own oracle rather
than shipping numbers no test can reach. Inter slices under CABAC keep the
existing inter-slice refusal, and transform_size_8x8_flag is now refused as a
decoded bin rather than a raw one.
crates/ec-h264/src/cabac.rsadded+559 -0
@@ -0,0 +1,559 @@
1+//! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine,
2+//! context variables, binarizations and context selection.
3+//!
4+//! Scope is what an I slice of a frame-coded 4:2:0 8-bit stream needs; every
5+//! other tool the decoder refuses by name before reaching this module, so the
6+//! contexts, block categories and initialisation columns that only P, B, field
7+//! or 8x8-transform coding reads are absent rather than transcribed untested.
8+//!
9+//! The engine keeps codIRange and codIOffset in `u32` with the spec's exact
10+//! integer steps — no probability floats, no shortcuts — and reads its bits
11+//! from the same [`BitCursor`] the CAVLC path uses. Past the end of the RBSP the
12+//! cursor is treated as zero-filled: a conformant stream never depends on those
13+//! bits (the last one read is the rbsp_stop_one_bit), and the macroblock loop,
14+//! not the bit supply, is what bounds a truncated one.
15+
16+use ec_core::error::{Error, Result};
17+
18+use crate::bits::BitCursor;
19+use crate::cabac_tables::{
20+ INIT_60_69, INIT_70_275, INIT_399_401, INIT_MB_TYPE_I, RANGE_LPS, TRANS_LPS, TRANS_MPS,
21+};
22+use crate::entropy::{BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo};
23+
24+/// Highest ctxIdx this decoder can address, plus one (399..401 is the
25+/// transform_size_8x8_flag block, the last range an I slice can reach).
26+const NUM_CTX: usize = 402;
27+
28+/// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by
29+/// DecodeTerminate and has no adapting state.
30+const CTX_TERMINATE: usize = 276;
31+
32+/// Table 9-40, `ctxIdxBlockCatOffset` for the five 4:2:0 block categories.
33+const CBF_CAT_OFF: [usize; 5] = [0, 4, 8, 12, 16];
34+const SIG_CAT_OFF: [usize; 5] = [0, 15, 29, 44, 47];
35+const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39];
36+
37+/// ctxIdxOffset values of Table 9-34 used here.
38+const OFF_MB_TYPE: usize = 3;
39+const OFF_QP_DELTA: usize = 60;
40+const OFF_CHROMA_PRED: usize = 64;
41+const OFF_PREV_I4: usize = 68;
42+const OFF_REM_I4: usize = 69;
43+const OFF_CBP_LUMA: usize = 73;
44+const OFF_CBP_CHROMA: usize = 77;
45+const OFF_CBF: usize = 85;
46+const OFF_SIG: usize = 105;
47+const OFF_LAST: usize = 166;
48+const OFF_ABS: usize = 227;
49+const OFF_TRANSFORM_8X8: usize = 399;
50+
51+pub(crate) struct Cabac<'a> {
52+ r: BitCursor<'a>,
53+ /// codIRange (9.3.3.2).
54+ range: u32,
55+ /// codIOffset (9.3.3.2).
56+ offset: u32,
57+ /// Context variables: `pStateIdx << 1 | valMPS`, indexed by ctxIdx.
58+ state: [u8; NUM_CTX],
59+ /// Neighbourhood of the macroblock being parsed.
60+ ctx: MbCtx,
61+ /// CodedBlockPatternLuma bins decoded so far in this macroblock, for the
62+ /// within-macroblock neighbours of clause 9.3.3.1.1.4.
63+ cbp_luma_bins: u8,
64+}
65+
66+impl<'a> Cabac<'a> {
67+ /// Start CABAC parsing at `header_bits`: `cabac_alignment_one_bit`s, then
68+ /// the context and engine initialisation of clause 9.3.1.
69+ pub(crate) fn new(rbsp: &'a [u8], header_bits: u64, slice_qp: i32) -> Result<Cabac<'a>> {
70+ let mut r = BitCursor::new(rbsp, header_bits);
71+ // cabac_alignment_one_bit (7.3.4): the stuffing bits are all 1, which
72+ // a corrupt-stream check would only duplicate; skipping to the byte
73+ // boundary is the whole effect.
74+ r.align_to_byte();
75+ let mut c = Cabac {
76+ r,
77+ range: 510,
78+ offset: 0,
79+ state: [63 << 1; NUM_CTX],
80+ ctx: MbCtx::default(),
81+ cbp_luma_bins: 0,
82+ };
83+ c.init_contexts(slice_qp);
84+ c.init_engine()?;
85+ Ok(c)
86+ }
87+
88+ /// 9.3.1.1: pStateIdx and valMPS from the (m, n) table entries and SliceQPY.
89+ fn init_contexts(&mut self, slice_qp: i32) {
90+ let qp = slice_qp.clamp(0, 51);
91+ let set = |state: &mut [u8; NUM_CTX], idx: usize, (m, n): (i8, i8)| {
92+ let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126);
93+ state[idx] = if pre <= 63 {
94+ ((63 - pre) as u8) << 1
95+ } else {
96+ (((pre - 64) as u8) << 1) | 1
97+ };
98+ };
99+ for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() {
100+ set(&mut self.state, i, mn);
101+ }
102+ for (i, &mn) in INIT_60_69.iter().enumerate() {
103+ set(&mut self.state, 60 + i, mn);
104+ }
105+ for (i, &mn) in INIT_70_275.iter().enumerate() {
106+ set(&mut self.state, 70 + i, mn);
107+ }
108+ for (i, &mn) in INIT_399_401.iter().enumerate() {
109+ set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn);
110+ }
111+ }
112+
113+ /// 9.3.1.2: codIRange = 510, codIOffset = read_bits(9).
114+ fn init_engine(&mut self) -> Result<()> {
115+ self.range = 510;
116+ self.offset = self.r.read_bits(9)?;
117+ if self.offset >= 510 {
118+ return Err(Error::corrupt("CABAC codIOffset initialised to 510 or 511"));
119+ }
120+ Ok(())
121+ }
122+
123+ /// One bit of slice data; zero past the end (see the module note).
124+ #[inline]
125+ fn bit(&mut self) -> u32 {
126+ u32::from(self.r.read_bit().unwrap_or(false))
127+ }
128+
129+ /// 9.3.3.2.2 RenormD.
130+ #[inline]
131+ fn renorm(&mut self) {
132+ while self.range < 256 {
133+ self.range <<= 1;
134+ self.offset = (self.offset << 1) | self.bit();
135+ }
136+ }
137+
138+ /// 9.3.3.2.1 DecodeDecision, with the state transition of 9.3.3.2.1.1.
139+ #[inline]
140+ fn decision(&mut self, ctx_idx: usize) -> bool {
141+ let s = self.state[ctx_idx];
142+ let p = usize::from(s >> 1);
143+ let mps = s & 1;
144+ let lps = u32::from(RANGE_LPS[p][((self.range >> 6) & 3) as usize]);
145+ self.range -= lps;
146+ let bin;
147+ if self.offset >= self.range {
148+ bin = mps ^ 1;
149+ self.offset -= self.range;
150+ self.range = lps;
151+ // Crossing state 0 swaps the most probable symbol.
152+ let mps = if p == 0 { mps ^ 1 } else { mps };
153+ self.state[ctx_idx] = (TRANS_LPS[p] << 1) | mps;
154+ } else {
155+ bin = mps;
156+ self.state[ctx_idx] = (TRANS_MPS[p] << 1) | mps;
157+ }
158+ self.renorm();
159+ bin != 0
160+ }
161+
162+ /// 9.3.3.2.3 DecodeBypass.
163+ #[inline]
164+ fn bypass(&mut self) -> bool {
165+ self.offset = (self.offset << 1) | self.bit();
166+ if self.offset >= self.range {
167+ self.offset -= self.range;
168+ true
169+ } else {
170+ false
171+ }
172+ }
173+
174+ /// 9.3.3.2.4 DecodeTerminate.
175+ #[inline]
176+ fn terminate(&mut self) -> bool {
177+ self.range -= 2;
178+ if self.offset >= self.range {
179+ true
180+ } else {
181+ self.renorm();
182+ false
183+ }
184+ }
185+
186+ pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) {
187+ self.ctx = *ctx;
188+ self.cbp_luma_bins = 0;
189+ }
190+
191+ /// 9.3.3.1.1.3: condTermFlagA + condTermFlagB for mb_type in an I slice,
192+ /// where a neighbour counts unless it is I_NxN.
193+ fn mb_type_inc(&self) -> usize {
194+ let cond = |n: Option<MbInfo>| match n {
195+ None => 0,
196+ Some(i) => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0),
197+ };
198+ cond(self.ctx.a) + cond(self.ctx.b)
199+ }
200+
201+ /// mb_type of an I slice (Table 9-36).
202+ pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
203+ if !self.decision(OFF_MB_TYPE + self.mb_type_inc()) {
204+ return Ok(0); // I_NxN
205+ }
206+ if self.terminate() {
207+ return Ok(25); // I_PCM
208+ }
209+ // b2: CodedBlockPatternLuma 0 or 15; b3 (+ b4): CodedBlockPatternChroma;
210+ // last two bins: Intra_16x16PredMode. The two prediction-mode bins keep
211+ // ctxIdx 9 and 10 either way (Table 9-39 row 3 with Table 9-41).
212+ let cbp_luma = u32::from(self.decision(OFF_MB_TYPE + 3));
213+ let chroma = if !self.decision(OFF_MB_TYPE + 4) {
214+ 0
215+ } else if self.decision(OFF_MB_TYPE + 5) {
216+ 2
217+ } else {
218+ 1
219+ };
220+ let mode = u32::from(self.decision(OFF_MB_TYPE + 6)) * 2
221+ + u32::from(self.decision(OFF_MB_TYPE + 7));
222+ Ok(1 + mode + chroma * 4 + cbp_luma * 12)
223+ }
224+
225+ /// transform_size_8x8_flag (9.3.3.1.1.10).
226+ pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
227+ // No neighbour can carry the flag: a macroblock that set it is refused
228+ // before its state is ever stored, so ctxIdxInc is always 0 here.
229+ Ok(self.decision(OFF_TRANSFORM_8X8))
230+ }
231+
232+ /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7
233+ /// with binIdx 0 the least significant bit.
234+ pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
235+ if self.decision(OFF_PREV_I4) {
236+ return Ok(None);
237+ }
238+ let mut rem = 0u8;
239+ for bit in 0..3 {
240+ rem |= u8::from(self.decision(OFF_REM_I4)) << bit;
241+ }
242+ Ok(Some(rem))
243+ }
244+
245+ /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8.
246+ pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
247+ let cond = |n: Option<MbInfo>| match n {
248+ None => 0,
249+ Some(i) => usize::from(i.flags & FLAG_PCM == 0 && i.flags & FLAG_CHROMA_PRED != 0),
250+ };
251+ let inc = cond(self.ctx.a) + cond(self.ctx.b);
252+ if !self.decision(OFF_CHROMA_PRED + inc) {
253+ return Ok(0);
254+ }
255+ if !self.decision(OFF_CHROMA_PRED + 3) {
256+ return Ok(1);
257+ }
258+ Ok(if self.decision(OFF_CHROMA_PRED + 3) {
259+ 3
260+ } else {
261+ 2
262+ })
263+ }
264+
265+ /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma
266+ /// suffix, both with the neighbour contexts of 9.3.3.1.1.4.
267+ pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> {
268+ for bin in 0..4u8 {
269+ // 6.4.11.2: the 8x8 block left of / above block `bin`, which for
270+ // blocks 1, 2 and 3 can be inside this macroblock.
271+ let (a, b) = match bin {
272+ 0 => (
273+ self.cbp_luma_neighbour(self.ctx.a, 1),
274+ self.cbp_luma_neighbour(self.ctx.b, 2),
275+ ),
276+ 1 => (self.cbp_luma_own(0), self.cbp_luma_neighbour(self.ctx.b, 3)),
277+ 2 => (self.cbp_luma_neighbour(self.ctx.a, 3), self.cbp_luma_own(0)),
278+ _ => (self.cbp_luma_own(2), self.cbp_luma_own(1)),
279+ };
280+ if self.decision(OFF_CBP_LUMA + a + 2 * b) {
281+ self.cbp_luma_bins |= 1 << bin;
282+ }
283+ }
284+ let luma = self.cbp_luma_bins;
285+ let chroma_cond = |n: Option<MbInfo>, bin: u8| match n {
286+ None => 0,
287+ Some(i) if i.flags & FLAG_PCM != 0 => 1,
288+ Some(i) => {
289+ let c = i.cbp >> 4;
290+ usize::from(if bin == 0 { c != 0 } else { c == 2 })
291+ }
292+ };
293+ let inc0 = chroma_cond(self.ctx.a, 0) + 2 * chroma_cond(self.ctx.b, 0);
294+ let chroma = if !self.decision(OFF_CBP_CHROMA + inc0) {
295+ 0
296+ } else {
297+ let inc1 = chroma_cond(self.ctx.a, 1) + 2 * chroma_cond(self.ctx.b, 1) + 4;
298+ if self.decision(OFF_CBP_CHROMA + inc1) {
299+ 2
300+ } else {
301+ 1
302+ }
303+ };
304+ Ok((luma, chroma))
305+ }
306+
307+ /// condTermFlagN for a coded_block_pattern luma bin whose neighbouring 8x8
308+ /// block lies in another macroblock: set when that block has no coefficients.
309+ fn cbp_luma_neighbour(&self, n: Option<MbInfo>, blk: u8) -> usize {
310+ match n {
311+ None => 0,
312+ Some(i) if i.flags & FLAG_PCM != 0 => 0,
313+ Some(i) => usize::from(i.cbp & (1 << blk) == 0),
314+ }
315+ }
316+
317+ /// The same for a neighbouring 8x8 block inside this macroblock, read from
318+ /// the bins already decoded.
319+ fn cbp_luma_own(&self, blk: u8) -> usize {
320+ usize::from(self.cbp_luma_bins & (1 << blk) == 0)
321+ }
322+
323+ /// mb_qp_delta: unary bin string of the Table 9-3 mapped value.
324+ pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
325+ let mut k = 0i32;
326+ while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) {
327+ k += 1;
328+ if k > 52 {
329+ return Err(Error::corrupt("mb_qp_delta bin string too long"));
330+ }
331+ }
332+ Ok(if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) })
333+ }
334+
335+ /// residual_block_cabac (7.3.5.3.3) for one block, in scan order.
336+ pub(crate) fn residual_block(
337+ &mut self,
338+ coeff: &mut [i32; 16],
339+ cat: BlockCat,
340+ na: Option<u8>,
341+ nb: Option<u8>,
342+ ) -> Result<u8> {
343+ *coeff = [0; 16];
344+ let cat_i = cat.ctx_block_cat();
345+ let max = cat.max_num_coeff();
346+
347+ // coded_block_flag (9.3.3.1.1.9). An unavailable neighbour counts as
348+ // set, because every macroblock of an I slice is intra coded; the
349+ // caller has already folded I_PCM (all coefficients present) into a
350+ // non-zero count.
351+ let cond = |n: Option<u8>| usize::from(n.is_none_or(|v| v != 0));
352+ let (a, b) = match cat {
353+ // The DC blocks' neighbours are per macroblock, not per 4x4 block.
354+ BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)),
355+ BlockCat::ChromaDc(c) => (
356+ self.dc_cbf(self.ctx.a, 1 + c),
357+ self.dc_cbf(self.ctx.b, 1 + c),
358+ ),
359+ _ => (cond(na), cond(nb)),
360+ };
361+ if !self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b) {
362+ return Ok(0);
363+ }
364+
365+ // Significance map: significant_coeff_flag / last_significant_coeff_flag
366+ // over scanning positions 0..maxNumCoeff-1.
367+ let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i];
368+ let last_base = OFF_LAST + SIG_CAT_OFF[cat_i];
369+ let mut sig = [false; 16];
370+ let mut num = max;
371+ let mut i = 0;
372+ while i + 1 < num {
373+ let inc = sig_inc(cat, i);
374+ if self.decision(sig_base + inc) {
375+ sig[i] = true;
376+ if self.decision(last_base + inc) {
377+ num = i + 1;
378+ }
379+ }
380+ i += 1;
381+ }
382+ sig[num - 1] = true;
383+
384+ // Levels, highest scanning position first (9.3.3.1.3 counters).
385+ let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i];
386+ let mut num_eq1 = 0u32;
387+ let mut num_gt1 = 0u32;
388+ let mut total = 0u8;
389+ for pos in (0..num).rev() {
390+ if !sig[pos] {
391+ continue;
392+ }
393+ let inc0 = if num_gt1 != 0 {
394+ 0
395+ } else {
396+ 4.min(1 + num_eq1) as usize
397+ };
398+ let inc1 = 5 + (4 - u32::from(cat_i == 3)).min(num_gt1) as usize;
399+ // Prefix: TU with cMax = uCoff = 14.
400+ let mut prefix = 0u32;
401+ while prefix < 14 {
402+ let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };
403+ if !self.decision(ctx_idx) {
404+ break;
405+ }
406+ prefix += 1;
407+ }
408+ let abs_minus1 = if prefix < 14 {
409+ prefix
410+ } else {
411+ 14 + self.ueg0_suffix()?
412+ };
413+ let level = i64::from(abs_minus1) + 1;
414+ let level = if self.bypass() { -level } else { level };
415+ coeff[pos] = i32::try_from(level)
416+ .map_err(|_| Error::corrupt("coefficient level out of range"))?;
417+ if abs_minus1 == 0 {
418+ num_eq1 += 1;
419+ } else {
420+ num_gt1 += 1;
421+ }
422+ total += 1;
423+ }
424+ Ok(total)
425+ }
426+
427+ /// The bypass-coded 0th order Exp-Golomb suffix of a UEG0 bin string (9-6).
428+ fn ueg0_suffix(&mut self) -> Result<u32> {
429+ let mut k = 0u32;
430+ let mut value = 0u32;
431+ while self.bypass() {
432+ value += 1 << k;
433+ k += 1;
434+ if k > 30 {
435+ return Err(Error::corrupt("UEG0 suffix prefix too long"));
436+ }
437+ }
438+ while k > 0 {
439+ k -= 1;
440+ value += u32::from(self.bypass()) << k;
441+ }
442+ Ok(value)
443+ }
444+
445+ /// condTermFlagN for a DC block: bit `which` of the neighbour's DC
446+ /// coded_block_flags, with I_PCM counting as coded and an unavailable
447+ /// neighbour as set (the current macroblock is always intra here).
448+ fn dc_cbf(&self, n: Option<MbInfo>, which: u8) -> usize {
449+ match n {
450+ None => 1,
451+ Some(i) if i.flags & FLAG_PCM != 0 => 1,
452+ Some(i) => usize::from(i.dc_cbf & (1 << which) != 0),
453+ }
454+ }
455+
456+ /// The 384 raw bytes of an I_PCM macroblock. The arithmetic engine restarts
457+ /// afterwards (9.3.1.2); the context variables survive.
458+ pub(crate) fn pcm_block(&mut self) -> Result<&'a [u8]> {
459+ self.r.align_to_byte();
460+ let bytes = self.r.read_bytes(384)?;
461+ self.init_engine()?;
462+ Ok(bytes)
463+ }
464+
465+ /// end_of_slice_flag (ctxIdx 276, DecodeTerminate).
466+ pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
467+ debug_assert_eq!(CTX_TERMINATE, 276);
468+ Ok(!self.terminate())
469+ }
470+}
471+
472+/// ctxIdxInc for mb_qp_delta bin `k` (Table 9-39 row 60).
473+#[inline]
474+fn qp_delta_inc(k: i32, first: usize) -> usize {
475+ match k {
476+ 0 => first,
477+ 1 => 2,
478+ _ => 3,
479+ }
480+}
481+
482+/// ctxIdxInc for significant_coeff_flag / last_significant_coeff_flag at
483+/// scanning position `i` (9.3.3.1.3, frame coded, no 8x8 categories).
484+#[inline]
485+fn sig_inc(cat: BlockCat, i: usize) -> usize {
486+ match cat {
487+ // ChromaDC with ChromaArrayType 1: Min( levelListIdx / NumC8x8, 2 ).
488+ BlockCat::ChromaDc(_) => i.min(2),
489+ _ => i,
490+ }
491+}
492+
493+#[cfg(test)]
494+mod tests {
495+ use super::*;
496+
497+ /// The engine tables are transcribed by hand-checked script; these are the
498+ /// structural invariants clause 9.3 states about them, so a shifted row or
499+ /// a dropped column cannot pass silently.
500+ #[test]
501+ fn engine_tables_have_their_stated_shape() {
502+ // Table 9-44 first and last rows (9.3.3.2.1): state 0 is p(LPS) = 0.5,
503+ // state 63 is the near-deterministic one.
504+ assert_eq!(RANGE_LPS[0], [128, 176, 208, 240]);
505+ assert_eq!(RANGE_LPS[63], [2, 2, 2, 2]);
506+ for (p, row) in RANGE_LPS.iter().enumerate() {
507+ // Each row rises with qCodIRangeIdx and falls with the state index.
508+ assert!(
509+ row.windows(2).all(|w| w[0] <= w[1]),
510+ "row {p} not monotonic"
511+ );
512+ if p > 0 {
513+ assert!(
514+ row[3] <= RANGE_LPS[p - 1][3],
515+ "row {p} above its predecessor"
516+ );
517+ }
518+ }
519+ // Table 9-45: MPS transitions step up one state until the two sticky
520+ // states at the top, LPS transitions never move up.
521+ for (p, &next) in TRANS_MPS.iter().enumerate().take(62) {
522+ assert_eq!(next, p as u8 + 1);
523+ }
524+ assert_eq!((TRANS_MPS[62], TRANS_MPS[63]), (62, 63));
525+ for (p, &next) in TRANS_LPS.iter().enumerate() {
526+ assert!(usize::from(next) <= p, "LPS transition {p} moves up");
527+ }
528+ assert_eq!(TRANS_LPS[63], 63);
529+ assert_eq!(TRANS_LPS[0], 0);
530+ }
531+
532+ /// 9.3.1.1 worked through by hand for two entries.
533+ #[test]
534+ fn context_initialisation_matches_equation_9_5() {
535+ let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 26).unwrap();
536+ // ctxIdx 0, (m, n) = (20, -15): preCtxState = ((20*26) >> 4) - 15 = 17,
537+ // so pStateIdx = 63 - 17 = 46 and valMPS = 0.
538+ assert_eq!(c.state[0], 46 << 1);
539+ // ctxIdx 60, (m, n) = (0, 41): preCtxState = 41 -> pStateIdx 22, MPS 0.
540+ assert_eq!(c.state[60], 22 << 1);
541+ // Clip3(1, 126, ...) at a low QP: ctxIdx 6, (m, n) = (-28, 127) at
542+ // QP 0 gives 127, clipped to 126 -> pStateIdx 62, valMPS 1.
543+ let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 0).unwrap();
544+ assert_eq!(c.state[6], (62 << 1) | 1);
545+ }
546+
547+ /// The initialisation of 9.3.1.2 reads exactly nine bits after the
548+ /// alignment bits, and every context lands in range.
549+ #[test]
550+ fn engine_initialisation_reads_nine_bits() {
551+ // Header ends mid byte: the alignment bits carry to the boundary, then
552+ // 0b1010_1010_1 is codIOffset.
553+ let data = [0xFF, 0b1010_1010, 0b1000_0000, 0, 0];
554+ let c = Cabac::new(&data, 3, 30).unwrap();
555+ assert_eq!(c.range, 510);
556+ assert_eq!(c.offset, 0b1_0101_0101);
557+ assert!(c.state.iter().all(|&s| s >> 1 < 64));
558+ }
559+}
crates/ec-h264/src/cabac_tables.rsadded+334 -0
@@ -0,0 +1,334 @@
1+//! CABAC tables transcribed from Rec. ITU-T H.264 (V15) clause 9.3.
2+//!
3+//! Only the values an I-slice, frame-coded, 4:2:0 decode reads are here: the
4+//! "I and SI slices" initialisation column (the cabac_init_idc columns exist
5+//! only for P and B slices), the frame-coded significance contexts, and no 8x8
6+//! transform categories. A later inter slice adds its own columns against its
7+//! own conformance oracle rather than inheriting untested numbers from here.
8+
9+/// Table 9-12, ctxIdx 0..10: mb_type in I slices.
10+pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [
11+ (20, -15),
12+ (2, 54),
13+ (3, 74),
14+ (20, -15),
15+ (2, 54),
16+ (3, 74),
17+ (-28, 127),
18+ (-23, 104),
19+ (-6, 53),
20+ (-1, 54),
21+ (7, 51),
22+];
23+
24+/// Table 9-17, ctxIdx 60..69: mb_qp_delta, intra_chroma_pred_mode and the two
25+/// intra 4x4 prediction mode elements.
26+pub(crate) const INIT_60_69: [(i8, i8); 10] = [
27+ (0, 41),
28+ (0, 63),
29+ (0, 63),
30+ (0, 63),
31+ (-9, 83),
32+ (4, 86),
33+ (0, 97),
34+ (-7, 72),
35+ (13, 41),
36+ (3, 62),
37+];
38+
39+/// Tables 9-18 to 9-21, ctxIdx 70..275, "I and SI slices" column:
40+/// coded_block_pattern, coded_block_flag, significant_coeff_flag,
41+/// last_significant_coeff_flag and coeff_abs_level_minus1.
42+pub(crate) const INIT_70_275: [(i8, i8); 206] = [
43+ (0, 11),
44+ (1, 55),
45+ (0, 69),
46+ (-17, 127),
47+ (-13, 102),
48+ (0, 82),
49+ (-7, 74),
50+ (-21, 107),
51+ (-27, 127),
52+ (-31, 127),
53+ (-24, 127),
54+ (-18, 95),
55+ (-27, 127),
56+ (-21, 114),
57+ (-30, 127),
58+ (-17, 123),
59+ (-12, 115),
60+ (-16, 122),
61+ (-11, 115),
62+ (-12, 63),
63+ (-2, 68),
64+ (-15, 84),
65+ (-13, 104),
66+ (-3, 70),
67+ (-8, 93),
68+ (-10, 90),
69+ (-30, 127),
70+ (-1, 74),
71+ (-6, 97),
72+ (-7, 91),
73+ (-20, 127),
74+ (-4, 56),
75+ (-5, 82),
76+ (-7, 76),
77+ (-22, 125),
78+ (-7, 93),
79+ (-11, 87),
80+ (-3, 77),
81+ (-5, 71),
82+ (-4, 63),
83+ (-4, 68),
84+ (-12, 84),
85+ (-7, 62),
86+ (-7, 65),
87+ (8, 61),
88+ (5, 56),
89+ (-2, 66),
90+ (1, 64),
91+ (0, 61),
92+ (-2, 78),
93+ (1, 50),
94+ (7, 52),
95+ (10, 35),
96+ (0, 44),
97+ (11, 38),
98+ (1, 45),
99+ (0, 46),
100+ (5, 44),
101+ (31, 17),
102+ (1, 51),
103+ (7, 50),
104+ (28, 19),
105+ (16, 33),
106+ (14, 62),
107+ (-13, 108),
108+ (-15, 100),
109+ (-13, 101),
110+ (-13, 91),
111+ (-12, 94),
112+ (-10, 88),
113+ (-16, 84),
114+ (-10, 86),
115+ (-7, 83),
116+ (-13, 87),
117+ (-19, 94),
118+ (1, 70),
119+ (0, 72),
120+ (-5, 74),
121+ (18, 59),
122+ (-8, 102),
123+ (-15, 100),
124+ (0, 95),
125+ (-4, 75),
126+ (2, 72),
127+ (-11, 75),
128+ (-3, 71),
129+ (15, 46),
130+ (-13, 69),
131+ (0, 62),
132+ (0, 65),
133+ (21, 37),
134+ (-15, 72),
135+ (9, 57),
136+ (16, 54),
137+ (0, 62),
138+ (12, 72),
139+ (24, 0),
140+ (15, 9),
141+ (8, 25),
142+ (13, 18),
143+ (15, 9),
144+ (13, 19),
145+ (10, 37),
146+ (12, 18),
147+ (6, 29),
148+ (20, 33),
149+ (15, 30),
150+ (4, 45),
151+ (1, 58),
152+ (0, 62),
153+ (7, 61),
154+ (12, 38),
155+ (11, 45),
156+ (15, 39),
157+ (11, 42),
158+ (13, 44),
159+ (16, 45),
160+ (12, 41),
161+ (10, 49),
162+ (30, 34),
163+ (18, 42),
164+ (10, 55),
165+ (17, 51),
166+ (17, 46),
167+ (0, 89),
168+ (26, -19),
169+ (22, -17),
170+ (26, -17),
171+ (30, -25),
172+ (28, -20),
173+ (33, -23),
174+ (37, -27),
175+ (33, -23),
176+ (40, -28),
177+ (38, -17),
178+ (33, -11),
179+ (40, -15),
180+ (41, -6),
181+ (38, 1),
182+ (41, 17),
183+ (30, -6),
184+ (27, 3),
185+ (26, 22),
186+ (37, -16),
187+ (35, -4),
188+ (38, -8),
189+ (38, -3),
190+ (37, 3),
191+ (38, 5),
192+ (42, 0),
193+ (35, 16),
194+ (39, 22),
195+ (14, 48),
196+ (27, 37),
197+ (21, 60),
198+ (12, 68),
199+ (2, 97),
200+ (-3, 71),
201+ (-6, 42),
202+ (-5, 50),
203+ (-3, 54),
204+ (-2, 62),
205+ (0, 58),
206+ (1, 63),
207+ (-2, 72),
208+ (-1, 74),
209+ (-9, 91),
210+ (-5, 67),
211+ (-5, 27),
212+ (-3, 39),
213+ (-2, 44),
214+ (0, 46),
215+ (-16, 64),
216+ (-8, 68),
217+ (-10, 78),
218+ (-6, 77),
219+ (-10, 86),
220+ (-12, 92),
221+ (-15, 55),
222+ (-10, 60),
223+ (-6, 62),
224+ (-4, 65),
225+ (-12, 73),
226+ (-8, 76),
227+ (-7, 80),
228+ (-9, 88),
229+ (-17, 110),
230+ (-11, 97),
231+ (-20, 84),
232+ (-11, 79),
233+ (-6, 73),
234+ (-4, 74),
235+ (-13, 86),
236+ (-13, 96),
237+ (-11, 97),
238+ (-19, 117),
239+ (-8, 78),
240+ (-5, 33),
241+ (-4, 48),
242+ (-2, 53),
243+ (-3, 62),
244+ (-13, 71),
245+ (-10, 79),
246+ (-12, 86),
247+ (-13, 90),
248+ (-14, 97),
249+];
250+
251+/// Table 9-16, ctxIdx 399..401: transform_size_8x8_flag.
252+pub(crate) const INIT_399_401: [(i8, i8); 3] = [(31, 21), (31, 31), (25, 50)];
253+
254+/// Table 9-44: rangeTabLPS[pStateIdx][qCodIRangeIdx].
255+pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [
256+ [128, 176, 208, 240],
257+ [128, 167, 197, 227],
258+ [128, 158, 187, 216],
259+ [123, 150, 178, 205],
260+ [116, 142, 169, 195],
261+ [111, 135, 160, 185],
262+ [105, 128, 152, 175],
263+ [100, 122, 144, 166],
264+ [95, 116, 137, 158],
265+ [90, 110, 130, 150],
266+ [85, 104, 123, 142],
267+ [81, 99, 117, 135],
268+ [77, 94, 111, 128],
269+ [73, 89, 105, 122],
270+ [69, 85, 100, 116],
271+ [66, 80, 95, 110],
272+ [62, 76, 90, 104],
273+ [59, 72, 86, 99],
274+ [56, 69, 81, 94],
275+ [53, 65, 77, 89],
276+ [51, 62, 73, 85],
277+ [48, 59, 69, 80],
278+ [46, 56, 66, 76],
279+ [43, 53, 63, 72],
280+ [41, 50, 59, 69],
281+ [39, 48, 56, 65],
282+ [37, 45, 54, 62],
283+ [35, 43, 51, 59],
284+ [33, 41, 48, 56],
285+ [32, 39, 46, 53],
286+ [30, 37, 43, 50],
287+ [29, 35, 41, 48],
288+ [27, 33, 39, 45],
289+ [26, 31, 37, 43],
290+ [24, 30, 35, 41],
291+ [23, 28, 33, 39],
292+ [22, 27, 32, 37],
293+ [21, 26, 30, 35],
294+ [20, 24, 29, 33],
295+ [19, 23, 27, 31],
296+ [18, 22, 26, 30],
297+ [17, 21, 25, 28],
298+ [16, 20, 23, 27],
299+ [15, 19, 22, 25],
300+ [14, 18, 21, 24],
301+ [14, 17, 20, 23],
302+ [13, 16, 19, 22],
303+ [12, 15, 18, 21],
304+ [12, 14, 17, 20],
305+ [11, 14, 16, 19],
306+ [11, 13, 15, 18],
307+ [10, 12, 15, 17],
308+ [10, 12, 14, 16],
309+ [9, 11, 13, 15],
310+ [9, 11, 12, 14],
311+ [8, 10, 12, 14],
312+ [8, 9, 11, 13],
313+ [7, 9, 11, 12],
314+ [7, 9, 10, 12],
315+ [7, 8, 10, 11],
316+ [6, 8, 9, 11],
317+ [6, 7, 9, 10],
318+ [6, 7, 8, 9],
319+ [2, 2, 2, 2],
320+];
321+
322+/// Table 9-45: transIdxLPS.
323+pub(crate) const TRANS_LPS: [u8; 64] = [
324+ 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21,
325+ 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34,
326+ 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
327+];
328+
329+/// Table 9-45: transIdxMPS.
330+pub(crate) const TRANS_MPS: [u8; 64] = [
331+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
332+ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
333+ 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
334+];
crates/ec-h264/src/decoder.rsmodified+52 -18
@@ -22,7 +22,9 @@ use ec_h264_syntax::{
22 use crate::deblock::{22 use crate::deblock::{
23 chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,23 chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,
24 };24 };
25-use crate::entropy::{BlockCat, Entropy};25+use crate::entropy::{
26+ BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo,
27+};
26 use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};28 use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
27 use crate::tables::{BLK4_POS, CHROMA_QP};29 use crate::tables::{BLK4_POS, CHROMA_QP};
28 use crate::transform::{30 use crate::transform::{
@@ -121,8 +123,14 @@ struct Picture {
121 i4_modes: Vec<u8>,123 i4_modes: Vec<u8>,
122 /// QPY per macroblock (the prediction-chain value; PCM keeps the chain).124 /// QPY per macroblock (the prediction-chain value; PCM keeps the chain).
123 mb_qp: Vec<u8>,125 mb_qp: Vec<u8>,
124- /// Bit 0: decoded, bit 1: I_PCM, bit 2: Intra_16x16.126+ /// `FLAG_*` bits per macroblock.
125 mb_flags: Vec<u8>,127 mb_flags: Vec<u8>,
128+ /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock,
129+ /// read by CABAC context selection (9.3.3.1.1.4).
130+ mb_cbp: Vec<u8>,
131+ /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb,
132+ /// 2 Cr (9.3.3.1.1.9 with ctxBlockCat 0 and 3).
133+ mb_dc_cbf: Vec<u8>,
126 /// Owning slice index per macroblock, `NO_SLICE` when undecoded.134 /// Owning slice index per macroblock, `NO_SLICE` when undecoded.
127 mb_slice: Vec<u16>,135 mb_slice: Vec<u16>,
128 slices: Vec<SliceParams>,136 slices: Vec<SliceParams>,
@@ -130,9 +138,6 @@ struct Picture {
130 complete: bool,138 complete: bool,
131 }139 }
132 140
133-const FLAG_DECODED: u8 = 1;
134-const FLAG_PCM: u8 = 2;
135-
136 impl Picture {141 impl Picture {
137 fn start(&mut self, sps: &Sps) {142 fn start(&mut self, sps: &Sps) {
138 let mb_w = sps.mb_width as usize;143 let mb_w = sps.mb_width as usize;
@@ -151,6 +156,8 @@ impl Picture {
151 self.i4_modes.resize(mb_w * mb_h * 16, 2);156 self.i4_modes.resize(mb_w * mb_h * 16, 2);
152 self.mb_qp.resize(mb_w * mb_h, 0);157 self.mb_qp.resize(mb_w * mb_h, 0);
153 self.mb_flags.resize(mb_w * mb_h, 0);158 self.mb_flags.resize(mb_w * mb_h, 0);
159+ self.mb_cbp.resize(mb_w * mb_h, 0);
160+ self.mb_dc_cbf.resize(mb_w * mb_h, 0);
154 self.mb_slice.resize(mb_w * mb_h, NO_SLICE);161 self.mb_slice.resize(mb_w * mb_h, NO_SLICE);
155 }162 }
156 // Per-MB metadata is rewritten by each decoded macroblock; only the163 // Per-MB metadata is rewritten by each decoded macroblock; only the
@@ -407,7 +414,11 @@ impl Decoder {
407 cr_qp_offset: pps.second_chroma_qp_index_offset,414 cr_qp_offset: pps.second_chroma_qp_index_offset,
408 });415 });
409 416
410- let mut r = Entropy::cavlc(rbsp, sh.header_bits);417+ let mut r = if pps.entropy_coding_mode {
418+ Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp)?
419+ } else {
420+ Entropy::cavlc(rbsp, sh.header_bits)
421+ };
411 422
412 let mut ctx = SliceCtx {423 let mut ctx = SliceCtx {
413 slice_id,424 slice_id,
@@ -415,6 +426,7 @@ impl Decoder {
415 cb_qp_offset: pps.chroma_qp_index_offset,426 cb_qp_offset: pps.chroma_qp_index_offset,
416 cr_qp_offset: pps.second_chroma_qp_index_offset,427 cr_qp_offset: pps.second_chroma_qp_index_offset,
417 transform_8x8_mode: pps.transform_8x8_mode,428 transform_8x8_mode: pps.transform_8x8_mode,
429+ qp_delta_inc: 0,
418 };430 };
419 let mbs = self.pic.mb_w * self.pic.mb_h;431 let mbs = self.pic.mb_w * self.pic.mb_h;
420 let mut mb_addr = first_mb as usize;432 let mut mb_addr = first_mb as usize;
@@ -439,13 +451,6 @@ impl Decoder {
439 /// conformance suite proves each one against a stream that really uses the451 /// conformance suite proves each one against a stream that really uses the
440 /// feature.452 /// feature.
441 fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {453 fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {
442- if pps.entropy_coding_mode {
443- return Err(Error::unsupported(
444- "CABAC entropy coding",
445- "entropy_coding_mode_flag 1 needs the arithmetic decoder and the \
446- context models of clause 9.3; only CAVLC (9.2) is implemented",
447- ));
448- }
449 if pps.num_slice_groups > 1 {454 if pps.num_slice_groups > 1 {
450 return Err(Error::unsupported(455 return Err(Error::unsupported(
451 "FMO slice groups",456 "FMO slice groups",
@@ -507,6 +512,9 @@ struct SliceCtx {
507 cb_qp_offset: i32,512 cb_qp_offset: i32,
508 cr_qp_offset: i32,513 cr_qp_offset: i32,
509 transform_8x8_mode: bool,514 transform_8x8_mode: bool,
515+ /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the
516+ /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5).
517+ qp_delta_inc: u8,
510 }518 }
511 519
512 /// Neighbour-availability snapshot for one macroblock (left, top,520 /// Neighbour-availability snapshot for one macroblock (left, top,
@@ -581,6 +589,16 @@ fn decode_macroblock(
581 return Err(Error::corrupt("macroblock decoded twice"));589 return Err(Error::corrupt("macroblock decoded twice"));
582 }590 }
583 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);591 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
592+ let info = |addr: usize| MbInfo {
593+ flags: pic.mb_flags[addr],
594+ cbp: pic.mb_cbp[addr],
595+ dc_cbf: pic.mb_dc_cbf[addr],
596+ };
597+ r.begin_mb(&MbCtx {
598+ a: nbr.a.then(|| info(mb_addr - 1)),
599+ b: nbr.b.then(|| info(mb_addr - pic.mb_w)),
600+ qp_delta_inc: ctx.qp_delta_inc,
601+ });
584 let w4 = pic.mb_w * 4;602 let w4 = pic.mb_w * 4;
585 let w2 = pic.mb_w * 2;603 let w2 = pic.mb_w * 2;
586 let (bx0, by0) = (mb_x * 4, mb_y * 4);604 let (bx0, by0) = (mb_x * 4, mb_y * 4);
@@ -617,6 +635,9 @@ fn decode_macroblock(
617 // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2).635 // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2).
618 pic.mb_qp[mb_addr] = ctx.qp as u8;636 pic.mb_qp[mb_addr] = ctx.qp as u8;
619 pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM;637 pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM;
638+ pic.mb_cbp[mb_addr] = 0x3F;
639+ pic.mb_dc_cbf[mb_addr] = 0b111;
640+ ctx.qp_delta_inc = 0;
620 pic.mb_slice[mb_addr] = ctx.slice_id;641 pic.mb_slice[mb_addr] = ctx.slice_id;
621 pic.decoded_mbs += 1;642 pic.decoded_mbs += 1;
622 return Ok(());643 return Ok(());
@@ -684,12 +705,21 @@ fn decode_macroblock(
684 };705 };
685 706
686 // mb_qp_delta (7.4.5).707 // mb_qp_delta (7.4.5).
708+ let mut qp_delta = 0;
687 if cbp_luma != 0 || cbp_chroma != 0 || is_i16 {709 if cbp_luma != 0 || cbp_chroma != 0 || is_i16 {
688- let delta = r.mb_qp_delta()?;710+ qp_delta = r.mb_qp_delta()?;
689- ctx.qp = (ctx.qp + delta + 52) % 52;711+ ctx.qp = (ctx.qp + qp_delta + 52) % 52;
690 }712 }
713+ ctx.qp_delta_inc = u8::from(qp_delta != 0);
691 pic.mb_qp[mb_addr] = ctx.qp as u8;714 pic.mb_qp[mb_addr] = ctx.qp as u8;
692- pic.mb_flags[mb_addr] = FLAG_DECODED;715+ pic.mb_flags[mb_addr] = FLAG_DECODED
716+ | if is_i16 { FLAG_I16 } else { 0 }
717+ | if chroma_mode != 0 {
718+ FLAG_CHROMA_PRED
719+ } else {
720+ 0
721+ };
722+ pic.mb_cbp[mb_addr] = cbp_luma | (cbp_chroma << 4);
693 pic.mb_slice[mb_addr] = ctx.slice_id;723 pic.mb_slice[mb_addr] = ctx.slice_id;
694 pic.decoded_mbs += 1;724 pic.decoded_mbs += 1;
695 let qp_y = ctx.qp;725 let qp_y = ctx.qp;
@@ -702,6 +732,7 @@ fn decode_macroblock(
702 // AC) equals reconstruction dependency order, so each block reconstructs732 // AC) equals reconstruction dependency order, so each block reconstructs
703 // the moment its levels are parsed: no per-MB coefficient arrays, and733 // the moment its levels are parsed: no per-MB coefficient arrays, and
704 // empty blocks cost one coeff_token read plus a prediction write.734 // empty blocks cost one coeff_token read plus a prediction write.
735+ let mut dc_cbf = 0u8;
705 let mut scan = [0i32; 16];736 let mut scan = [0i32; 16];
706 let mut raster = [0i32; 16];737 let mut raster = [0i32; 16];
707 let mut resid = [0i32; 16];738 let mut resid = [0i32; 16];
@@ -714,7 +745,8 @@ fn decode_macroblock(
714 pred_16x16(i16_mode, &mut w, nbr.b, nbr.a);745 pred_16x16(i16_mode, &mut w, nbr.b, nbr.a);
715 // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.746 // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
716 let (na, nb) = luma_nz_pair(pic, &nbr, bx0, by0);747 let (na, nb) = luma_nz_pair(pic, &nbr, bx0, by0);
717- r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?;748+ let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?;
749+ dc_cbf |= u8::from(dc_tc != 0);
718 unzigzag(&scan, &mut raster);750 unzigzag(&scan, &mut raster);
719 luma_dc_transform(&mut raster, &ls[0], qp_y);751 luma_dc_transform(&mut raster, &ls[0], qp_y);
720 let dc = raster;752 let dc = raster;
@@ -798,7 +830,8 @@ fn decode_macroblock(
798 let mut chroma_dc = [[0i32; 4]; 2];830 let mut chroma_dc = [[0i32; 4]; 2];
799 if cbp_chroma != 0 {831 if cbp_chroma != 0 {
800 for (comp, c) in chroma_dc.iter_mut().enumerate() {832 for (comp, c) in chroma_dc.iter_mut().enumerate() {
801- r.residual_block(&mut scan, BlockCat::ChromaDc, None, None)?;833+ let tc = r.residual_block(&mut scan, BlockCat::ChromaDc(comp as u8), None, None)?;
834+ dc_cbf |= u8::from(tc != 0) << (1 + comp);
802 c.copy_from_slice(&scan[..4]);835 c.copy_from_slice(&scan[..4]);
803 let (ls_c, qp_c) = if comp == 0 {836 let (ls_c, qp_c) = if comp == 0 {
804 (&ls[1], qp_cb)837 (&ls[1], qp_cb)
@@ -842,6 +875,7 @@ fn decode_macroblock(
842 add_residual_4x4(&mut plane.data, plane.stride, origin, &resid);875 add_residual_4x4(&mut plane.data, plane.stride, origin, &resid);
843 }876 }
844 }877 }
878+ pic.mb_dc_cbf[mb_addr] = dc_cbf;
845 Ok(())879 Ok(())
846 }880 }
847 881
crates/ec-h264/src/entropy.rsmodified+80 -4
@@ -19,8 +19,20 @@
19 use ec_core::error::{Error, Result};19 use ec_core::error::{Error, Result};
20 20
21 use crate::bits::BitCursor;21 use crate::bits::BitCursor;
22+use crate::cabac::Cabac;
22 use crate::tables::CBP_INTRA_420;23 use crate::tables::CBP_INTRA_420;
23 24
25+/// Macroblock state bits (`Picture::mb_flags`, and `MbInfo::flags` for a
26+/// neighbour). CABAC context selection reads all of them.
27+/// The macroblock has been decoded in this picture.
28+pub(crate) const FLAG_DECODED: u8 = 1;
29+/// mb_type is I_PCM.
30+pub(crate) const FLAG_PCM: u8 = 2;
31+/// mb_type is one of the Intra_16x16 types.
32+pub(crate) const FLAG_I16: u8 = 4;
33+/// intra_chroma_pred_mode is not 0 (DC).
34+pub(crate) const FLAG_CHROMA_PRED: u8 = 8;
35+
24 /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes).36 /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes).
25 #[derive(Clone, Copy, PartialEq, Eq, Debug)]37 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
26 pub(crate) enum BlockCat {38 pub(crate) enum BlockCat {
@@ -30,8 +42,8 @@ pub(crate) enum BlockCat {
30 LumaAc,42 LumaAc,
31 /// LumaLevel4x4, `ctxBlockCat` 2.43 /// LumaLevel4x4, `ctxBlockCat` 2.
32 Luma4x4,44 Luma4x4,
33- /// ChromaDCLevel, `ctxBlockCat` 3.45+ /// ChromaDCLevel of component `iCbCr`, `ctxBlockCat` 3.
34- ChromaDc,46+ ChromaDc(u8),
35 /// ChromaACLevel, `ctxBlockCat` 4.47 /// ChromaACLevel, `ctxBlockCat` 4.
36 ChromaAc,48 ChromaAc,
37 }49 }
@@ -42,14 +54,55 @@ impl BlockCat {
42 match self {54 match self {
43 BlockCat::LumaDc | BlockCat::Luma4x4 => 16,55 BlockCat::LumaDc | BlockCat::Luma4x4 => 16,
44 BlockCat::LumaAc | BlockCat::ChromaAc => 15,56 BlockCat::LumaAc | BlockCat::ChromaAc => 15,
45- BlockCat::ChromaDc => 4,57+ BlockCat::ChromaDc(_) => 4,
58+ }
59+ }
60+
61+ /// `ctxBlockCat` (Table 9-42).
62+ pub(crate) const fn ctx_block_cat(self) -> usize {
63+ match self {
64+ BlockCat::LumaDc => 0,
65+ BlockCat::LumaAc => 1,
66+ BlockCat::Luma4x4 => 2,
67+ BlockCat::ChromaDc(_) => 3,
68+ BlockCat::ChromaAc => 4,
69+ }
46 }70 }
47 }71 }
72+
73+/// What a context-adaptive reader needs to know about one neighbouring
74+/// macroblock.
75+#[derive(Clone, Copy)]
76+pub(crate) struct MbInfo {
77+ /// The `FLAG_*` bits above.
78+ pub flags: u8,
79+ /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4`.
80+ pub cbp: u8,
81+ /// coded_block_flag of the DC blocks: bit 0 luma, bit 1 Cb, bit 2 Cr.
82+ pub dc_cbf: u8,
83+}
84+
85+/// Neighbourhood of the macroblock about to be parsed: left (A) and above (B)
86+/// per clause 6.4.11.1, `None` when outside the picture or in another slice.
87+#[derive(Clone, Copy, Default)]
88+pub(crate) struct MbCtx {
89+ pub a: Option<MbInfo>,
90+ pub b: Option<MbInfo>,
91+ /// ctxIdxInc for the first mb_qp_delta bin (clause 9.3.3.1.1.5), derived by
92+ /// the caller from the previous macroblock in decoding order.
93+ pub qp_delta_inc: u8,
48 }94 }
49 95
50 /// The slice-data syntax reader.96 /// The slice-data syntax reader.
97+///
98+/// The CABAC variant is much the larger of the two (it carries 402 context
99+/// variables), and stays inline on purpose: one of these lives per slice on the
100+/// stack, so boxing it would trade a compile-time size warning for a heap
101+/// allocation in a decode loop that is otherwise allocation free.
102+#[allow(clippy::large_enum_variant)]
51 pub(crate) enum Entropy<'a> {103 pub(crate) enum Entropy<'a> {
52 Cavlc(BitCursor<'a>),104 Cavlc(BitCursor<'a>),
105+ Cabac(Cabac<'a>),
53 }106 }
54 107
55 impl<'a> Entropy<'a> {108 impl<'a> Entropy<'a> {
@@ -58,6 +111,20 @@ impl<'a> Entropy<'a> {
58 Entropy::Cavlc(BitCursor::new(rbsp, header_bits))111 Entropy::Cavlc(BitCursor::new(rbsp, header_bits))
59 }112 }
60 113
114+ /// A CABAC reader: consumes the `cabac_alignment_one_bit`s and initialises
115+ /// the context variables and the arithmetic decoding engine (clause 9.3.1).
116+ pub(crate) fn cabac(rbsp: &'a [u8], header_bits: u64, slice_qp: i32) -> Result<Entropy<'a>> {
117+ Ok(Entropy::Cabac(Cabac::new(rbsp, header_bits, slice_qp)?))
118+ }
119+
120+ /// Publish the neighbourhood of the macroblock about to be parsed.
121+ #[inline]
122+ pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) {
123+ if let Entropy::Cabac(c) = self {
124+ c.begin_mb(ctx);
125+ }
126+ }
127+
61 /// `mb_type` of an I slice: 0 (I_NxN), 1..24 (Intra_16x16), 25 (I_PCM).128 /// `mb_type` of an I slice: 0 (I_NxN), 1..24 (Intra_16x16), 25 (I_PCM).
62 pub(crate) fn mb_type_i(&mut self) -> Result<u32> {129 pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
63 match self {130 match self {
@@ -68,6 +135,7 @@ impl<'a> Entropy<'a> {
68 }135 }
69 Ok(t)136 Ok(t)
70 }137 }
138+ Entropy::Cabac(c) => c.mb_type_i(),
71 }139 }
72 }140 }
73 141
@@ -75,6 +143,7 @@ impl<'a> Entropy<'a> {
75 pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {143 pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
76 match self {144 match self {
77 Entropy::Cavlc(r) => r.read_bit(),145 Entropy::Cavlc(r) => r.read_bit(),
146+ Entropy::Cabac(c) => c.transform_size_8x8_flag(),
78 }147 }
79 }148 }
80 149
@@ -90,6 +159,7 @@ impl<'a> Entropy<'a> {
90 Ok(Some(r.read_bits(3)? as u8))159 Ok(Some(r.read_bits(3)? as u8))
91 }160 }
92 }161 }
162+ Entropy::Cabac(c) => c.intra4x4_pred_mode(),
93 }163 }
94 }164 }
95 165
@@ -103,6 +173,7 @@ impl<'a> Entropy<'a> {
103 }173 }
104 Ok(m as u8)174 Ok(m as u8)
105 }175 }
176+ Entropy::Cabac(c) => c.intra_chroma_pred_mode(),
106 }177 }
107 }178 }
108 179
@@ -118,6 +189,7 @@ impl<'a> Entropy<'a> {
118 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;189 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;
119 Ok((cbp & 15, cbp >> 4))190 Ok((cbp & 15, cbp >> 4))
120 }191 }
192+ Entropy::Cabac(c) => c.coded_block_pattern(),
121 }193 }
122 }194 }
123 195
@@ -125,6 +197,7 @@ impl<'a> Entropy<'a> {
125 pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {197 pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
126 let delta = match self {198 let delta = match self {
127 Entropy::Cavlc(r) => r.read_se()?,199 Entropy::Cavlc(r) => r.read_se()?,
200+ Entropy::Cabac(c) => c.mb_qp_delta()?,
128 };201 };
129 if !(-26..=25).contains(&delta) {202 if !(-26..=25).contains(&delta) {
130 return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));203 return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
@@ -149,7 +222,7 @@ impl<'a> Entropy<'a> {
149 ) -> Result<u8> {222 ) -> Result<u8> {
150 match self {223 match self {
151 Entropy::Cavlc(r) => {224 Entropy::Cavlc(r) => {
152- let nc = if cat == BlockCat::ChromaDc {225+ let nc = if matches!(cat, BlockCat::ChromaDc(_)) {
153 -1226 -1
154 } else {227 } else {
155 match (na, nb) {228 match (na, nb) {
@@ -161,6 +234,7 @@ impl<'a> Entropy<'a> {
161 };234 };
162 crate::cavlc::residual_block(r, coeff, cat.max_num_coeff(), nc)235 crate::cavlc::residual_block(r, coeff, cat.max_num_coeff(), nc)
163 }236 }
237+ Entropy::Cabac(c) => c.residual_block(coeff, cat, na, nb),
164 }238 }
165 }239 }
166 240
@@ -173,6 +247,7 @@ impl<'a> Entropy<'a> {
173 r.align_to_byte();247 r.align_to_byte();
174 r.read_bytes(384)248 r.read_bytes(384)
175 }249 }
250+ Entropy::Cabac(c) => c.pcm_block(),
176 }251 }
177 }252 }
178 253
@@ -181,6 +256,7 @@ impl<'a> Entropy<'a> {
181 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {256 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
182 match self {257 match self {
183 Entropy::Cavlc(r) => Ok(r.more_rbsp_data()),258 Entropy::Cavlc(r) => Ok(r.more_rbsp_data()),
259+ Entropy::Cabac(c) => c.more_macroblocks(),
184 }260 }
185 }261 }
186 }262 }
crates/ec-h264/src/lib.rsmodified+2 -0
@@ -31,6 +31,8 @@
31 #![forbid(unsafe_code)]31 #![forbid(unsafe_code)]
32 32
33 mod bits;33 mod bits;
34+mod cabac;
35+mod cabac_tables;
34 mod cavlc;36 mod cavlc;
35 mod codec;37 mod codec;
36 mod deblock;38 mod deblock;
crates/ec-h264/tests/conformance.rsmodified+14 -3
@@ -624,10 +624,21 @@ fn refusals_name_a_feature_the_stream_really_uses() {
624 let dir = scratch("refusals");624 let dir = scratch("refusals");
625 // (tag, encoder arguments, the words the refusal must contain)625 // (tag, encoder arguments, the words the refusal must contain)
626 let cases: &[(&str, &[&str], &str)] = &[626 let cases: &[(&str, &[&str], &str)] = &[
627+ // Field or macroblock-adaptive frame/field coding: the neighbour
628+ // derivation of 6.4.9 is not implemented, under either entropy coder.
627 (629 (
628- "cabac",630+ "interlaced",
629- &["-profile:v", "main", "-qp", "26", "-x264-params", "cabac=1"],631+ &[
630- "CABAC",632+ "-profile:v",
633+ "main",
634+ "-coder",
635+ "ac",
636+ "-qp",
637+ "26",
638+ "-x264-params",
639+ "interlaced=1",
640+ ],
641+ "frame_mbs_only_flag 0",
631 ),642 ),
632 (643 (
633 "transform8x8",644 "transform8x8",